1 package C4::Acquisition;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 use C4::Dates qw(format_date format_date_in_iso);
31 use C4::SQLHelper qw(InsertInTable);
32 use C4::Bookseller qw(GetBookSellerFromId);
33 use C4::Templates qw(gettemplate);
38 use vars qw($VERSION @ISA @EXPORT);
41 # set the version for version checking
42 $VERSION = 3.07.00.049;
46 &GetBasket &NewBasket &CloseBasket &DelBasket &ModBasket
47 &GetBasketAsCSV &GetBasketGroupAsCSV
48 &GetBasketsByBookseller &GetBasketsByBasketgroup
49 &GetBasketsInfosByBookseller
53 &ModBasketgroup &NewBasketgroup &DelBasketgroup &GetBasketgroup &CloseBasketgroup
54 &GetBasketgroups &ReOpenBasketgroup
56 &NewOrder &DelOrder &ModOrder &GetPendingOrders &GetOrder &GetOrders
57 &GetOrderNumber &GetLateOrders &GetOrderFromItemnumber
58 &SearchOrder &GetHistory &GetRecentAcqui
59 &ModReceiveOrder &CancelReceipt &ModOrderBiblioitemNumber
62 &NewOrderItem &ModOrderItem &ModItemOrder
64 &GetParcels &GetParcel
65 &GetContracts &GetContract
75 &GetItemnumbersFromOrder
85 sub GetOrderFromItemnumber {
86 my ($itemnumber) = @_;
87 my $dbh = C4::Context->dbh;
90 SELECT * from aqorders LEFT JOIN aqorders_items
91 ON ( aqorders.ordernumber = aqorders_items.ordernumber )
92 WHERE itemnumber = ? |;
94 my $sth = $dbh->prepare($query);
98 $sth->execute($itemnumber);
100 my $order = $sth->fetchrow_hashref;
105 # Returns the itemnumber(s) associated with the ordernumber given in parameter
106 sub GetItemnumbersFromOrder {
107 my ($ordernumber) = @_;
108 my $dbh = C4::Context->dbh;
109 my $query = "SELECT itemnumber FROM aqorders_items WHERE ordernumber=?";
110 my $sth = $dbh->prepare($query);
111 $sth->execute($ordernumber);
114 while (my $order = $sth->fetchrow_hashref) {
115 push @tab, $order->{'itemnumber'};
129 C4::Acquisition - Koha functions for dealing with orders and acquisitions
137 The functions in this module deal with acquisitions, managing book
138 orders, basket and parcels.
142 =head2 FUNCTIONS ABOUT BASKETS
146 $aqbasket = &GetBasket($basketnumber);
148 get all basket informations in aqbasket for a given basket
150 B<returns:> informations for a given basket returned as a hashref.
156 my $dbh = C4::Context->dbh;
159 concat( b.firstname,' ',b.surname) AS authorisedbyname,
160 b.branchcode AS branch
162 LEFT JOIN borrowers b ON aqbasket.authorisedby=b.borrowernumber
165 my $sth=$dbh->prepare($query);
166 $sth->execute($basketno);
167 my $basket = $sth->fetchrow_hashref;
171 #------------------------------------------------------------#
175 $basket = &NewBasket( $booksellerid, $authorizedby, $basketname,
176 $basketnote, $basketbooksellernote, $basketcontractnumber, $deliveryplace, $billingplace );
178 Create a new basket in aqbasket table
182 =item C<$booksellerid> is a foreign key in the aqbasket table
184 =item C<$authorizedby> is the username of who created the basket
188 The other parameters are optional, see ModBasketHeader for more info on them.
193 my ( $booksellerid, $authorisedby, $basketname, $basketnote,
194 $basketbooksellernote, $basketcontractnumber, $deliveryplace,
195 $billingplace ) = @_;
196 my $dbh = C4::Context->dbh;
198 'INSERT INTO aqbasket (creationdate,booksellerid,authorisedby) '
199 . 'VALUES (now(),?,?)';
200 $dbh->do( $query, {}, $booksellerid, $authorisedby );
202 my $basket = $dbh->{mysql_insertid};
203 $basketname ||= q{}; # default to empty strings
205 $basketbooksellernote ||= q{};
206 ModBasketHeader( $basket, $basketname, $basketnote, $basketbooksellernote,
207 $basketcontractnumber, $booksellerid, $deliveryplace, $billingplace );
211 #------------------------------------------------------------#
215 &CloseBasket($basketno);
217 close a basket (becomes unmodifiable,except for recieves)
223 my $dbh = C4::Context->dbh;
229 my $sth = $dbh->prepare($query);
230 $sth->execute($basketno);
233 #------------------------------------------------------------#
235 =head3 GetBasketAsCSV
237 &GetBasketAsCSV($basketno);
239 Export a basket as CSV
241 $cgi parameter is needed for column name translation
246 my ($basketno, $cgi) = @_;
247 my $basket = GetBasket($basketno);
248 my @orders = GetOrders($basketno);
249 my $contract = GetContract($basket->{'contractnumber'});
251 my $template = C4::Templates::gettemplate("acqui/csv/basket.tmpl", "intranet", $cgi);
254 foreach my $order (@orders) {
255 my $bd = GetBiblioData( $order->{'biblionumber'} );
257 contractname => $contract->{'contractname'},
258 ordernumber => $order->{'ordernumber'},
259 entrydate => $order->{'entrydate'},
260 isbn => $order->{'isbn'},
261 author => $bd->{'author'},
262 title => $bd->{'title'},
263 publicationyear => $bd->{'publicationyear'},
264 publishercode => $bd->{'publishercode'},
265 collectiontitle => $bd->{'collectiontitle'},
266 notes => $order->{'notes'},
267 quantity => $order->{'quantity'},
268 rrp => $order->{'rrp'},
269 deliveryplace => C4::Branch::GetBranchName( $basket->{'deliveryplace'} ),
270 billingplace => C4::Branch::GetBranchName( $basket->{'billingplace'} ),
273 contractname author title publishercode collectiontitle notes
274 deliveryplace billingplace
276 # Double the quotes to not be interpreted as a field end
277 $row->{$_} =~ s/"/""/g if $row->{$_};
283 if(defined $a->{publishercode} and defined $b->{publishercode}) {
284 $a->{publishercode} cmp $b->{publishercode};
288 $template->param(rows => \@rows);
290 return $template->output;
294 =head3 GetBasketGroupAsCSV
298 &GetBasketGroupAsCSV($basketgroupid);
300 Export a basket group as CSV
302 $cgi parameter is needed for column name translation
308 sub GetBasketGroupAsCSV {
309 my ($basketgroupid, $cgi) = @_;
310 my $baskets = GetBasketsByBasketgroup($basketgroupid);
312 my $template = C4::Templates::gettemplate('acqui/csv/basketgroup.tmpl', 'intranet', $cgi);
315 for my $basket (@$baskets) {
316 my @orders = GetOrders( $$basket{basketno} );
317 my $contract = GetContract( $$basket{contractnumber} );
318 my $bookseller = GetBookSellerFromId( $$basket{booksellerid} );
319 my $basketgroup = GetBasketgroup( $$basket{basketgroupid} );
321 foreach my $order (@orders) {
322 my $bd = GetBiblioData( $order->{'biblionumber'} );
324 clientnumber => $bookseller->{accountnumber},
325 basketname => $basket->{basketname},
326 ordernumber => $order->{ordernumber},
327 author => $bd->{author},
328 title => $bd->{title},
329 publishercode => $bd->{publishercode},
330 publicationyear => $bd->{publicationyear},
331 collectiontitle => $bd->{collectiontitle},
332 isbn => $order->{isbn},
333 quantity => $order->{quantity},
334 rrp => $order->{rrp},
335 discount => $bookseller->{discount},
336 ecost => $order->{ecost},
337 notes => $order->{notes},
338 entrydate => $order->{entrydate},
339 booksellername => $bookseller->{name},
340 bookselleraddress => $bookseller->{address1},
341 booksellerpostal => $bookseller->{postal},
342 contractnumber => $contract->{contractnumber},
343 contractname => $contract->{contractname},
344 basketgroupdeliveryplace => C4::Branch::GetBranchName( $basketgroup->{deliveryplace} ),
345 basketgroupbillingplace => C4::Branch::GetBranchName( $basketgroup->{billingplace} ),
346 basketdeliveryplace => C4::Branch::GetBranchName( $basket->{deliveryplace} ),
347 basketbillingplace => C4::Branch::GetBranchName( $basket->{billingplace} ),
350 basketname author title publishercode collectiontitle notes
351 booksellername bookselleraddress booksellerpostal contractname
352 basketgroupdeliveryplace basketgroupbillingplace
353 basketdeliveryplace basketbillingplace
355 # Double the quotes to not be interpreted as a field end
356 $row->{$_} =~ s/"/""/g if $row->{$_};
361 $template->param(rows => \@rows);
363 return $template->output;
367 =head3 CloseBasketgroup
369 &CloseBasketgroup($basketgroupno);
375 sub CloseBasketgroup {
376 my ($basketgroupno) = @_;
377 my $dbh = C4::Context->dbh;
378 my $sth = $dbh->prepare("
379 UPDATE aqbasketgroups
383 $sth->execute($basketgroupno);
386 #------------------------------------------------------------#
388 =head3 ReOpenBaskergroup($basketgroupno)
390 &ReOpenBaskergroup($basketgroupno);
396 sub ReOpenBasketgroup {
397 my ($basketgroupno) = @_;
398 my $dbh = C4::Context->dbh;
399 my $sth = $dbh->prepare("
400 UPDATE aqbasketgroups
404 $sth->execute($basketgroupno);
407 #------------------------------------------------------------#
412 &DelBasket($basketno);
414 Deletes the basket that has basketno field $basketno in the aqbasket table.
418 =item C<$basketno> is the primary key of the basket in the aqbasket table.
425 my ( $basketno ) = @_;
426 my $query = "DELETE FROM aqbasket WHERE basketno=?";
427 my $dbh = C4::Context->dbh;
428 my $sth = $dbh->prepare($query);
429 $sth->execute($basketno);
433 #------------------------------------------------------------#
437 &ModBasket($basketinfo);
439 Modifies a basket, using a hashref $basketinfo for the relevant information, only $basketinfo->{'basketno'} is required.
443 =item C<$basketno> is the primary key of the basket in the aqbasket table.
450 my $basketinfo = shift;
451 my $query = "UPDATE aqbasket SET ";
453 foreach my $key (keys %$basketinfo){
454 if ($key ne 'basketno'){
455 $query .= "$key=?, ";
456 push(@params, $basketinfo->{$key} || undef );
459 # get rid of the "," at the end of $query
460 if (substr($query, length($query)-2) eq ', '){
465 $query .= "WHERE basketno=?";
466 push(@params, $basketinfo->{'basketno'});
467 my $dbh = C4::Context->dbh;
468 my $sth = $dbh->prepare($query);
469 $sth->execute(@params);
473 #------------------------------------------------------------#
475 =head3 ModBasketHeader
477 &ModBasketHeader($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid);
479 Modifies a basket's header.
483 =item C<$basketno> is the "basketno" field in the "aqbasket" table;
485 =item C<$basketname> is the "basketname" field in the "aqbasket" table;
487 =item C<$note> is the "note" field in the "aqbasket" table;
489 =item C<$booksellernote> is the "booksellernote" field in the "aqbasket" table;
491 =item C<$contractnumber> is the "contractnumber" (foreign) key in the "aqbasket" table.
493 =item C<$booksellerid> is the id (foreign) key in the "aqbooksellers" table for the vendor.
495 =item C<$deliveryplace> is the "deliveryplace" field in the aqbasket table.
497 =item C<$billingplace> is the "billingplace" field in the aqbasket table.
503 sub ModBasketHeader {
504 my ($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid, $deliveryplace, $billingplace) = @_;
507 SET basketname=?, note=?, booksellernote=?, booksellerid=?, deliveryplace=?, billingplace=?
511 my $dbh = C4::Context->dbh;
512 my $sth = $dbh->prepare($query);
513 $sth->execute($basketname, $note, $booksellernote, $booksellerid, $deliveryplace, $billingplace, $basketno);
515 if ( $contractnumber ) {
516 my $query2 ="UPDATE aqbasket SET contractnumber=? WHERE basketno=?";
517 my $sth2 = $dbh->prepare($query2);
518 $sth2->execute($contractnumber,$basketno);
524 #------------------------------------------------------------#
526 =head3 GetBasketsByBookseller
528 @results = &GetBasketsByBookseller($booksellerid, $extra);
530 Returns a list of hashes of all the baskets that belong to bookseller 'booksellerid'.
534 =item C<$booksellerid> is the 'id' field of the bookseller in the aqbooksellers table
536 =item C<$extra> is the extra sql parameters, can be
538 $extra->{groupby}: group baskets by column
539 ex. $extra->{groupby} = aqbasket.basketgroupid
540 $extra->{orderby}: order baskets by column
541 $extra->{limit}: limit number of results (can be helpful for pagination)
547 sub GetBasketsByBookseller {
548 my ($booksellerid, $extra) = @_;
549 my $query = "SELECT * FROM aqbasket WHERE booksellerid=?";
551 if ($extra->{groupby}) {
552 $query .= " GROUP by $extra->{groupby}";
554 if ($extra->{orderby}){
555 $query .= " ORDER by $extra->{orderby}";
557 if ($extra->{limit}){
558 $query .= " LIMIT $extra->{limit}";
561 my $dbh = C4::Context->dbh;
562 my $sth = $dbh->prepare($query);
563 $sth->execute($booksellerid);
564 my $results = $sth->fetchall_arrayref({});
569 =head3 GetBasketsInfosByBookseller
571 my $baskets = GetBasketsInfosByBookseller($supplierid);
573 Returns in a arrayref of hashref all about booksellers baskets, plus:
574 total_biblios: Number of distinct biblios in basket
575 total_items: Number of items in basket
576 expected_items: Number of non-received items in basket
580 sub GetBasketsInfosByBookseller {
581 my ($supplierid) = @_;
583 return unless $supplierid;
585 my $dbh = C4::Context->dbh;
588 SUM(aqorders.quantity) AS total_items,
589 COUNT(DISTINCT aqorders.biblionumber) AS total_biblios,
591 IF(aqorders.datereceived IS NULL
592 AND aqorders.datecancellationprinted IS NULL
597 LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
598 WHERE booksellerid = ?
599 GROUP BY aqbasket.basketno
601 my $sth = $dbh->prepare($query);
602 $sth->execute($supplierid);
603 return $sth->fetchall_arrayref({});
607 #------------------------------------------------------------#
609 =head3 GetBasketsByBasketgroup
611 $baskets = &GetBasketsByBasketgroup($basketgroupid);
613 Returns a reference to all baskets that belong to basketgroup $basketgroupid.
617 sub GetBasketsByBasketgroup {
618 my $basketgroupid = shift;
620 SELECT *, aqbasket.booksellerid as booksellerid
622 LEFT JOIN aqcontract USING(contractnumber) WHERE basketgroupid=?
624 my $dbh = C4::Context->dbh;
625 my $sth = $dbh->prepare($query);
626 $sth->execute($basketgroupid);
627 my $results = $sth->fetchall_arrayref({});
632 #------------------------------------------------------------#
634 =head3 NewBasketgroup
636 $basketgroupid = NewBasketgroup(\%hashref);
638 Adds a basketgroup to the aqbasketgroups table, and add the initial baskets to it.
640 $hashref->{'booksellerid'} is the 'id' field of the bookseller in the aqbooksellers table,
642 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
644 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
646 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
648 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
650 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
655 my $basketgroupinfo = shift;
656 die "booksellerid is required to create a basketgroup" unless $basketgroupinfo->{'booksellerid'};
657 my $query = "INSERT INTO aqbasketgroups (";
659 foreach my $field ('name', 'deliveryplace', 'deliverycomment', 'closed') {
660 if ( $basketgroupinfo->{$field} ) {
661 $query .= "$field, ";
662 push(@params, $basketgroupinfo->{$field});
665 $query .= "booksellerid) VALUES (";
670 push(@params, $basketgroupinfo->{'booksellerid'});
671 my $dbh = C4::Context->dbh;
672 my $sth = $dbh->prepare($query);
673 $sth->execute(@params);
674 my $basketgroupid = $dbh->{'mysql_insertid'};
675 if( $basketgroupinfo->{'basketlist'} ) {
676 foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
677 my $query2 = "UPDATE aqbasket SET basketgroupid=? WHERE basketno=?";
678 my $sth2 = $dbh->prepare($query2);
679 $sth2->execute($basketgroupid, $basketno);
682 return $basketgroupid;
685 #------------------------------------------------------------#
687 =head3 ModBasketgroup
689 ModBasketgroup(\%hashref);
691 Modifies a basketgroup in the aqbasketgroups table, and add the baskets to it.
693 $hashref->{'id'} is the 'id' field of the basketgroup in the aqbasketgroup table, this parameter is mandatory,
695 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
697 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
699 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
701 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
703 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
705 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
710 my $basketgroupinfo = shift;
711 die "basketgroup id is required to edit a basketgroup" unless $basketgroupinfo->{'id'};
712 my $dbh = C4::Context->dbh;
713 my $query = "UPDATE aqbasketgroups SET ";
715 foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
716 if ( defined $basketgroupinfo->{$field} ) {
717 $query .= "$field=?, ";
718 push(@params, $basketgroupinfo->{$field});
723 $query .= " WHERE id=?";
724 push(@params, $basketgroupinfo->{'id'});
725 my $sth = $dbh->prepare($query);
726 $sth->execute(@params);
728 $sth = $dbh->prepare('UPDATE aqbasket SET basketgroupid = NULL WHERE basketgroupid = ?');
729 $sth->execute($basketgroupinfo->{'id'});
731 if($basketgroupinfo->{'basketlist'} && @{$basketgroupinfo->{'basketlist'}}){
732 $sth = $dbh->prepare("UPDATE aqbasket SET basketgroupid=? WHERE basketno=?");
733 foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
734 $sth->execute($basketgroupinfo->{'id'}, $basketno);
741 #------------------------------------------------------------#
743 =head3 DelBasketgroup
745 DelBasketgroup($basketgroupid);
747 Deletes a basketgroup in the aqbasketgroups table, and removes the reference to it from the baskets,
751 =item C<$basketgroupid> is the 'id' field of the basket in the aqbasketgroup table
758 my $basketgroupid = shift;
759 die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
760 my $query = "DELETE FROM aqbasketgroups WHERE id=?";
761 my $dbh = C4::Context->dbh;
762 my $sth = $dbh->prepare($query);
763 $sth->execute($basketgroupid);
767 #------------------------------------------------------------#
770 =head2 FUNCTIONS ABOUT ORDERS
772 =head3 GetBasketgroup
774 $basketgroup = &GetBasketgroup($basketgroupid);
776 Returns a reference to the hash containing all infermation about the basketgroup.
781 my $basketgroupid = shift;
782 die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
783 my $query = "SELECT * FROM aqbasketgroups WHERE id=?";
784 my $dbh = C4::Context->dbh;
785 my $sth = $dbh->prepare($query);
786 $sth->execute($basketgroupid);
787 my $result = $sth->fetchrow_hashref;
792 #------------------------------------------------------------#
794 =head3 GetBasketgroups
796 $basketgroups = &GetBasketgroups($booksellerid);
798 Returns a reference to the array of all the basketgroups of bookseller $booksellerid.
802 sub GetBasketgroups {
803 my $booksellerid = shift;
804 die "bookseller id is required to edit a basketgroup" unless $booksellerid;
805 my $query = "SELECT * FROM aqbasketgroups WHERE booksellerid=? ORDER BY `id` DESC";
806 my $dbh = C4::Context->dbh;
807 my $sth = $dbh->prepare($query);
808 $sth->execute($booksellerid);
809 my $results = $sth->fetchall_arrayref({});
814 #------------------------------------------------------------#
816 =head2 FUNCTIONS ABOUT ORDERS
820 #------------------------------------------------------------#
822 =head3 GetPendingOrders
824 $orders = &GetPendingOrders($supplierid,$grouped,$owner,$basketno,$ordernumber,$search,$ean);
826 Finds pending orders from the bookseller with the given ID. Ignores
827 completed and cancelled orders.
829 C<$booksellerid> contains the bookseller identifier
830 C<$owner> contains 0 or 1. 0 means any owner. 1 means only the list of orders entered by the user itself.
831 C<$grouped> is a boolean that, if set to 1 will group all order lines of the same basket
832 in a single result line
833 C<$orders> is a reference-to-array; each element is a reference-to-hash.
835 Used also by the filter in parcel.pl
842 These give the value of the corresponding field in the aqorders table
843 of the Koha database.
845 Results are ordered from most to least recent.
849 sub GetPendingOrders {
850 my ($supplierid,$grouped,$owner,$basketno,$ordernumber,$search,$ean) = @_;
851 my $dbh = C4::Context->dbh;
853 SELECT ".($grouped?"count(*),":"")."aqbasket.basketno,
854 surname,firstname,biblio.*,biblioitems.isbn,
855 aqbasket.closedate, aqbasket.creationdate, aqbasket.basketname,
858 LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
859 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
860 LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
861 LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
862 WHERE (quantity > quantityreceived OR quantityreceived is NULL)
863 AND datecancellationprinted IS NULL";
865 my $userenv = C4::Context->userenv;
866 if ( C4::Context->preference("IndependantBranches") ) {
867 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
868 $strsth .= " AND (borrowers.branchcode = ?
869 or borrowers.branchcode = '')";
870 push @query_params, $userenv->{branch};
874 $strsth .= " AND aqbasket.booksellerid = ?";
875 push @query_params, $supplierid;
878 $strsth .= " AND (aqorders.ordernumber=?)";
879 push @query_params, $ordernumber;
882 $strsth .= " AND (biblio.title like ? OR biblio.author LIKE ? OR biblioitems.isbn like ?)";
883 push @query_params, ("%$search%","%$search%","%$search%");
886 $strsth .= " AND biblioitems.ean = ?";
887 push @query_params, $ean;
890 $strsth .= " AND aqbasket.basketno=? ";
891 push @query_params, $basketno;
894 $strsth .= " AND aqbasket.authorisedby=? ";
895 push @query_params, $userenv->{'number'};
897 $strsth .= " group by aqbasket.basketno" if $grouped;
898 $strsth .= " order by aqbasket.basketno";
899 my $sth = $dbh->prepare($strsth);
900 $sth->execute( @query_params );
901 my $results = $sth->fetchall_arrayref({});
906 #------------------------------------------------------------#
910 @orders = &GetOrders($basketnumber, $orderby);
912 Looks up the pending (non-cancelled) orders with the given basket
913 number. If C<$booksellerID> is non-empty, only orders from that seller
917 C<&basket> returns a two-element array. C<@orders> is an array of
918 references-to-hash, whose keys are the fields from the aqorders,
919 biblio, and biblioitems tables in the Koha database.
924 my ( $basketno, $orderby ) = @_;
925 my $dbh = C4::Context->dbh;
927 SELECT biblio.*,biblioitems.*,
932 LEFT JOIN aqbudgets ON aqbudgets.budget_id = aqorders.budget_id
933 LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
934 LEFT JOIN biblioitems ON biblioitems.biblionumber =biblio.biblionumber
936 AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
939 $orderby = "biblioitems.publishercode,biblio.title" unless $orderby;
940 $query .= " ORDER BY $orderby";
941 my $sth = $dbh->prepare($query);
942 $sth->execute($basketno);
943 my $results = $sth->fetchall_arrayref({});
948 #------------------------------------------------------------#
950 =head3 GetOrderNumber
952 $ordernumber = &GetOrderNumber($biblioitemnumber, $biblionumber);
954 Looks up the ordernumber with the given biblionumber and biblioitemnumber.
956 Returns the number of this order.
960 =item C<$ordernumber> is the order number.
967 my ( $biblionumber,$biblioitemnumber ) = @_;
968 my $dbh = C4::Context->dbh;
973 AND biblioitemnumber=?
975 my $sth = $dbh->prepare($query);
976 $sth->execute( $biblionumber, $biblioitemnumber );
978 return $sth->fetchrow;
981 #------------------------------------------------------------#
985 $order = &GetOrder($ordernumber);
987 Looks up an order by order number.
989 Returns a reference-to-hash describing the order. The keys of
990 C<$order> are fields from the biblio, biblioitems, aqorders tables of the Koha database.
995 my ($ordernumber) = @_;
996 my $dbh = C4::Context->dbh;
998 SELECT biblioitems.*, biblio.*, aqorders.*
1000 LEFT JOIN biblio on biblio.biblionumber=aqorders.biblionumber
1001 LEFT JOIN biblioitems on biblioitems.biblionumber=aqorders.biblionumber
1002 WHERE aqorders.ordernumber=?
1005 my $sth= $dbh->prepare($query);
1006 $sth->execute($ordernumber);
1007 my $data = $sth->fetchrow_hashref;
1012 #------------------------------------------------------------#
1016 &NewOrder(\%hashref);
1018 Adds a new order to the database. Any argument that isn't described
1019 below is the new value of the field with the same name in the aqorders
1020 table of the Koha database.
1024 =item $hashref->{'basketno'} is the basketno foreign key in aqorders, it is mandatory
1026 =item $hashref->{'ordernumber'} is a "minimum order number."
1028 =item $hashref->{'budgetdate'} is effectively ignored.
1029 If it's undef (anything false) or the string 'now', the current day is used.
1030 Else, the upcoming July 1st is used.
1032 =item $hashref->{'subscription'} may be either "yes", or anything else for "no".
1034 =item $hashref->{'uncertainprice'} may be 0 for "the price is known" or 1 for "the price is uncertain"
1036 =item defaults entrydate to Now
1038 The following keys are used: "biblionumber", "title", "basketno", "quantity", "notes", "biblioitemnumber", "rrp", "ecost", "gstrate", "unitprice", "subscription", "sort1", "sort2", "booksellerinvoicenumber", "listprice", "budgetdate", "purchaseordernumber", "branchcode", "booksellerinvoicenumber", "budget_id".
1045 my $orderinfo = shift;
1046 #### ------------------------------
1047 my $dbh = C4::Context->dbh;
1051 # if these parameters are missing, we can't continue
1052 for my $key (qw/basketno quantity biblionumber budget_id/) {
1053 croak "Mandatory parameter $key missing" unless $orderinfo->{$key};
1056 if ( defined $orderinfo->{subscription} && $orderinfo->{'subscription'} eq 'yes' ) {
1057 $orderinfo->{'subscription'} = 1;
1059 $orderinfo->{'subscription'} = 0;
1061 $orderinfo->{'entrydate'} ||= C4::Dates->new()->output("iso");
1062 if (!$orderinfo->{quantityreceived}) {
1063 $orderinfo->{quantityreceived} = 0;
1066 my $ordernumber=InsertInTable("aqorders",$orderinfo);
1067 if (not $orderinfo->{parent_ordernumber}) {
1068 my $sth = $dbh->prepare("
1070 SET parent_ordernumber = ordernumber
1071 WHERE ordernumber = ?
1073 $sth->execute($ordernumber);
1075 return ( $orderinfo->{'basketno'}, $ordernumber );
1080 #------------------------------------------------------------#
1089 my ($itemnumber, $ordernumber) = @_;
1090 my $dbh = C4::Context->dbh;
1092 INSERT INTO aqorders_items
1093 (itemnumber, ordernumber)
1096 my $sth = $dbh->prepare($query);
1097 $sth->execute( $itemnumber, $ordernumber);
1100 #------------------------------------------------------------#
1104 &ModOrder(\%hashref);
1106 Modifies an existing order. Updates the order with order number
1107 $hashref->{'ordernumber'} and biblionumber $hashref->{'biblionumber'}. All
1108 other keys of the hash update the fields with the same name in the aqorders
1109 table of the Koha database.
1114 my $orderinfo = shift;
1116 die "Ordernumber is required" if $orderinfo->{'ordernumber'} eq '' ;
1117 die "Biblionumber is required" if $orderinfo->{'biblionumber'} eq '';
1119 my $dbh = C4::Context->dbh;
1122 # update uncertainprice to an integer, just in case (under FF, checked boxes have the value "ON" by default)
1123 $orderinfo->{uncertainprice}=1 if $orderinfo->{uncertainprice};
1125 # delete($orderinfo->{'branchcode'});
1126 # the hash contains a lot of entries not in aqorders, so get the columns ...
1127 my $sth = $dbh->prepare("SELECT * FROM aqorders LIMIT 1;");
1129 my $colnames = $sth->{NAME};
1130 my $query = "UPDATE aqorders SET ";
1132 foreach my $orderinfokey (grep(!/ordernumber/, keys %$orderinfo)){
1133 # ... and skip hash entries that are not in the aqorders table
1134 # FIXME : probably not the best way to do it (would be better to have a correct hash)
1135 next unless grep(/^$orderinfokey$/, @$colnames);
1136 $query .= "$orderinfokey=?, ";
1137 push(@params, $orderinfo->{$orderinfokey});
1140 $query .= "timestamp=NOW() WHERE ordernumber=?";
1141 # push(@params, $specorderinfo{'ordernumber'});
1142 push(@params, $orderinfo->{'ordernumber'} );
1143 $sth = $dbh->prepare($query);
1144 $sth->execute(@params);
1148 #------------------------------------------------------------#
1152 &ModOrderItem(\%hashref);
1154 Modifies the itemnumber in the aqorders_items table. The input hash needs three entities:
1158 =item - itemnumber: the old itemnumber
1159 =item - ordernumber: the order this item is attached to
1160 =item - newitemnumber: the new itemnumber we want to attach the line to
1167 my $orderiteminfo = shift;
1168 if (! $orderiteminfo->{'ordernumber'} || ! $orderiteminfo->{'itemnumber'} || ! $orderiteminfo->{'newitemnumber'}){
1169 die "Ordernumber, itemnumber and newitemnumber is required";
1172 my $dbh = C4::Context->dbh;
1174 my $query = "UPDATE aqorders_items set itemnumber=? where itemnumber=? and ordernumber=?";
1175 my @params = ($orderiteminfo->{'newitemnumber'}, $orderiteminfo->{'itemnumber'}, $orderiteminfo->{'ordernumber'});
1176 my $sth = $dbh->prepare($query);
1177 $sth->execute(@params);
1183 ModItemOrder($itemnumber, $ordernumber);
1185 Modifies the ordernumber of an item in aqorders_items.
1190 my ($itemnumber, $ordernumber) = @_;
1192 return unless ($itemnumber and $ordernumber);
1194 my $dbh = C4::Context->dbh;
1196 UPDATE aqorders_items
1198 WHERE itemnumber = ?
1200 my $sth = $dbh->prepare($query);
1201 return $sth->execute($ordernumber, $itemnumber);
1204 #------------------------------------------------------------#
1207 =head3 ModOrderBibliotemNumber
1209 &ModOrderBiblioitemNumber($biblioitemnumber,$ordernumber, $biblionumber);
1211 Modifies the biblioitemnumber for an existing order.
1212 Updates the order with order number C<$ordernum> and biblionumber C<$biblionumber>.
1216 #FIXME: is this used at all?
1217 sub ModOrderBiblioitemNumber {
1218 my ($biblioitemnumber,$ordernumber, $biblionumber) = @_;
1219 my $dbh = C4::Context->dbh;
1222 SET biblioitemnumber = ?
1223 WHERE ordernumber = ?
1224 AND biblionumber = ?";
1225 my $sth = $dbh->prepare($query);
1226 $sth->execute( $biblioitemnumber, $ordernumber, $biblionumber );
1229 =head3 GetCancelledOrders
1231 my @orders = GetCancelledOrders($basketno, $orderby);
1233 Returns cancelled orders for a basket
1237 sub GetCancelledOrders {
1238 my ( $basketno, $orderby ) = @_;
1240 return () unless $basketno;
1242 my $dbh = C4::Context->dbh;
1244 SELECT biblio.*, biblioitems.*, aqorders.*, aqbudgets.*
1246 LEFT JOIN aqbudgets ON aqbudgets.budget_id = aqorders.budget_id
1247 LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1248 LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
1250 AND (datecancellationprinted IS NOT NULL
1251 AND datecancellationprinted <> '0000-00-00')
1254 $orderby = "aqorders.datecancellationprinted desc, aqorders.timestamp desc"
1256 $query .= " ORDER BY $orderby";
1257 my $sth = $dbh->prepare($query);
1258 $sth->execute($basketno);
1259 my $results = $sth->fetchall_arrayref( {} );
1265 #------------------------------------------------------------#
1267 =head3 ModReceiveOrder
1269 &ModReceiveOrder($biblionumber, $ordernumber, $quantityreceived, $user,
1270 $unitprice, $invoiceid, $biblioitemnumber,
1271 $bookfund, $rrp, \@received_itemnumbers);
1273 Updates an order, to reflect the fact that it was received, at least
1274 in part. All arguments not mentioned below update the fields with the
1275 same name in the aqorders table of the Koha database.
1277 If a partial order is received, splits the order into two.
1279 Updates the order with bibilionumber C<$biblionumber> and ordernumber
1285 sub ModReceiveOrder {
1287 $biblionumber, $ordernumber, $quantrec, $user, $cost, $ecost,
1288 $invoiceid, $rrp, $budget_id, $datereceived, $received_items
1292 my $dbh = C4::Context->dbh;
1293 $datereceived = C4::Dates->output('iso') unless $datereceived;
1294 my $suggestionid = GetSuggestionFromBiblionumber( $biblionumber );
1295 if ($suggestionid) {
1296 ModSuggestion( {suggestionid=>$suggestionid,
1297 STATUS=>'AVAILABLE',
1298 biblionumber=> $biblionumber}
1302 my $sth=$dbh->prepare("
1303 SELECT * FROM aqorders
1304 WHERE biblionumber=? AND aqorders.ordernumber=?");
1306 $sth->execute($biblionumber,$ordernumber);
1307 my $order = $sth->fetchrow_hashref();
1310 my $new_ordernumber = $ordernumber;
1311 if ( $order->{quantity} > $quantrec ) {
1312 # Split order line in two parts: the first is the original order line
1313 # without received items (the quantity is decreased),
1314 # the second part is a new order line with quantity=quantityrec
1315 # (entirely received)
1316 $sth=$dbh->prepare("
1319 WHERE ordernumber = ?
1322 $sth->execute($order->{quantity} - $quantrec, $ordernumber);
1326 delete $order->{'ordernumber'};
1327 $order->{'quantity'} = $quantrec;
1328 $order->{'quantityreceived'} = $quantrec;
1329 $order->{'datereceived'} = $datereceived;
1330 $order->{'invoiceid'} = $invoiceid;
1331 $order->{'unitprice'} = $cost;
1332 $order->{'rrp'} = $rrp;
1333 $order->{ecost} = $ecost;
1334 $order->{'orderstatus'} = 3; # totally received
1335 $new_ordernumber = NewOrder($order);
1337 if ($received_items) {
1338 foreach my $itemnumber (@$received_items) {
1339 ModItemOrder($itemnumber, $new_ordernumber);
1343 $sth=$dbh->prepare("update aqorders
1344 set quantityreceived=?,datereceived=?,invoiceid=?,
1345 unitprice=?,rrp=?,ecost=?
1346 where biblionumber=? and ordernumber=?");
1347 $sth->execute($quantrec,$datereceived,$invoiceid,$cost,$rrp,$ecost,$biblionumber,$ordernumber);
1350 return ($datereceived, $new_ordernumber);
1353 =head3 CancelReceipt
1355 my $parent_ordernumber = CancelReceipt($ordernumber);
1357 Cancel an order line receipt and update the parent order line, as if no
1359 If items are created at receipt (AcqCreateItem = receiving) then delete
1365 my $ordernumber = shift;
1367 return unless $ordernumber;
1369 my $dbh = C4::Context->dbh;
1371 SELECT datereceived, parent_ordernumber, quantity
1373 WHERE ordernumber = ?
1375 my $sth = $dbh->prepare($query);
1376 $sth->execute($ordernumber);
1377 my $order = $sth->fetchrow_hashref;
1379 warn "CancelReceipt: order $ordernumber does not exist";
1382 unless($order->{'datereceived'}) {
1383 warn "CancelReceipt: order $ordernumber is not received";
1387 my $parent_ordernumber = $order->{'parent_ordernumber'};
1389 if($parent_ordernumber == $ordernumber || not $parent_ordernumber) {
1390 # The order line has no parent, just mark it as not received
1393 SET quantityreceived = ?,
1396 WHERE ordernumber = ?
1398 $sth = $dbh->prepare($query);
1399 $sth->execute(0, undef, undef, $ordernumber);
1401 # The order line has a parent, increase parent quantity and delete
1404 SELECT quantity, datereceived
1406 WHERE ordernumber = ?
1408 $sth = $dbh->prepare($query);
1409 $sth->execute($parent_ordernumber);
1410 my $parent_order = $sth->fetchrow_hashref;
1411 unless($parent_order) {
1412 warn "Parent order $parent_ordernumber does not exist.";
1415 if($parent_order->{'datereceived'}) {
1416 warn "CancelReceipt: parent order is received.".
1417 " Can't cancel receipt.";
1423 WHERE ordernumber = ?
1425 $sth = $dbh->prepare($query);
1426 my $rv = $sth->execute(
1427 $order->{'quantity'} + $parent_order->{'quantity'},
1431 warn "Cannot update parent order line, so do not cancel".
1435 if(C4::Context->preference('AcqCreateItem') eq 'receiving') {
1436 # Remove items that were created at receipt
1438 DELETE FROM items, aqorders_items
1439 USING items, aqorders_items
1440 WHERE items.itemnumber = ? AND aqorders_items.itemnumber = ?
1442 $sth = $dbh->prepare($query);
1443 my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
1444 foreach my $itemnumber (@itemnumbers) {
1445 $sth->execute($itemnumber, $itemnumber);
1449 my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
1450 foreach my $itemnumber (@itemnumbers) {
1451 ModItemOrder($itemnumber, $parent_ordernumber);
1456 DELETE FROM aqorders
1457 WHERE ordernumber = ?
1459 $sth = $dbh->prepare($query);
1460 $sth->execute($ordernumber);
1464 return $parent_ordernumber;
1467 #------------------------------------------------------------#
1471 @results = &SearchOrder($search, $biblionumber, $complete);
1473 Searches for orders.
1475 C<$search> may take one of several forms: if it is an ISBN,
1476 C<&ordersearch> returns orders with that ISBN. If C<$search> is an
1477 order number, C<&ordersearch> returns orders with that order number
1478 and biblionumber C<$biblionumber>. Otherwise, C<$search> is considered
1479 to be a space-separated list of search terms; in this case, all of the
1480 terms must appear in the title (matching the beginning of title
1483 If C<$complete> is C<yes>, the results will include only completed
1484 orders. In any case, C<&ordersearch> ignores cancelled orders.
1486 C<&ordersearch> returns an array.
1487 C<@results> is an array of references-to-hash with the following keys:
1493 =item C<seriestitle>
1504 #### -------- SearchOrder-------------------------------
1505 my ( $ordernumber, $search, $ean, $supplierid, $basket ) = @_;
1507 my $dbh = C4::Context->dbh;
1512 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1513 LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
1514 LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
1515 WHERE (datecancellationprinted is NULL)";
1518 $query .= " AND (aqorders.ordernumber=?)";
1519 push @args, $ordernumber;
1522 $query .= " AND (biblio.title like ? OR biblio.author LIKE ? OR biblioitems.isbn like ?)";
1523 push @args, ("%$search%","%$search%","%$search%");
1526 $query .= " AND biblioitems.ean = ?";
1530 $query .= "AND aqbasket.booksellerid = ?";
1531 push @args, $supplierid;
1534 $query .= "AND aqorders.basketno = ?";
1535 push @args, $basket;
1538 my $sth = $dbh->prepare($query);
1539 $sth->execute(@args);
1540 my $results = $sth->fetchall_arrayref({});
1545 #------------------------------------------------------------#
1549 &DelOrder($biblionumber, $ordernumber);
1551 Cancel the order with the given order and biblio numbers. It does not
1552 delete any entries in the aqorders table, it merely marks them as
1558 my ( $bibnum, $ordernumber ) = @_;
1559 my $dbh = C4::Context->dbh;
1562 SET datecancellationprinted=now()
1563 WHERE biblionumber=? AND ordernumber=?
1565 my $sth = $dbh->prepare($query);
1566 $sth->execute( $bibnum, $ordernumber );
1568 my @itemnumbers = GetItemnumbersFromOrder( $ordernumber );
1569 foreach my $itemnumber (@itemnumbers){
1570 C4::Items::DelItem( $dbh, $bibnum, $itemnumber );
1575 =head2 FUNCTIONS ABOUT PARCELS
1579 #------------------------------------------------------------#
1583 @results = &GetParcel($booksellerid, $code, $date);
1585 Looks up all of the received items from the supplier with the given
1586 bookseller ID at the given date, for the given code (bookseller Invoice number). Ignores cancelled and completed orders.
1588 C<@results> is an array of references-to-hash. The keys of each element are fields from
1589 the aqorders, biblio, and biblioitems tables of the Koha database.
1591 C<@results> is sorted alphabetically by book title.
1596 #gets all orders from a certain supplier, orders them alphabetically
1597 my ( $supplierid, $code, $datereceived ) = @_;
1598 my $dbh = C4::Context->dbh;
1601 if $code; # add % if we search on a given code (otherwise, let him empty)
1603 SELECT authorisedby,
1608 aqorders.biblionumber,
1609 aqorders.ordernumber,
1610 aqorders.parent_ordernumber,
1612 aqorders.quantityreceived,
1620 LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
1621 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
1622 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1623 LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
1625 aqbasket.booksellerid = ?
1626 AND aqinvoices.invoicenumber LIKE ?
1627 AND aqorders.datereceived = ? ";
1629 my @query_params = ( $supplierid, $code, $datereceived );
1630 if ( C4::Context->preference("IndependantBranches") ) {
1631 my $userenv = C4::Context->userenv;
1632 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1633 $strsth .= " and (borrowers.branchcode = ?
1634 or borrowers.branchcode = '')";
1635 push @query_params, $userenv->{branch};
1638 $strsth .= " ORDER BY aqbasket.basketno";
1639 # ## parcelinformation : $strsth
1640 my $sth = $dbh->prepare($strsth);
1641 $sth->execute( @query_params );
1642 while ( my $data = $sth->fetchrow_hashref ) {
1643 push( @results, $data );
1645 # ## countparcelbiblio: scalar(@results)
1651 #------------------------------------------------------------#
1655 $results = &GetParcels($bookseller, $order, $code, $datefrom, $dateto);
1657 get a lists of parcels.
1664 is the bookseller this function has to get parcels.
1667 To know on what criteria the results list has to be ordered.
1670 is the booksellerinvoicenumber.
1672 =item $datefrom & $dateto
1673 to know on what date this function has to filter its search.
1678 a pointer on a hash list containing parcel informations as such :
1684 =item Last operation
1686 =item Number of biblio
1688 =item Number of items
1695 my ($bookseller,$order, $code, $datefrom, $dateto) = @_;
1696 my $dbh = C4::Context->dbh;
1697 my @query_params = ();
1699 SELECT aqinvoices.invoicenumber,
1700 datereceived,purchaseordernumber,
1701 count(DISTINCT biblionumber) AS biblio,
1702 sum(quantity) AS itemsexpected,
1703 sum(quantityreceived) AS itemsreceived
1704 FROM aqorders LEFT JOIN aqbasket ON aqbasket.basketno = aqorders.basketno
1705 LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
1706 WHERE aqbasket.booksellerid = ? and datereceived IS NOT NULL
1708 push @query_params, $bookseller;
1710 if ( defined $code ) {
1711 $strsth .= ' and aqinvoices.invoicenumber like ? ';
1712 # add a % to the end of the code to allow stemming.
1713 push @query_params, "$code%";
1716 if ( defined $datefrom ) {
1717 $strsth .= ' and datereceived >= ? ';
1718 push @query_params, $datefrom;
1721 if ( defined $dateto ) {
1722 $strsth .= 'and datereceived <= ? ';
1723 push @query_params, $dateto;
1726 $strsth .= "group by aqinvoices.invoicenumber,datereceived ";
1728 # can't use a placeholder to place this column name.
1729 # but, we could probably be checking to make sure it is a column that will be fetched.
1730 $strsth .= "order by $order " if ($order);
1732 my $sth = $dbh->prepare($strsth);
1734 $sth->execute( @query_params );
1735 my $results = $sth->fetchall_arrayref({});
1740 #------------------------------------------------------------#
1742 =head3 GetLateOrders
1744 @results = &GetLateOrders;
1746 Searches for bookseller with late orders.
1749 the table of supplier with late issues. This table is full of hashref.
1755 my $supplierid = shift;
1757 my $estimateddeliverydatefrom = shift;
1758 my $estimateddeliverydateto = shift;
1760 my $dbh = C4::Context->dbh;
1762 #BEWARE, order of parenthesis and LEFT JOIN is important for speed
1763 my $dbdriver = C4::Context->config("db_scheme") || "mysql";
1765 my @query_params = ();
1767 SELECT aqbasket.basketno,
1768 aqorders.ordernumber,
1769 DATE(aqbasket.closedate) AS orderdate,
1770 aqorders.rrp AS unitpricesupplier,
1771 aqorders.ecost AS unitpricelib,
1772 aqorders.claims_count AS claims_count,
1773 aqorders.claimed_date AS claimed_date,
1774 aqbudgets.budget_name AS budget,
1775 borrowers.branchcode AS branch,
1776 aqbooksellers.name AS supplier,
1777 aqbooksellers.id AS supplierid,
1778 biblio.author, biblio.title,
1779 biblioitems.publishercode AS publisher,
1780 biblioitems.publicationyear,
1781 ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) AS estimateddeliverydate,
1785 aqorders LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1786 LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
1787 LEFT JOIN aqbudgets ON aqorders.budget_id = aqbudgets.budget_id,
1788 aqbasket LEFT JOIN borrowers ON aqbasket.authorisedby = borrowers.borrowernumber
1789 LEFT JOIN aqbooksellers ON aqbasket.booksellerid = aqbooksellers.id
1790 WHERE aqorders.basketno = aqbasket.basketno
1791 AND ( datereceived = ''
1792 OR datereceived IS NULL
1793 OR aqorders.quantityreceived < aqorders.quantity
1795 AND aqbasket.closedate IS NOT NULL
1796 AND (aqorders.datecancellationprinted IS NULL OR aqorders.datecancellationprinted='0000-00-00')
1799 if ($dbdriver eq "mysql") {
1801 aqorders.quantity - COALESCE(aqorders.quantityreceived,0) AS quantity,
1802 (aqorders.quantity - COALESCE(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
1803 DATEDIFF(CAST(now() AS date),closedate) AS latesince
1805 if ( defined $delay ) {
1806 $from .= " AND (closedate <= DATE_SUB(CAST(now() AS date),INTERVAL ? DAY)) " ;
1807 push @query_params, $delay;
1810 HAVING quantity <> 0
1811 AND unitpricesupplier <> 0
1812 AND unitpricelib <> 0
1815 # FIXME: account for IFNULL as above
1817 aqorders.quantity AS quantity,
1818 aqorders.quantity * aqorders.rrp AS subtotal,
1819 (CAST(now() AS date) - closedate) AS latesince
1821 if ( defined $delay ) {
1822 $from .= " AND (closedate <= (CAST(now() AS date) -(INTERVAL ? DAY)) ";
1823 push @query_params, $delay;
1826 if (defined $supplierid) {
1827 $from .= ' AND aqbasket.booksellerid = ? ';
1828 push @query_params, $supplierid;
1830 if (defined $branch) {
1831 $from .= ' AND borrowers.branchcode LIKE ? ';
1832 push @query_params, $branch;
1835 if ( defined $estimateddeliverydatefrom or defined $estimateddeliverydateto ) {
1836 $from .= ' AND aqbooksellers.deliverytime IS NOT NULL ';
1838 if ( defined $estimateddeliverydatefrom ) {
1839 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) >= ?';
1840 push @query_params, $estimateddeliverydatefrom;
1842 if ( defined $estimateddeliverydateto ) {
1843 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= ?';
1844 push @query_params, $estimateddeliverydateto;
1846 if ( defined $estimateddeliverydatefrom and not defined $estimateddeliverydateto ) {
1847 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= CAST(now() AS date)';
1849 if (C4::Context->preference("IndependantBranches")
1850 && C4::Context->userenv
1851 && C4::Context->userenv->{flags} != 1 ) {
1852 $from .= ' AND borrowers.branchcode LIKE ? ';
1853 push @query_params, C4::Context->userenv->{branch};
1855 my $query = "$select $from $having\nORDER BY latesince, basketno, borrowers.branchcode, supplier";
1856 $debug and print STDERR "GetLateOrders query: $query\nGetLateOrders args: " . join(" ",@query_params);
1857 my $sth = $dbh->prepare($query);
1858 $sth->execute(@query_params);
1860 while (my $data = $sth->fetchrow_hashref) {
1861 $data->{orderdate} = format_date($data->{orderdate});
1862 $data->{claimed_date} = format_date($data->{claimed_date});
1863 push @results, $data;
1868 #------------------------------------------------------------#
1872 (\@order_loop, $total_qty, $total_price, $total_qtyreceived) = GetHistory( %params );
1874 Retreives some acquisition history information
1882 basket - search both basket name and number
1883 booksellerinvoicenumber
1886 $order_loop is a list of hashrefs that each look like this:
1888 'author' => 'Twain, Mark',
1890 'biblionumber' => '215',
1892 'creationdate' => 'MM/DD/YYYY',
1893 'datereceived' => undef,
1896 'invoicenumber' => undef,
1898 'ordernumber' => '1',
1900 'quantityreceived' => undef,
1901 'title' => 'The Adventures of Huckleberry Finn'
1903 $total_qty is the sum of all of the quantities in $order_loop
1904 $total_price is the cost of each in $order_loop times the quantity
1905 $total_qtyreceived is the sum of all of the quantityreceived entries in $order_loop
1910 # don't run the query if there are no parameters (list would be too long for sure !)
1911 croak "No search params" unless @_;
1913 my $title = $params{title};
1914 my $author = $params{author};
1915 my $isbn = $params{isbn};
1916 my $ean = $params{ean};
1917 my $name = $params{name};
1918 my $from_placed_on = $params{from_placed_on};
1919 my $to_placed_on = $params{to_placed_on};
1920 my $basket = $params{basket};
1921 my $booksellerinvoicenumber = $params{booksellerinvoicenumber};
1922 my $basketgroupname = $params{basketgroupname};
1925 my $total_qtyreceived = 0;
1926 my $total_price = 0;
1928 my $dbh = C4::Context->dbh;
1936 aqbasket.basketname,
1937 aqbasket.basketgroupid,
1938 aqbasketgroups.name as groupname,
1940 aqbasket.creationdate,
1941 aqorders.datereceived,
1943 aqorders.quantityreceived,
1945 aqorders.ordernumber,
1946 aqinvoices.invoicenumber,
1947 aqbooksellers.id as id,
1948 aqorders.biblionumber
1950 LEFT JOIN aqbasket ON aqorders.basketno=aqbasket.basketno
1951 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid=aqbasketgroups.id
1952 LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
1953 LEFT JOIN biblioitems ON biblioitems.biblionumber=aqorders.biblionumber
1954 LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
1955 LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid";
1957 $query .= " LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber"
1958 if ( C4::Context->preference("IndependantBranches") );
1960 $query .= " WHERE (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') ";
1962 my @query_params = ();
1965 $query .= " AND biblio.title LIKE ? ";
1966 $title =~ s/\s+/%/g;
1967 push @query_params, "%$title%";
1971 $query .= " AND biblio.author LIKE ? ";
1972 push @query_params, "%$author%";
1976 $query .= " AND biblioitems.isbn LIKE ? ";
1977 push @query_params, "%$isbn%";
1979 if ( defined $ean and $ean ) {
1980 $query .= " AND biblioitems.ean = ? ";
1981 push @query_params, "$ean";
1984 $query .= " AND aqbooksellers.name LIKE ? ";
1985 push @query_params, "%$name%";
1988 if ( $from_placed_on ) {
1989 $query .= " AND creationdate >= ? ";
1990 push @query_params, $from_placed_on;
1993 if ( $to_placed_on ) {
1994 $query .= " AND creationdate <= ? ";
1995 push @query_params, $to_placed_on;
1999 if ($basket =~ m/^\d+$/) {
2000 $query .= " AND aqorders.basketno = ? ";
2001 push @query_params, $basket;
2003 $query .= " AND aqbasket.basketname LIKE ? ";
2004 push @query_params, "%$basket%";
2008 if ($booksellerinvoicenumber) {
2009 $query .= " AND aqinvoices.invoicenumber LIKE ? ";
2010 push @query_params, "%$booksellerinvoicenumber%";
2013 if ($basketgroupname) {
2014 $query .= " AND aqbasketgroups.name LIKE ? ";
2015 push @query_params, "%$basketgroupname%";
2018 if ( C4::Context->preference("IndependantBranches") ) {
2019 my $userenv = C4::Context->userenv;
2020 if ( $userenv && ($userenv->{flags} || 0) != 1 ) {
2021 $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
2022 push @query_params, $userenv->{branch};
2025 $query .= " ORDER BY id";
2026 my $sth = $dbh->prepare($query);
2027 $sth->execute( @query_params );
2029 while ( my $line = $sth->fetchrow_hashref ) {
2030 $line->{count} = $cnt++;
2031 $line->{toggle} = 1 if $cnt % 2;
2032 push @order_loop, $line;
2033 $total_qty += $line->{'quantity'};
2034 $total_qtyreceived += $line->{'quantityreceived'};
2035 $total_price += $line->{'quantity'} * $line->{'ecost'};
2037 return \@order_loop, $total_qty, $total_price, $total_qtyreceived;
2040 =head2 GetRecentAcqui
2042 $results = GetRecentAcqui($days);
2044 C<$results> is a ref to a table which containts hashref
2048 sub GetRecentAcqui {
2050 my $dbh = C4::Context->dbh;
2054 ORDER BY timestamp DESC
2057 my $sth = $dbh->prepare($query);
2059 my $results = $sth->fetchall_arrayref({});
2065 $contractlist = &GetContracts($booksellerid, $activeonly);
2067 Looks up the contracts that belong to a bookseller
2069 Returns a list of contracts
2073 =item C<$booksellerid> is the "id" field in the "aqbooksellers" table.
2075 =item C<$activeonly> if exists get only contracts that are still active.
2082 my ( $booksellerid, $activeonly ) = @_;
2083 my $dbh = C4::Context->dbh;
2085 if (! $activeonly) {
2089 WHERE booksellerid=?
2094 WHERE booksellerid=?
2095 AND contractenddate >= CURDATE( )";
2097 my $sth = $dbh->prepare($query);
2098 $sth->execute( $booksellerid );
2100 while (my $data = $sth->fetchrow_hashref ) {
2101 push(@results, $data);
2107 #------------------------------------------------------------#
2111 $contract = &GetContract($contractID);
2113 Looks up the contract that has PRIMKEY (contractnumber) value $contractID
2120 my ( $contractno ) = @_;
2121 my $dbh = C4::Context->dbh;
2125 WHERE contractnumber=?
2128 my $sth = $dbh->prepare($query);
2129 $sth->execute( $contractno );
2130 my $result = $sth->fetchrow_hashref;
2138 &AddClaim($ordernumber);
2140 Add a claim for an order
2146 my ($ordernumber) = @_;
2147 my $dbh = C4::Context->dbh;
2150 claims_count = claims_count + 1,
2151 claimed_date = CURDATE()
2152 WHERE ordernumber = ?
2154 my $sth = $dbh->prepare($query);
2155 $sth->execute($ordernumber);
2160 my @invoices = GetInvoices(
2161 invoicenumber => $invoicenumber,
2162 suppliername => $suppliername,
2163 shipmentdatefrom => $shipmentdatefrom, # ISO format
2164 shipmentdateto => $shipmentdateto, # ISO format
2165 billingdatefrom => $billingdatefrom, # ISO format
2166 billingdateto => $billingdateto, # ISO format
2167 isbneanissn => $isbn_or_ean_or_issn,
2170 publisher => $publisher,
2171 publicationyear => $publicationyear,
2172 branchcode => $branchcode,
2173 order_by => $order_by
2176 Return a list of invoices that match all given criteria.
2178 $order_by is "column_name (asc|desc)", where column_name is any of
2179 'invoicenumber', 'booksellerid', 'shipmentdate', 'billingdate', 'closedate',
2180 'shipmentcost', 'shipmentcost_budgetid'.
2182 asc is the default if omitted
2189 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2190 closedate shipmentcost shipmentcost_budgetid);
2192 my $dbh = C4::Context->dbh;
2194 SELECT aqinvoices.*, aqbooksellers.name AS suppliername,
2197 aqorders.datereceived IS NOT NULL,
2198 aqorders.biblionumber,
2201 ) AS receivedbiblios,
2202 SUM(aqorders.quantityreceived) AS receiveditems
2204 LEFT JOIN aqbooksellers ON aqbooksellers.id = aqinvoices.booksellerid
2205 LEFT JOIN aqorders ON aqorders.invoiceid = aqinvoices.invoiceid
2206 LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
2207 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
2208 LEFT JOIN subscription ON biblio.biblionumber = subscription.biblionumber
2213 if($args{supplierid}) {
2214 push @bind_strs, " aqinvoices.booksellerid = ? ";
2215 push @bind_args, $args{supplierid};
2217 if($args{invoicenumber}) {
2218 push @bind_strs, " aqinvoices.invoicenumber LIKE ? ";
2219 push @bind_args, "%$args{invoicenumber}%";
2221 if($args{suppliername}) {
2222 push @bind_strs, " aqbooksellers.name LIKE ? ";
2223 push @bind_args, "%$args{suppliername}%";
2225 if($args{shipmentdatefrom}) {
2226 push @bind_strs, " aqinvoices.shipementdate >= ? ";
2227 push @bind_args, $args{shipmentdatefrom};
2229 if($args{shipmentdateto}) {
2230 push @bind_strs, " aqinvoices.shipementdate <= ? ";
2231 push @bind_args, $args{shipmentdateto};
2233 if($args{billingdatefrom}) {
2234 push @bind_strs, " aqinvoices.billingdate >= ? ";
2235 push @bind_args, $args{billingdatefrom};
2237 if($args{billingdateto}) {
2238 push @bind_strs, " aqinvoices.billingdate <= ? ";
2239 push @bind_args, $args{billingdateto};
2241 if($args{isbneanissn}) {
2242 push @bind_strs, " (biblioitems.isbn LIKE ? OR biblioitems.ean LIKE ? OR biblioitems.issn LIKE ? ) ";
2243 push @bind_args, $args{isbneanissn}, $args{isbneanissn}, $args{isbneanissn};
2246 push @bind_strs, " biblio.title LIKE ? ";
2247 push @bind_args, $args{title};
2250 push @bind_strs, " biblio.author LIKE ? ";
2251 push @bind_args, $args{author};
2253 if($args{publisher}) {
2254 push @bind_strs, " biblioitems.publishercode LIKE ? ";
2255 push @bind_args, $args{publisher};
2257 if($args{publicationyear}) {
2258 push @bind_strs, " biblioitems.publicationyear = ? ";
2259 push @bind_args, $args{publicationyear};
2261 if($args{branchcode}) {
2262 push @bind_strs, " aqorders.branchcode = ? ";
2263 push @bind_args, $args{branchcode};
2266 $query .= " WHERE " . join(" AND ", @bind_strs) if @bind_strs;
2267 $query .= " GROUP BY aqinvoices.invoiceid ";
2269 if($args{order_by}) {
2270 my ($column, $direction) = split / /, $args{order_by};
2271 if(grep /^$column$/, @columns) {
2272 $direction ||= 'ASC';
2273 $query .= " ORDER BY $column $direction";
2277 my $sth = $dbh->prepare($query);
2278 $sth->execute(@bind_args);
2280 my $results = $sth->fetchall_arrayref({});
2286 my $invoice = GetInvoice($invoiceid);
2288 Get informations about invoice with given $invoiceid
2290 Return a hash filled with aqinvoices.* fields
2295 my ($invoiceid) = @_;
2298 return unless $invoiceid;
2300 my $dbh = C4::Context->dbh;
2306 my $sth = $dbh->prepare($query);
2307 $sth->execute($invoiceid);
2309 $invoice = $sth->fetchrow_hashref;
2313 =head3 GetInvoiceDetails
2315 my $invoice = GetInvoiceDetails($invoiceid)
2317 Return informations about an invoice + the list of related order lines
2319 Orders informations are in $invoice->{orders} (array ref)
2323 sub GetInvoiceDetails {
2324 my ($invoiceid) = @_;
2326 if ( !defined $invoiceid ) {
2327 carp 'GetInvoiceDetails called without an invoiceid';
2331 my $dbh = C4::Context->dbh;
2333 SELECT aqinvoices.*, aqbooksellers.name AS suppliername
2335 LEFT JOIN aqbooksellers ON aqinvoices.booksellerid = aqbooksellers.id
2338 my $sth = $dbh->prepare($query);
2339 $sth->execute($invoiceid);
2341 my $invoice = $sth->fetchrow_hashref;
2344 SELECT aqorders.*, biblio.*
2346 LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
2349 $sth = $dbh->prepare($query);
2350 $sth->execute($invoiceid);
2351 $invoice->{orders} = $sth->fetchall_arrayref({});
2352 $invoice->{orders} ||= []; # force an empty arrayref if fetchall_arrayref fails
2359 my $invoiceid = AddInvoice(
2360 invoicenumber => $invoicenumber,
2361 booksellerid => $booksellerid,
2362 shipmentdate => $shipmentdate,
2363 billingdate => $billingdate,
2364 closedate => $closedate,
2365 shipmentcost => $shipmentcost,
2366 shipmentcost_budgetid => $shipmentcost_budgetid
2369 Create a new invoice and return its id or undef if it fails.
2376 return unless(%invoice and $invoice{invoicenumber});
2378 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2379 closedate shipmentcost shipmentcost_budgetid);
2383 foreach my $key (keys %invoice) {
2384 if(0 < grep(/^$key$/, @columns)) {
2385 push @set_strs, "$key = ?";
2386 push @set_args, ($invoice{$key} || undef);
2392 my $dbh = C4::Context->dbh;
2393 my $query = "INSERT INTO aqinvoices SET ";
2394 $query .= join (",", @set_strs);
2395 my $sth = $dbh->prepare($query);
2396 $rv = $sth->execute(@set_args);
2398 $rv = $dbh->last_insert_id(undef, undef, 'aqinvoices', undef);
2407 invoiceid => $invoiceid, # Mandatory
2408 invoicenumber => $invoicenumber,
2409 booksellerid => $booksellerid,
2410 shipmentdate => $shipmentdate,
2411 billingdate => $billingdate,
2412 closedate => $closedate,
2413 shipmentcost => $shipmentcost,
2414 shipmentcost_budgetid => $shipmentcost_budgetid
2417 Modify an invoice, invoiceid is mandatory.
2419 Return undef if it fails.
2426 return unless(%invoice and $invoice{invoiceid});
2428 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2429 closedate shipmentcost shipmentcost_budgetid);
2433 foreach my $key (keys %invoice) {
2434 if(0 < grep(/^$key$/, @columns)) {
2435 push @set_strs, "$key = ?";
2436 push @set_args, ($invoice{$key} || undef);
2440 my $dbh = C4::Context->dbh;
2441 my $query = "UPDATE aqinvoices SET ";
2442 $query .= join(",", @set_strs);
2443 $query .= " WHERE invoiceid = ?";
2445 my $sth = $dbh->prepare($query);
2446 $sth->execute(@set_args, $invoice{invoiceid});
2451 CloseInvoice($invoiceid);
2455 Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => undef);
2460 my ($invoiceid) = @_;
2462 return unless $invoiceid;
2464 my $dbh = C4::Context->dbh;
2467 SET closedate = CAST(NOW() AS DATE)
2470 my $sth = $dbh->prepare($query);
2471 $sth->execute($invoiceid);
2474 =head3 ReopenInvoice
2476 ReopenInvoice($invoiceid);
2480 Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => C4::Dates->new()->output('iso'))
2485 my ($invoiceid) = @_;
2487 return unless $invoiceid;
2489 my $dbh = C4::Context->dbh;
2492 SET closedate = NULL
2495 my $sth = $dbh->prepare($query);
2496 $sth->execute($invoiceid);
2504 Koha Development Team <http://koha-community.org/>