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 &GetOrder &GetOrders &GetOrdersByBiblionumber
57 &GetLateOrders &GetOrderFromItemnumber
58 &SearchOrders &GetHistory &GetRecentAcqui
59 &ModReceiveOrder &CancelReceipt
60 &GetCancelledOrders &TransferOrder
61 &GetLastOrderNotReceivedFromSubscriptionid &GetLastOrderReceivedFromSubscriptionid
62 &NewOrderItem &ModItemOrder
64 &GetParcels &GetParcel
65 &GetContracts &GetContract
77 &GetItemnumbersFromOrder
87 sub GetOrderFromItemnumber {
88 my ($itemnumber) = @_;
89 my $dbh = C4::Context->dbh;
92 SELECT * from aqorders LEFT JOIN aqorders_items
93 ON ( aqorders.ordernumber = aqorders_items.ordernumber )
94 WHERE itemnumber = ? |;
96 my $sth = $dbh->prepare($query);
100 $sth->execute($itemnumber);
102 my $order = $sth->fetchrow_hashref;
107 # Returns the itemnumber(s) associated with the ordernumber given in parameter
108 sub GetItemnumbersFromOrder {
109 my ($ordernumber) = @_;
110 my $dbh = C4::Context->dbh;
111 my $query = "SELECT itemnumber FROM aqorders_items WHERE ordernumber=?";
112 my $sth = $dbh->prepare($query);
113 $sth->execute($ordernumber);
116 while (my $order = $sth->fetchrow_hashref) {
117 push @tab, $order->{'itemnumber'};
131 C4::Acquisition - Koha functions for dealing with orders and acquisitions
139 The functions in this module deal with acquisitions, managing book
140 orders, basket and parcels.
144 =head2 FUNCTIONS ABOUT BASKETS
148 $aqbasket = &GetBasket($basketnumber);
150 get all basket informations in aqbasket for a given basket
152 B<returns:> informations for a given basket returned as a hashref.
158 my $dbh = C4::Context->dbh;
161 concat( b.firstname,' ',b.surname) AS authorisedbyname,
162 b.branchcode AS branch
164 LEFT JOIN borrowers b ON aqbasket.authorisedby=b.borrowernumber
167 my $sth=$dbh->prepare($query);
168 $sth->execute($basketno);
169 my $basket = $sth->fetchrow_hashref;
173 #------------------------------------------------------------#
177 $basket = &NewBasket( $booksellerid, $authorizedby, $basketname,
178 $basketnote, $basketbooksellernote, $basketcontractnumber, $deliveryplace, $billingplace );
180 Create a new basket in aqbasket table
184 =item C<$booksellerid> is a foreign key in the aqbasket table
186 =item C<$authorizedby> is the username of who created the basket
190 The other parameters are optional, see ModBasketHeader for more info on them.
195 my ( $booksellerid, $authorisedby, $basketname, $basketnote,
196 $basketbooksellernote, $basketcontractnumber, $deliveryplace,
197 $billingplace ) = @_;
198 my $dbh = C4::Context->dbh;
200 'INSERT INTO aqbasket (creationdate,booksellerid,authorisedby) '
201 . 'VALUES (now(),?,?)';
202 $dbh->do( $query, {}, $booksellerid, $authorisedby );
204 my $basket = $dbh->{mysql_insertid};
205 $basketname ||= q{}; # default to empty strings
207 $basketbooksellernote ||= q{};
208 ModBasketHeader( $basket, $basketname, $basketnote, $basketbooksellernote,
209 $basketcontractnumber, $booksellerid, $deliveryplace, $billingplace );
213 #------------------------------------------------------------#
217 &CloseBasket($basketno);
219 close a basket (becomes unmodifiable,except for recieves)
225 my $dbh = C4::Context->dbh;
231 my $sth = $dbh->prepare($query);
232 $sth->execute($basketno);
235 #------------------------------------------------------------#
237 =head3 GetBasketAsCSV
239 &GetBasketAsCSV($basketno);
241 Export a basket as CSV
243 $cgi parameter is needed for column name translation
248 my ($basketno, $cgi) = @_;
249 my $basket = GetBasket($basketno);
250 my @orders = GetOrders($basketno);
251 my $contract = GetContract($basket->{'contractnumber'});
253 my $template = C4::Templates::gettemplate("acqui/csv/basket.tmpl", "intranet", $cgi);
256 foreach my $order (@orders) {
257 my $bd = GetBiblioData( $order->{'biblionumber'} );
259 contractname => $contract->{'contractname'},
260 ordernumber => $order->{'ordernumber'},
261 entrydate => $order->{'entrydate'},
262 isbn => $order->{'isbn'},
263 author => $bd->{'author'},
264 title => $bd->{'title'},
265 publicationyear => $bd->{'publicationyear'},
266 publishercode => $bd->{'publishercode'},
267 collectiontitle => $bd->{'collectiontitle'},
268 notes => $order->{'notes'},
269 quantity => $order->{'quantity'},
270 rrp => $order->{'rrp'},
271 deliveryplace => C4::Branch::GetBranchName( $basket->{'deliveryplace'} ),
272 billingplace => C4::Branch::GetBranchName( $basket->{'billingplace'} ),
275 contractname author title publishercode collectiontitle notes
276 deliveryplace billingplace
278 # Double the quotes to not be interpreted as a field end
279 $row->{$_} =~ s/"/""/g if $row->{$_};
285 if(defined $a->{publishercode} and defined $b->{publishercode}) {
286 $a->{publishercode} cmp $b->{publishercode};
290 $template->param(rows => \@rows);
292 return $template->output;
296 =head3 GetBasketGroupAsCSV
300 &GetBasketGroupAsCSV($basketgroupid);
302 Export a basket group as CSV
304 $cgi parameter is needed for column name translation
310 sub GetBasketGroupAsCSV {
311 my ($basketgroupid, $cgi) = @_;
312 my $baskets = GetBasketsByBasketgroup($basketgroupid);
314 my $template = C4::Templates::gettemplate('acqui/csv/basketgroup.tmpl', 'intranet', $cgi);
317 for my $basket (@$baskets) {
318 my @orders = GetOrders( $$basket{basketno} );
319 my $contract = GetContract( $$basket{contractnumber} );
320 my $bookseller = GetBookSellerFromId( $$basket{booksellerid} );
321 my $basketgroup = GetBasketgroup( $$basket{basketgroupid} );
323 foreach my $order (@orders) {
324 my $bd = GetBiblioData( $order->{'biblionumber'} );
326 clientnumber => $bookseller->{accountnumber},
327 basketname => $basket->{basketname},
328 ordernumber => $order->{ordernumber},
329 author => $bd->{author},
330 title => $bd->{title},
331 publishercode => $bd->{publishercode},
332 publicationyear => $bd->{publicationyear},
333 collectiontitle => $bd->{collectiontitle},
334 isbn => $order->{isbn},
335 quantity => $order->{quantity},
336 rrp => $order->{rrp},
337 discount => $bookseller->{discount},
338 ecost => $order->{ecost},
339 notes => $order->{notes},
340 entrydate => $order->{entrydate},
341 booksellername => $bookseller->{name},
342 bookselleraddress => $bookseller->{address1},
343 booksellerpostal => $bookseller->{postal},
344 contractnumber => $contract->{contractnumber},
345 contractname => $contract->{contractname},
346 basketgroupdeliveryplace => C4::Branch::GetBranchName( $basketgroup->{deliveryplace} ),
347 basketgroupbillingplace => C4::Branch::GetBranchName( $basketgroup->{billingplace} ),
348 basketdeliveryplace => C4::Branch::GetBranchName( $basket->{deliveryplace} ),
349 basketbillingplace => C4::Branch::GetBranchName( $basket->{billingplace} ),
352 basketname author title publishercode collectiontitle notes
353 booksellername bookselleraddress booksellerpostal contractname
354 basketgroupdeliveryplace basketgroupbillingplace
355 basketdeliveryplace basketbillingplace
357 # Double the quotes to not be interpreted as a field end
358 $row->{$_} =~ s/"/""/g if $row->{$_};
363 $template->param(rows => \@rows);
365 return $template->output;
369 =head3 CloseBasketgroup
371 &CloseBasketgroup($basketgroupno);
377 sub CloseBasketgroup {
378 my ($basketgroupno) = @_;
379 my $dbh = C4::Context->dbh;
380 my $sth = $dbh->prepare("
381 UPDATE aqbasketgroups
385 $sth->execute($basketgroupno);
388 #------------------------------------------------------------#
390 =head3 ReOpenBaskergroup($basketgroupno)
392 &ReOpenBaskergroup($basketgroupno);
398 sub ReOpenBasketgroup {
399 my ($basketgroupno) = @_;
400 my $dbh = C4::Context->dbh;
401 my $sth = $dbh->prepare("
402 UPDATE aqbasketgroups
406 $sth->execute($basketgroupno);
409 #------------------------------------------------------------#
414 &DelBasket($basketno);
416 Deletes the basket that has basketno field $basketno in the aqbasket table.
420 =item C<$basketno> is the primary key of the basket in the aqbasket table.
427 my ( $basketno ) = @_;
428 my $query = "DELETE FROM aqbasket WHERE basketno=?";
429 my $dbh = C4::Context->dbh;
430 my $sth = $dbh->prepare($query);
431 $sth->execute($basketno);
435 #------------------------------------------------------------#
439 &ModBasket($basketinfo);
441 Modifies a basket, using a hashref $basketinfo for the relevant information, only $basketinfo->{'basketno'} is required.
445 =item C<$basketno> is the primary key of the basket in the aqbasket table.
452 my $basketinfo = shift;
453 my $query = "UPDATE aqbasket SET ";
455 foreach my $key (keys %$basketinfo){
456 if ($key ne 'basketno'){
457 $query .= "$key=?, ";
458 push(@params, $basketinfo->{$key} || undef );
461 # get rid of the "," at the end of $query
462 if (substr($query, length($query)-2) eq ', '){
467 $query .= "WHERE basketno=?";
468 push(@params, $basketinfo->{'basketno'});
469 my $dbh = C4::Context->dbh;
470 my $sth = $dbh->prepare($query);
471 $sth->execute(@params);
475 #------------------------------------------------------------#
477 =head3 ModBasketHeader
479 &ModBasketHeader($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid);
481 Modifies a basket's header.
485 =item C<$basketno> is the "basketno" field in the "aqbasket" table;
487 =item C<$basketname> is the "basketname" field in the "aqbasket" table;
489 =item C<$note> is the "note" field in the "aqbasket" table;
491 =item C<$booksellernote> is the "booksellernote" field in the "aqbasket" table;
493 =item C<$contractnumber> is the "contractnumber" (foreign) key in the "aqbasket" table.
495 =item C<$booksellerid> is the id (foreign) key in the "aqbooksellers" table for the vendor.
497 =item C<$deliveryplace> is the "deliveryplace" field in the aqbasket table.
499 =item C<$billingplace> is the "billingplace" field in the aqbasket table.
505 sub ModBasketHeader {
506 my ($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid, $deliveryplace, $billingplace) = @_;
509 SET basketname=?, note=?, booksellernote=?, booksellerid=?, deliveryplace=?, billingplace=?
513 my $dbh = C4::Context->dbh;
514 my $sth = $dbh->prepare($query);
515 $sth->execute($basketname, $note, $booksellernote, $booksellerid, $deliveryplace, $billingplace, $basketno);
517 if ( $contractnumber ) {
518 my $query2 ="UPDATE aqbasket SET contractnumber=? WHERE basketno=?";
519 my $sth2 = $dbh->prepare($query2);
520 $sth2->execute($contractnumber,$basketno);
526 #------------------------------------------------------------#
528 =head3 GetBasketsByBookseller
530 @results = &GetBasketsByBookseller($booksellerid, $extra);
532 Returns a list of hashes of all the baskets that belong to bookseller 'booksellerid'.
536 =item C<$booksellerid> is the 'id' field of the bookseller in the aqbooksellers table
538 =item C<$extra> is the extra sql parameters, can be
540 $extra->{groupby}: group baskets by column
541 ex. $extra->{groupby} = aqbasket.basketgroupid
542 $extra->{orderby}: order baskets by column
543 $extra->{limit}: limit number of results (can be helpful for pagination)
549 sub GetBasketsByBookseller {
550 my ($booksellerid, $extra) = @_;
551 my $query = "SELECT * FROM aqbasket WHERE booksellerid=?";
553 if ($extra->{groupby}) {
554 $query .= " GROUP by $extra->{groupby}";
556 if ($extra->{orderby}){
557 $query .= " ORDER by $extra->{orderby}";
559 if ($extra->{limit}){
560 $query .= " LIMIT $extra->{limit}";
563 my $dbh = C4::Context->dbh;
564 my $sth = $dbh->prepare($query);
565 $sth->execute($booksellerid);
566 my $results = $sth->fetchall_arrayref({});
571 =head3 GetBasketsInfosByBookseller
573 my $baskets = GetBasketsInfosByBookseller($supplierid, $allbaskets);
575 The optional second parameter allbaskets is a boolean allowing you to
576 select all baskets from the supplier; by default only active baskets (open or
577 closed but still something to receive) are returned.
579 Returns in a arrayref of hashref all about booksellers baskets, plus:
580 total_biblios: Number of distinct biblios in basket
581 total_items: Number of items in basket
582 expected_items: Number of non-received items in basket
586 sub GetBasketsInfosByBookseller {
587 my ($supplierid, $allbaskets) = @_;
589 return unless $supplierid;
591 my $dbh = C4::Context->dbh;
594 SUM(aqorders.quantity) AS total_items,
595 COUNT(DISTINCT aqorders.biblionumber) AS total_biblios,
597 IF(aqorders.datereceived IS NULL
598 AND aqorders.datecancellationprinted IS NULL
603 LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
604 WHERE booksellerid = ?};
606 $query.=" AND (closedate IS NULL OR (aqorders.quantity > aqorders.quantityreceived AND datecancellationprinted IS NULL))";
608 $query.=" GROUP BY aqbasket.basketno";
610 my $sth = $dbh->prepare($query);
611 $sth->execute($supplierid);
612 return $sth->fetchall_arrayref({});
616 #------------------------------------------------------------#
618 =head3 GetBasketsByBasketgroup
620 $baskets = &GetBasketsByBasketgroup($basketgroupid);
622 Returns a reference to all baskets that belong to basketgroup $basketgroupid.
626 sub GetBasketsByBasketgroup {
627 my $basketgroupid = shift;
629 SELECT *, aqbasket.booksellerid as booksellerid
631 LEFT JOIN aqcontract USING(contractnumber) WHERE basketgroupid=?
633 my $dbh = C4::Context->dbh;
634 my $sth = $dbh->prepare($query);
635 $sth->execute($basketgroupid);
636 my $results = $sth->fetchall_arrayref({});
641 #------------------------------------------------------------#
643 =head3 NewBasketgroup
645 $basketgroupid = NewBasketgroup(\%hashref);
647 Adds a basketgroup to the aqbasketgroups table, and add the initial baskets to it.
649 $hashref->{'booksellerid'} is the 'id' field of the bookseller in the aqbooksellers table,
651 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
653 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
655 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
657 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
659 $hashref->{'freedeliveryplace'} is the 'freedeliveryplace' field of the basketgroup in the aqbasketgroups table,
661 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
663 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
668 my $basketgroupinfo = shift;
669 die "booksellerid is required to create a basketgroup" unless $basketgroupinfo->{'booksellerid'};
670 my $query = "INSERT INTO aqbasketgroups (";
672 foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
673 if ( defined $basketgroupinfo->{$field} ) {
674 $query .= "$field, ";
675 push(@params, $basketgroupinfo->{$field});
678 $query .= "booksellerid) VALUES (";
683 push(@params, $basketgroupinfo->{'booksellerid'});
684 my $dbh = C4::Context->dbh;
685 my $sth = $dbh->prepare($query);
686 $sth->execute(@params);
687 my $basketgroupid = $dbh->{'mysql_insertid'};
688 if( $basketgroupinfo->{'basketlist'} ) {
689 foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
690 my $query2 = "UPDATE aqbasket SET basketgroupid=? WHERE basketno=?";
691 my $sth2 = $dbh->prepare($query2);
692 $sth2->execute($basketgroupid, $basketno);
695 return $basketgroupid;
698 #------------------------------------------------------------#
700 =head3 ModBasketgroup
702 ModBasketgroup(\%hashref);
704 Modifies a basketgroup in the aqbasketgroups table, and add the baskets to it.
706 $hashref->{'id'} is the 'id' field of the basketgroup in the aqbasketgroup table, this parameter is mandatory,
708 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
710 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
712 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
714 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
716 $hashref->{'freedeliveryplace'} is the 'freedeliveryplace' field of the basketgroup in the aqbasketgroups table,
718 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
720 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
725 my $basketgroupinfo = shift;
726 die "basketgroup id is required to edit a basketgroup" unless $basketgroupinfo->{'id'};
727 my $dbh = C4::Context->dbh;
728 my $query = "UPDATE aqbasketgroups SET ";
730 foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
731 if ( defined $basketgroupinfo->{$field} ) {
732 $query .= "$field=?, ";
733 push(@params, $basketgroupinfo->{$field});
738 $query .= " WHERE id=?";
739 push(@params, $basketgroupinfo->{'id'});
740 my $sth = $dbh->prepare($query);
741 $sth->execute(@params);
743 $sth = $dbh->prepare('UPDATE aqbasket SET basketgroupid = NULL WHERE basketgroupid = ?');
744 $sth->execute($basketgroupinfo->{'id'});
746 if($basketgroupinfo->{'basketlist'} && @{$basketgroupinfo->{'basketlist'}}){
747 $sth = $dbh->prepare("UPDATE aqbasket SET basketgroupid=? WHERE basketno=?");
748 foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
749 $sth->execute($basketgroupinfo->{'id'}, $basketno);
756 #------------------------------------------------------------#
758 =head3 DelBasketgroup
760 DelBasketgroup($basketgroupid);
762 Deletes a basketgroup in the aqbasketgroups table, and removes the reference to it from the baskets,
766 =item C<$basketgroupid> is the 'id' field of the basket in the aqbasketgroup table
773 my $basketgroupid = shift;
774 die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
775 my $query = "DELETE FROM aqbasketgroups WHERE id=?";
776 my $dbh = C4::Context->dbh;
777 my $sth = $dbh->prepare($query);
778 $sth->execute($basketgroupid);
782 #------------------------------------------------------------#
785 =head2 FUNCTIONS ABOUT ORDERS
787 =head3 GetBasketgroup
789 $basketgroup = &GetBasketgroup($basketgroupid);
791 Returns a reference to the hash containing all infermation about the basketgroup.
796 my $basketgroupid = shift;
797 die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
798 my $query = "SELECT * FROM aqbasketgroups WHERE id=?";
799 my $dbh = C4::Context->dbh;
800 my $sth = $dbh->prepare($query);
801 $sth->execute($basketgroupid);
802 my $result = $sth->fetchrow_hashref;
807 #------------------------------------------------------------#
809 =head3 GetBasketgroups
811 $basketgroups = &GetBasketgroups($booksellerid);
813 Returns a reference to the array of all the basketgroups of bookseller $booksellerid.
817 sub GetBasketgroups {
818 my $booksellerid = shift;
819 die 'bookseller id is required to edit a basketgroup' unless $booksellerid;
820 my $query = 'SELECT * FROM aqbasketgroups WHERE booksellerid=? ORDER BY id DESC';
821 my $dbh = C4::Context->dbh;
822 my $sth = $dbh->prepare($query);
823 $sth->execute($booksellerid);
824 return $sth->fetchall_arrayref({});
827 #------------------------------------------------------------#
829 =head2 FUNCTIONS ABOUT ORDERS
833 @orders = &GetOrders($basketnumber, $orderby);
835 Looks up the pending (non-cancelled) orders with the given basket
836 number. If C<$booksellerID> is non-empty, only orders from that seller
840 C<&basket> returns a two-element array. C<@orders> is an array of
841 references-to-hash, whose keys are the fields from the aqorders,
842 biblio, and biblioitems tables in the Koha database.
847 my ( $basketno, $orderby ) = @_;
848 my $dbh = C4::Context->dbh;
850 SELECT biblio.*,biblioitems.*,
854 aqorders_transfers.ordernumber_from AS transferred_from,
855 aqorders_transfers.timestamp AS transferred_from_timestamp
857 LEFT JOIN aqbudgets ON aqbudgets.budget_id = aqorders.budget_id
858 LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
859 LEFT JOIN biblioitems ON biblioitems.biblionumber =biblio.biblionumber
860 LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_to = aqorders.ordernumber
862 AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
865 $orderby = "biblioitems.publishercode,biblio.title" unless $orderby;
866 $query .= " ORDER BY $orderby";
867 my $sth = $dbh->prepare($query);
868 $sth->execute($basketno);
869 my $results = $sth->fetchall_arrayref({});
874 #------------------------------------------------------------#
875 =head3 GetOrdersByBiblionumber
877 @orders = &GetOrdersByBiblionumber($biblionumber);
879 Looks up the orders with linked to a specific $biblionumber, including
880 cancelled orders and received orders.
883 C<@orders> is an array of references-to-hash, whose keys are the
884 fields from the aqorders, biblio, and biblioitems tables in the Koha database.
888 sub GetOrdersByBiblionumber {
889 my $biblionumber = shift;
890 return unless $biblionumber;
891 my $dbh = C4::Context->dbh;
893 SELECT biblio.*,biblioitems.*,
897 LEFT JOIN aqbudgets ON aqbudgets.budget_id = aqorders.budget_id
898 LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
899 LEFT JOIN biblioitems ON biblioitems.biblionumber =biblio.biblionumber
900 WHERE aqorders.biblionumber=?
902 my $sth = $dbh->prepare($query);
903 $sth->execute($biblionumber);
904 my $results = $sth->fetchall_arrayref({});
909 #------------------------------------------------------------#
913 $order = &GetOrder($ordernumber);
915 Looks up an order by order number.
917 Returns a reference-to-hash describing the order. The keys of
918 C<$order> are fields from the biblio, biblioitems, aqorders tables of the Koha database.
923 my ($ordernumber) = @_;
924 my $dbh = C4::Context->dbh;
926 SELECT biblioitems.*, biblio.*, aqorders.*
928 LEFT JOIN biblio on biblio.biblionumber=aqorders.biblionumber
929 LEFT JOIN biblioitems on biblioitems.biblionumber=aqorders.biblionumber
930 WHERE aqorders.ordernumber=?
933 my $sth= $dbh->prepare($query);
934 $sth->execute($ordernumber);
935 my $data = $sth->fetchrow_hashref;
940 =head3 GetLastOrderNotReceivedFromSubscriptionid
942 $order = &GetLastOrderNotReceivedFromSubscriptionid($subscriptionid);
944 Returns a reference-to-hash describing the last order not received for a subscription.
948 sub GetLastOrderNotReceivedFromSubscriptionid {
949 my ( $subscriptionid ) = @_;
950 my $dbh = C4::Context->dbh;
952 SELECT * FROM aqorders
953 LEFT JOIN subscription
954 ON ( aqorders.subscriptionid = subscription.subscriptionid )
955 WHERE aqorders.subscriptionid = ?
956 AND aqorders.datereceived IS NULL
959 my $sth = $dbh->prepare( $query );
960 $sth->execute( $subscriptionid );
961 my $order = $sth->fetchrow_hashref;
965 =head3 GetLastOrderReceivedFromSubscriptionid
967 $order = &GetLastOrderReceivedFromSubscriptionid($subscriptionid);
969 Returns a reference-to-hash describing the last order received for a subscription.
973 sub GetLastOrderReceivedFromSubscriptionid {
974 my ( $subscriptionid ) = @_;
975 my $dbh = C4::Context->dbh;
977 SELECT * FROM aqorders
978 LEFT JOIN subscription
979 ON ( aqorders.subscriptionid = subscription.subscriptionid )
980 WHERE aqorders.subscriptionid = ?
981 AND aqorders.datereceived =
983 SELECT MAX( aqorders.datereceived )
985 LEFT JOIN subscription
986 ON ( aqorders.subscriptionid = subscription.subscriptionid )
987 WHERE aqorders.subscriptionid = ?
988 AND aqorders.datereceived IS NOT NULL
990 ORDER BY ordernumber DESC
993 my $sth = $dbh->prepare( $query );
994 $sth->execute( $subscriptionid, $subscriptionid );
995 my $order = $sth->fetchrow_hashref;
1001 #------------------------------------------------------------#
1005 &NewOrder(\%hashref);
1007 Adds a new order to the database. Any argument that isn't described
1008 below is the new value of the field with the same name in the aqorders
1009 table of the Koha database.
1013 =item $hashref->{'basketno'} is the basketno foreign key in aqorders, it is mandatory
1015 =item $hashref->{'ordernumber'} is a "minimum order number."
1017 =item $hashref->{'budgetdate'} is effectively ignored.
1018 If it's undef (anything false) or the string 'now', the current day is used.
1019 Else, the upcoming July 1st is used.
1021 =item $hashref->{'subscription'} may be either "yes", or anything else for "no".
1023 =item $hashref->{'uncertainprice'} may be 0 for "the price is known" or 1 for "the price is uncertain"
1025 =item defaults entrydate to Now
1027 The following keys are used: "biblionumber", "title", "basketno", "quantity", "notes", "rrp", "ecost", "gstrate", "unitprice", "subscription", "sort1", "sort2", "booksellerinvoicenumber", "listprice", "budgetdate", "purchaseordernumber", "branchcode", "booksellerinvoicenumber", "budget_id".
1034 my $orderinfo = shift;
1035 #### ------------------------------
1036 my $dbh = C4::Context->dbh;
1040 # if these parameters are missing, we can't continue
1041 for my $key (qw/basketno quantity biblionumber budget_id/) {
1042 croak "Mandatory parameter $key missing" unless $orderinfo->{$key};
1045 if ( defined $orderinfo->{subscription} && $orderinfo->{'subscription'} eq 'yes' ) {
1046 $orderinfo->{'subscription'} = 1;
1048 $orderinfo->{'subscription'} = 0;
1050 $orderinfo->{'entrydate'} ||= C4::Dates->new()->output("iso");
1051 if (!$orderinfo->{quantityreceived}) {
1052 $orderinfo->{quantityreceived} = 0;
1055 my $ordernumber=InsertInTable("aqorders",$orderinfo);
1056 if (not $orderinfo->{parent_ordernumber}) {
1057 my $sth = $dbh->prepare("
1059 SET parent_ordernumber = ordernumber
1060 WHERE ordernumber = ?
1062 $sth->execute($ordernumber);
1064 return ( $orderinfo->{'basketno'}, $ordernumber );
1069 #------------------------------------------------------------#
1078 my ($itemnumber, $ordernumber) = @_;
1079 my $dbh = C4::Context->dbh;
1081 INSERT INTO aqorders_items
1082 (itemnumber, ordernumber)
1085 my $sth = $dbh->prepare($query);
1086 $sth->execute( $itemnumber, $ordernumber);
1089 #------------------------------------------------------------#
1093 &ModOrder(\%hashref);
1095 Modifies an existing order. Updates the order with order number
1096 $hashref->{'ordernumber'} and biblionumber $hashref->{'biblionumber'}. All
1097 other keys of the hash update the fields with the same name in the aqorders
1098 table of the Koha database.
1103 my $orderinfo = shift;
1105 die "Ordernumber is required" if $orderinfo->{'ordernumber'} eq '' ;
1106 die "Biblionumber is required" if $orderinfo->{'biblionumber'} eq '';
1108 my $dbh = C4::Context->dbh;
1111 # update uncertainprice to an integer, just in case (under FF, checked boxes have the value "ON" by default)
1112 $orderinfo->{uncertainprice}=1 if $orderinfo->{uncertainprice};
1114 # delete($orderinfo->{'branchcode'});
1115 # the hash contains a lot of entries not in aqorders, so get the columns ...
1116 my $sth = $dbh->prepare("SELECT * FROM aqorders LIMIT 1;");
1118 my $colnames = $sth->{NAME};
1119 #FIXME Be careful. If aqorders would have columns with diacritics,
1120 #you should need to decode what you get back from NAME.
1121 #See report 10110 and guided_reports.pl
1122 my $query = "UPDATE aqorders SET ";
1124 foreach my $orderinfokey (grep(!/ordernumber/, keys %$orderinfo)){
1125 # ... and skip hash entries that are not in the aqorders table
1126 # FIXME : probably not the best way to do it (would be better to have a correct hash)
1127 next unless grep(/^$orderinfokey$/, @$colnames);
1128 $query .= "$orderinfokey=?, ";
1129 push(@params, $orderinfo->{$orderinfokey});
1132 $query .= "timestamp=NOW() WHERE ordernumber=?";
1133 # push(@params, $specorderinfo{'ordernumber'});
1134 push(@params, $orderinfo->{'ordernumber'} );
1135 $sth = $dbh->prepare($query);
1136 $sth->execute(@params);
1140 #------------------------------------------------------------#
1144 ModItemOrder($itemnumber, $ordernumber);
1146 Modifies the ordernumber of an item in aqorders_items.
1151 my ($itemnumber, $ordernumber) = @_;
1153 return unless ($itemnumber and $ordernumber);
1155 my $dbh = C4::Context->dbh;
1157 UPDATE aqorders_items
1159 WHERE itemnumber = ?
1161 my $sth = $dbh->prepare($query);
1162 return $sth->execute($ordernumber, $itemnumber);
1165 #------------------------------------------------------------#
1167 =head3 GetCancelledOrders
1169 my @orders = GetCancelledOrders($basketno, $orderby);
1171 Returns cancelled orders for a basket
1175 sub GetCancelledOrders {
1176 my ( $basketno, $orderby ) = @_;
1178 return () unless $basketno;
1180 my $dbh = C4::Context->dbh;
1187 aqorders_transfers.ordernumber_to AS transferred_to,
1188 aqorders_transfers.timestamp AS transferred_to_timestamp
1190 LEFT JOIN aqbudgets ON aqbudgets.budget_id = aqorders.budget_id
1191 LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1192 LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
1193 LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_from = aqorders.ordernumber
1195 AND (datecancellationprinted IS NOT NULL
1196 AND datecancellationprinted <> '0000-00-00')
1199 $orderby = "aqorders.datecancellationprinted desc, aqorders.timestamp desc"
1201 $query .= " ORDER BY $orderby";
1202 my $sth = $dbh->prepare($query);
1203 $sth->execute($basketno);
1204 my $results = $sth->fetchall_arrayref( {} );
1210 #------------------------------------------------------------#
1212 =head3 ModReceiveOrder
1214 &ModReceiveOrder($biblionumber, $ordernumber, $quantityreceived, $user,
1215 $cost, $ecost, $invoiceid, rrp, budget_id, datereceived, \@received_itemnumbers);
1217 Updates an order, to reflect the fact that it was received, at least
1218 in part. All arguments not mentioned below update the fields with the
1219 same name in the aqorders table of the Koha database.
1221 If a partial order is received, splits the order into two.
1223 Updates the order with bibilionumber C<$biblionumber> and ordernumber
1229 sub ModReceiveOrder {
1231 $biblionumber, $ordernumber, $quantrec, $user, $cost, $ecost,
1232 $invoiceid, $rrp, $budget_id, $datereceived, $received_items
1236 my $dbh = C4::Context->dbh;
1237 $datereceived = C4::Dates->output('iso') unless $datereceived;
1238 my $suggestionid = GetSuggestionFromBiblionumber( $biblionumber );
1239 if ($suggestionid) {
1240 ModSuggestion( {suggestionid=>$suggestionid,
1241 STATUS=>'AVAILABLE',
1242 biblionumber=> $biblionumber}
1246 my $sth=$dbh->prepare("
1247 SELECT * FROM aqorders
1248 WHERE biblionumber=? AND aqorders.ordernumber=?");
1250 $sth->execute($biblionumber,$ordernumber);
1251 my $order = $sth->fetchrow_hashref();
1254 my $new_ordernumber = $ordernumber;
1255 if ( $order->{quantity} > $quantrec ) {
1256 # Split order line in two parts: the first is the original order line
1257 # without received items (the quantity is decreased),
1258 # the second part is a new order line with quantity=quantityrec
1259 # (entirely received)
1260 $sth=$dbh->prepare("
1263 WHERE ordernumber = ?
1266 $sth->execute($order->{quantity} - $quantrec, $ordernumber);
1270 delete $order->{'ordernumber'};
1271 $order->{'quantity'} = $quantrec;
1272 $order->{'quantityreceived'} = $quantrec;
1273 $order->{'datereceived'} = $datereceived;
1274 $order->{'invoiceid'} = $invoiceid;
1275 $order->{'unitprice'} = $cost;
1276 $order->{'rrp'} = $rrp;
1277 $order->{ecost} = $ecost;
1278 $order->{'orderstatus'} = 3; # totally received
1280 ( $basketno, $new_ordernumber ) = NewOrder($order);
1282 if ($received_items) {
1283 foreach my $itemnumber (@$received_items) {
1284 ModItemOrder($itemnumber, $new_ordernumber);
1288 $sth=$dbh->prepare("update aqorders
1289 set quantityreceived=?,datereceived=?,invoiceid=?,
1290 unitprice=?,rrp=?,ecost=?
1291 where biblionumber=? and ordernumber=?");
1292 $sth->execute($quantrec,$datereceived,$invoiceid,$cost,$rrp,$ecost,$biblionumber,$ordernumber);
1295 return ($datereceived, $new_ordernumber);
1298 =head3 CancelReceipt
1300 my $parent_ordernumber = CancelReceipt($ordernumber);
1302 Cancel an order line receipt and update the parent order line, as if no
1304 If items are created at receipt (AcqCreateItem = receiving) then delete
1310 my $ordernumber = shift;
1312 return unless $ordernumber;
1314 my $dbh = C4::Context->dbh;
1316 SELECT datereceived, parent_ordernumber, quantity
1318 WHERE ordernumber = ?
1320 my $sth = $dbh->prepare($query);
1321 $sth->execute($ordernumber);
1322 my $order = $sth->fetchrow_hashref;
1324 warn "CancelReceipt: order $ordernumber does not exist";
1327 unless($order->{'datereceived'}) {
1328 warn "CancelReceipt: order $ordernumber is not received";
1332 my $parent_ordernumber = $order->{'parent_ordernumber'};
1334 if($parent_ordernumber == $ordernumber || not $parent_ordernumber) {
1335 # The order line has no parent, just mark it as not received
1338 SET quantityreceived = ?,
1341 WHERE ordernumber = ?
1343 $sth = $dbh->prepare($query);
1344 $sth->execute(0, undef, undef, $ordernumber);
1346 # The order line has a parent, increase parent quantity and delete
1349 SELECT quantity, datereceived
1351 WHERE ordernumber = ?
1353 $sth = $dbh->prepare($query);
1354 $sth->execute($parent_ordernumber);
1355 my $parent_order = $sth->fetchrow_hashref;
1356 unless($parent_order) {
1357 warn "Parent order $parent_ordernumber does not exist.";
1360 if($parent_order->{'datereceived'}) {
1361 warn "CancelReceipt: parent order is received.".
1362 " Can't cancel receipt.";
1368 WHERE ordernumber = ?
1370 $sth = $dbh->prepare($query);
1371 my $rv = $sth->execute(
1372 $order->{'quantity'} + $parent_order->{'quantity'},
1376 warn "Cannot update parent order line, so do not cancel".
1380 if(C4::Context->preference('AcqCreateItem') eq 'receiving') {
1381 # Remove items that were created at receipt
1383 DELETE FROM items, aqorders_items
1384 USING items, aqorders_items
1385 WHERE items.itemnumber = ? AND aqorders_items.itemnumber = ?
1387 $sth = $dbh->prepare($query);
1388 my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
1389 foreach my $itemnumber (@itemnumbers) {
1390 $sth->execute($itemnumber, $itemnumber);
1394 my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
1395 foreach my $itemnumber (@itemnumbers) {
1396 ModItemOrder($itemnumber, $parent_ordernumber);
1401 DELETE FROM aqorders
1402 WHERE ordernumber = ?
1404 $sth = $dbh->prepare($query);
1405 $sth->execute($ordernumber);
1409 return $parent_ordernumber;
1412 #------------------------------------------------------------#
1416 @results = &SearchOrders({
1417 ordernumber => $ordernumber,
1419 biblionumber => $biblionumber,
1421 booksellerid => $booksellerid,
1422 basketno => $basketno,
1427 Searches for orders.
1429 C<$owner> Finds order for the logged in user.
1430 C<$pending> Finds pending orders. Ignores completed and cancelled orders.
1433 C<@results> is an array of references-to-hash with the keys are fields
1434 from aqorders, biblio, biblioitems and aqbasket tables.
1439 my ( $params ) = @_;
1440 my $ordernumber = $params->{ordernumber};
1441 my $search = $params->{search};
1442 my $ean = $params->{ean};
1443 my $booksellerid = $params->{booksellerid};
1444 my $basketno = $params->{basketno};
1445 my $basketname = $params->{basketname};
1446 my $basketgroupname = $params->{basketgroupname};
1447 my $owner = $params->{owner};
1448 my $pending = $params->{pending};
1450 my $dbh = C4::Context->dbh;
1453 SELECT aqbasket.basketno,
1455 borrowers.firstname,
1458 biblioitems.biblioitemnumber,
1460 aqbasket.creationdate,
1461 aqbasket.basketname,
1464 LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
1465 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid = aqbasketgroups.id
1466 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
1467 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1468 LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
1469 WHERE (datecancellationprinted is NULL)
1473 AND (quantity > quantityreceived OR quantityreceived is NULL)
1476 my $userenv = C4::Context->userenv;
1477 if ( C4::Context->preference("IndependentBranches") ) {
1478 if ( ( $userenv ) and ( $userenv->{flags} != 1 ) ) {
1481 borrowers.branchcode = ?
1482 OR borrowers.branchcode = ''
1485 push @args, $userenv->{branch};
1489 if ( $ordernumber ) {
1490 $query .= ' AND (aqorders.ordernumber=?)';
1491 push @args, $ordernumber;
1494 $query .= ' AND (biblio.title LIKE ? OR biblio.author LIKE ? OR biblioitems.isbn LIKE ?)';
1495 push @args, ("%$search%","%$search%","%$search%");
1498 $query .= ' AND biblioitems.ean = ?';
1501 if ( $booksellerid ) {
1502 $query .= 'AND aqbasket.booksellerid = ?';
1503 push @args, $booksellerid;
1506 $query .= 'AND aqbasket.basketno = ?';
1507 push @args, $basketno;
1510 $query .= 'AND aqbasket.basketname LIKE ?';
1511 push @args, "%$basketname%";
1513 if( $basketgroupname ) {
1514 $query .= ' AND aqbasketgroups.name LIKE ?';
1515 push @args, "%$basketgroupname%";
1519 $query .= ' AND aqbasket.authorisedby=? ';
1520 push @args, $userenv->{'number'};
1523 $query .= ' ORDER BY aqbasket.basketno';
1525 my $sth = $dbh->prepare($query);
1526 $sth->execute(@args);
1527 return $sth->fetchall_arrayref({});
1530 #------------------------------------------------------------#
1534 &DelOrder($biblionumber, $ordernumber);
1536 Cancel the order with the given order and biblio numbers. It does not
1537 delete any entries in the aqorders table, it merely marks them as
1543 my ( $bibnum, $ordernumber ) = @_;
1544 my $dbh = C4::Context->dbh;
1547 SET datecancellationprinted=now()
1548 WHERE biblionumber=? AND ordernumber=?
1550 my $sth = $dbh->prepare($query);
1551 $sth->execute( $bibnum, $ordernumber );
1553 my @itemnumbers = GetItemnumbersFromOrder( $ordernumber );
1554 foreach my $itemnumber (@itemnumbers){
1555 C4::Items::DelItem( $dbh, $bibnum, $itemnumber );
1560 =head3 TransferOrder
1562 my $newordernumber = TransferOrder($ordernumber, $basketno);
1564 Transfer an order line to a basket.
1565 Mark $ordernumber as cancelled with an internal note 'Cancelled and transfered
1566 to BOOKSELLER on DATE' and create new order with internal note
1567 'Transfered from BOOKSELLER on DATE'.
1568 Move all attached items to the new order.
1569 Received orders cannot be transfered.
1570 Return the ordernumber of created order.
1575 my ($ordernumber, $basketno) = @_;
1577 return unless ($ordernumber and $basketno);
1579 my $order = GetOrder( $ordernumber );
1580 return if $order->{datereceived};
1581 my $basket = GetBasket($basketno);
1582 return unless $basket;
1584 my $dbh = C4::Context->dbh;
1585 my ($query, $sth, $rv);
1589 SET datecancellationprinted = CAST(NOW() AS date)
1590 WHERE ordernumber = ?
1592 $sth = $dbh->prepare($query);
1593 $rv = $sth->execute($ordernumber);
1595 delete $order->{'ordernumber'};
1596 $order->{'basketno'} = $basketno;
1598 (undef, $newordernumber) = NewOrder($order);
1601 UPDATE aqorders_items
1603 WHERE ordernumber = ?
1605 $sth = $dbh->prepare($query);
1606 $sth->execute($newordernumber, $ordernumber);
1609 INSERT INTO aqorders_transfers (ordernumber_from, ordernumber_to)
1612 $sth = $dbh->prepare($query);
1613 $sth->execute($ordernumber, $newordernumber);
1615 return $newordernumber;
1618 =head2 FUNCTIONS ABOUT PARCELS
1622 #------------------------------------------------------------#
1626 @results = &GetParcel($booksellerid, $code, $date);
1628 Looks up all of the received items from the supplier with the given
1629 bookseller ID at the given date, for the given code (bookseller Invoice number). Ignores cancelled and completed orders.
1631 C<@results> is an array of references-to-hash. The keys of each element are fields from
1632 the aqorders, biblio, and biblioitems tables of the Koha database.
1634 C<@results> is sorted alphabetically by book title.
1639 #gets all orders from a certain supplier, orders them alphabetically
1640 my ( $supplierid, $code, $datereceived ) = @_;
1641 my $dbh = C4::Context->dbh;
1644 if $code; # add % if we search on a given code (otherwise, let him empty)
1646 SELECT authorisedby,
1651 aqorders.biblionumber,
1652 aqorders.ordernumber,
1653 aqorders.parent_ordernumber,
1655 aqorders.quantityreceived,
1663 LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
1664 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
1665 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1666 LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
1668 aqbasket.booksellerid = ?
1669 AND aqinvoices.invoicenumber LIKE ?
1670 AND aqorders.datereceived = ? ";
1672 my @query_params = ( $supplierid, $code, $datereceived );
1673 if ( C4::Context->preference("IndependentBranches") ) {
1674 my $userenv = C4::Context->userenv;
1675 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1676 $strsth .= " and (borrowers.branchcode = ?
1677 or borrowers.branchcode = '')";
1678 push @query_params, $userenv->{branch};
1681 $strsth .= " ORDER BY aqbasket.basketno";
1682 # ## parcelinformation : $strsth
1683 my $sth = $dbh->prepare($strsth);
1684 $sth->execute( @query_params );
1685 while ( my $data = $sth->fetchrow_hashref ) {
1686 push( @results, $data );
1688 # ## countparcelbiblio: scalar(@results)
1694 #------------------------------------------------------------#
1698 $results = &GetParcels($bookseller, $order, $code, $datefrom, $dateto);
1700 get a lists of parcels.
1707 is the bookseller this function has to get parcels.
1710 To know on what criteria the results list has to be ordered.
1713 is the booksellerinvoicenumber.
1715 =item $datefrom & $dateto
1716 to know on what date this function has to filter its search.
1721 a pointer on a hash list containing parcel informations as such :
1727 =item Last operation
1729 =item Number of biblio
1731 =item Number of items
1738 my ($bookseller,$order, $code, $datefrom, $dateto) = @_;
1739 my $dbh = C4::Context->dbh;
1740 my @query_params = ();
1742 SELECT aqinvoices.invoicenumber,
1743 datereceived,purchaseordernumber,
1744 count(DISTINCT biblionumber) AS biblio,
1745 sum(quantity) AS itemsexpected,
1746 sum(quantityreceived) AS itemsreceived
1747 FROM aqorders LEFT JOIN aqbasket ON aqbasket.basketno = aqorders.basketno
1748 LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
1749 WHERE aqbasket.booksellerid = ? and datereceived IS NOT NULL
1751 push @query_params, $bookseller;
1753 if ( defined $code ) {
1754 $strsth .= ' and aqinvoices.invoicenumber like ? ';
1755 # add a % to the end of the code to allow stemming.
1756 push @query_params, "$code%";
1759 if ( defined $datefrom ) {
1760 $strsth .= ' and datereceived >= ? ';
1761 push @query_params, $datefrom;
1764 if ( defined $dateto ) {
1765 $strsth .= 'and datereceived <= ? ';
1766 push @query_params, $dateto;
1769 $strsth .= "group by aqinvoices.invoicenumber,datereceived ";
1771 # can't use a placeholder to place this column name.
1772 # but, we could probably be checking to make sure it is a column that will be fetched.
1773 $strsth .= "order by $order " if ($order);
1775 my $sth = $dbh->prepare($strsth);
1777 $sth->execute( @query_params );
1778 my $results = $sth->fetchall_arrayref({});
1783 #------------------------------------------------------------#
1785 =head3 GetLateOrders
1787 @results = &GetLateOrders;
1789 Searches for bookseller with late orders.
1792 the table of supplier with late issues. This table is full of hashref.
1798 my $supplierid = shift;
1800 my $estimateddeliverydatefrom = shift;
1801 my $estimateddeliverydateto = shift;
1803 my $dbh = C4::Context->dbh;
1805 #BEWARE, order of parenthesis and LEFT JOIN is important for speed
1806 my $dbdriver = C4::Context->config("db_scheme") || "mysql";
1808 my @query_params = ();
1810 SELECT aqbasket.basketno,
1811 aqorders.ordernumber,
1812 DATE(aqbasket.closedate) AS orderdate,
1813 aqorders.rrp AS unitpricesupplier,
1814 aqorders.ecost AS unitpricelib,
1815 aqorders.claims_count AS claims_count,
1816 aqorders.claimed_date AS claimed_date,
1817 aqbudgets.budget_name AS budget,
1818 borrowers.branchcode AS branch,
1819 aqbooksellers.name AS supplier,
1820 aqbooksellers.id AS supplierid,
1821 biblio.author, biblio.title,
1822 biblioitems.publishercode AS publisher,
1823 biblioitems.publicationyear,
1824 ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) AS estimateddeliverydate,
1828 aqorders LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1829 LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
1830 LEFT JOIN aqbudgets ON aqorders.budget_id = aqbudgets.budget_id,
1831 aqbasket LEFT JOIN borrowers ON aqbasket.authorisedby = borrowers.borrowernumber
1832 LEFT JOIN aqbooksellers ON aqbasket.booksellerid = aqbooksellers.id
1833 WHERE aqorders.basketno = aqbasket.basketno
1834 AND ( datereceived = ''
1835 OR datereceived IS NULL
1836 OR aqorders.quantityreceived < aqorders.quantity
1838 AND aqbasket.closedate IS NOT NULL
1839 AND (aqorders.datecancellationprinted IS NULL OR aqorders.datecancellationprinted='0000-00-00')
1842 if ($dbdriver eq "mysql") {
1844 aqorders.quantity - COALESCE(aqorders.quantityreceived,0) AS quantity,
1845 (aqorders.quantity - COALESCE(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
1846 DATEDIFF(CAST(now() AS date),closedate) AS latesince
1848 if ( defined $delay ) {
1849 $from .= " AND (closedate <= DATE_SUB(CAST(now() AS date),INTERVAL ? DAY)) " ;
1850 push @query_params, $delay;
1853 HAVING quantity <> 0
1854 AND unitpricesupplier <> 0
1855 AND unitpricelib <> 0
1858 # FIXME: account for IFNULL as above
1860 aqorders.quantity AS quantity,
1861 aqorders.quantity * aqorders.rrp AS subtotal,
1862 (CAST(now() AS date) - closedate) AS latesince
1864 if ( defined $delay ) {
1865 $from .= " AND (closedate <= (CAST(now() AS date) -(INTERVAL ? DAY)) ";
1866 push @query_params, $delay;
1869 if (defined $supplierid) {
1870 $from .= ' AND aqbasket.booksellerid = ? ';
1871 push @query_params, $supplierid;
1873 if (defined $branch) {
1874 $from .= ' AND borrowers.branchcode LIKE ? ';
1875 push @query_params, $branch;
1878 if ( defined $estimateddeliverydatefrom or defined $estimateddeliverydateto ) {
1879 $from .= ' AND aqbooksellers.deliverytime IS NOT NULL ';
1881 if ( defined $estimateddeliverydatefrom ) {
1882 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) >= ?';
1883 push @query_params, $estimateddeliverydatefrom;
1885 if ( defined $estimateddeliverydateto ) {
1886 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= ?';
1887 push @query_params, $estimateddeliverydateto;
1889 if ( defined $estimateddeliverydatefrom and not defined $estimateddeliverydateto ) {
1890 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= CAST(now() AS date)';
1892 if (C4::Context->preference("IndependentBranches")
1893 && C4::Context->userenv
1894 && C4::Context->userenv->{flags} != 1 ) {
1895 $from .= ' AND borrowers.branchcode LIKE ? ';
1896 push @query_params, C4::Context->userenv->{branch};
1898 my $query = "$select $from $having\nORDER BY latesince, basketno, borrowers.branchcode, supplier";
1899 $debug and print STDERR "GetLateOrders query: $query\nGetLateOrders args: " . join(" ",@query_params);
1900 my $sth = $dbh->prepare($query);
1901 $sth->execute(@query_params);
1903 while (my $data = $sth->fetchrow_hashref) {
1904 $data->{orderdate} = format_date($data->{orderdate});
1905 $data->{claimed_date} = format_date($data->{claimed_date});
1906 push @results, $data;
1911 #------------------------------------------------------------#
1915 (\@order_loop, $total_qty, $total_price, $total_qtyreceived) = GetHistory( %params );
1917 Retreives some acquisition history information
1925 basket - search both basket name and number
1926 booksellerinvoicenumber
1929 $order_loop is a list of hashrefs that each look like this:
1931 'author' => 'Twain, Mark',
1933 'biblionumber' => '215',
1935 'creationdate' => 'MM/DD/YYYY',
1936 'datereceived' => undef,
1939 'invoicenumber' => undef,
1941 'ordernumber' => '1',
1943 'quantityreceived' => undef,
1944 'title' => 'The Adventures of Huckleberry Finn'
1946 $total_qty is the sum of all of the quantities in $order_loop
1947 $total_price is the cost of each in $order_loop times the quantity
1948 $total_qtyreceived is the sum of all of the quantityreceived entries in $order_loop
1953 # don't run the query if there are no parameters (list would be too long for sure !)
1954 croak "No search params" unless @_;
1956 my $title = $params{title};
1957 my $author = $params{author};
1958 my $isbn = $params{isbn};
1959 my $ean = $params{ean};
1960 my $name = $params{name};
1961 my $from_placed_on = $params{from_placed_on};
1962 my $to_placed_on = $params{to_placed_on};
1963 my $basket = $params{basket};
1964 my $booksellerinvoicenumber = $params{booksellerinvoicenumber};
1965 my $basketgroupname = $params{basketgroupname};
1968 my $total_qtyreceived = 0;
1969 my $total_price = 0;
1971 my $dbh = C4::Context->dbh;
1979 aqbasket.basketname,
1980 aqbasket.basketgroupid,
1981 aqbasketgroups.name as groupname,
1983 aqbasket.creationdate,
1984 aqorders.datereceived,
1986 aqorders.quantityreceived,
1988 aqorders.ordernumber,
1990 aqinvoices.invoicenumber,
1991 aqbooksellers.id as id,
1992 aqorders.biblionumber
1994 LEFT JOIN aqbasket ON aqorders.basketno=aqbasket.basketno
1995 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid=aqbasketgroups.id
1996 LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
1997 LEFT JOIN biblioitems ON biblioitems.biblionumber=aqorders.biblionumber
1998 LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
1999 LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid";
2001 $query .= " LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber"
2002 if ( C4::Context->preference("IndependentBranches") );
2004 $query .= " WHERE (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') ";
2006 my @query_params = ();
2009 $query .= " AND biblio.title LIKE ? ";
2010 $title =~ s/\s+/%/g;
2011 push @query_params, "%$title%";
2015 $query .= " AND biblio.author LIKE ? ";
2016 push @query_params, "%$author%";
2020 $query .= " AND biblioitems.isbn LIKE ? ";
2021 push @query_params, "%$isbn%";
2023 if ( defined $ean and $ean ) {
2024 $query .= " AND biblioitems.ean = ? ";
2025 push @query_params, "$ean";
2028 $query .= " AND aqbooksellers.name LIKE ? ";
2029 push @query_params, "%$name%";
2032 if ( $from_placed_on ) {
2033 $query .= " AND creationdate >= ? ";
2034 push @query_params, $from_placed_on;
2037 if ( $to_placed_on ) {
2038 $query .= " AND creationdate <= ? ";
2039 push @query_params, $to_placed_on;
2043 if ($basket =~ m/^\d+$/) {
2044 $query .= " AND aqorders.basketno = ? ";
2045 push @query_params, $basket;
2047 $query .= " AND aqbasket.basketname LIKE ? ";
2048 push @query_params, "%$basket%";
2052 if ($booksellerinvoicenumber) {
2053 $query .= " AND aqinvoices.invoicenumber LIKE ? ";
2054 push @query_params, "%$booksellerinvoicenumber%";
2057 if ($basketgroupname) {
2058 $query .= " AND aqbasketgroups.name LIKE ? ";
2059 push @query_params, "%$basketgroupname%";
2062 if ( C4::Context->preference("IndependentBranches") ) {
2063 my $userenv = C4::Context->userenv;
2064 if ( $userenv && ($userenv->{flags} || 0) != 1 ) {
2065 $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
2066 push @query_params, $userenv->{branch};
2069 $query .= " ORDER BY id";
2070 my $sth = $dbh->prepare($query);
2071 $sth->execute( @query_params );
2073 while ( my $line = $sth->fetchrow_hashref ) {
2074 $line->{count} = $cnt++;
2075 $line->{toggle} = 1 if $cnt % 2;
2076 push @order_loop, $line;
2077 $total_qty += $line->{'quantity'};
2078 $total_qtyreceived += $line->{'quantityreceived'};
2079 $total_price += $line->{'quantity'} * $line->{'ecost'};
2081 return \@order_loop, $total_qty, $total_price, $total_qtyreceived;
2084 =head2 GetRecentAcqui
2086 $results = GetRecentAcqui($days);
2088 C<$results> is a ref to a table which containts hashref
2092 sub GetRecentAcqui {
2094 my $dbh = C4::Context->dbh;
2098 ORDER BY timestamp DESC
2101 my $sth = $dbh->prepare($query);
2103 my $results = $sth->fetchall_arrayref({});
2109 $contractlist = &GetContracts($booksellerid, $activeonly);
2111 Looks up the contracts that belong to a bookseller
2113 Returns a list of contracts
2117 =item C<$booksellerid> is the "id" field in the "aqbooksellers" table.
2119 =item C<$activeonly> if exists get only contracts that are still active.
2126 my ( $booksellerid, $activeonly ) = @_;
2127 my $dbh = C4::Context->dbh;
2129 if (! $activeonly) {
2133 WHERE booksellerid=?
2138 WHERE booksellerid=?
2139 AND contractenddate >= CURDATE( )";
2141 my $sth = $dbh->prepare($query);
2142 $sth->execute( $booksellerid );
2144 while (my $data = $sth->fetchrow_hashref ) {
2145 push(@results, $data);
2151 #------------------------------------------------------------#
2155 $contract = &GetContract($contractID);
2157 Looks up the contract that has PRIMKEY (contractnumber) value $contractID
2164 my ( $contractno ) = @_;
2165 my $dbh = C4::Context->dbh;
2169 WHERE contractnumber=?
2172 my $sth = $dbh->prepare($query);
2173 $sth->execute( $contractno );
2174 my $result = $sth->fetchrow_hashref;
2182 &AddClaim($ordernumber);
2184 Add a claim for an order
2190 my ($ordernumber) = @_;
2191 my $dbh = C4::Context->dbh;
2194 claims_count = claims_count + 1,
2195 claimed_date = CURDATE()
2196 WHERE ordernumber = ?
2198 my $sth = $dbh->prepare($query);
2199 $sth->execute($ordernumber);
2204 my @invoices = GetInvoices(
2205 invoicenumber => $invoicenumber,
2206 suppliername => $suppliername,
2207 shipmentdatefrom => $shipmentdatefrom, # ISO format
2208 shipmentdateto => $shipmentdateto, # ISO format
2209 billingdatefrom => $billingdatefrom, # ISO format
2210 billingdateto => $billingdateto, # ISO format
2211 isbneanissn => $isbn_or_ean_or_issn,
2214 publisher => $publisher,
2215 publicationyear => $publicationyear,
2216 branchcode => $branchcode,
2217 order_by => $order_by
2220 Return a list of invoices that match all given criteria.
2222 $order_by is "column_name (asc|desc)", where column_name is any of
2223 'invoicenumber', 'booksellerid', 'shipmentdate', 'billingdate', 'closedate',
2224 'shipmentcost', 'shipmentcost_budgetid'.
2226 asc is the default if omitted
2233 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2234 closedate shipmentcost shipmentcost_budgetid);
2236 my $dbh = C4::Context->dbh;
2238 SELECT aqinvoices.*, aqbooksellers.name AS suppliername,
2241 aqorders.datereceived IS NOT NULL,
2242 aqorders.biblionumber,
2245 ) AS receivedbiblios,
2246 SUM(aqorders.quantityreceived) AS receiveditems
2248 LEFT JOIN aqbooksellers ON aqbooksellers.id = aqinvoices.booksellerid
2249 LEFT JOIN aqorders ON aqorders.invoiceid = aqinvoices.invoiceid
2250 LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
2251 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
2252 LEFT JOIN subscription ON biblio.biblionumber = subscription.biblionumber
2257 if($args{supplierid}) {
2258 push @bind_strs, " aqinvoices.booksellerid = ? ";
2259 push @bind_args, $args{supplierid};
2261 if($args{invoicenumber}) {
2262 push @bind_strs, " aqinvoices.invoicenumber LIKE ? ";
2263 push @bind_args, "%$args{invoicenumber}%";
2265 if($args{suppliername}) {
2266 push @bind_strs, " aqbooksellers.name LIKE ? ";
2267 push @bind_args, "%$args{suppliername}%";
2269 if($args{shipmentdatefrom}) {
2270 push @bind_strs, " aqinvoices.shipementdate >= ? ";
2271 push @bind_args, $args{shipmentdatefrom};
2273 if($args{shipmentdateto}) {
2274 push @bind_strs, " aqinvoices.shipementdate <= ? ";
2275 push @bind_args, $args{shipmentdateto};
2277 if($args{billingdatefrom}) {
2278 push @bind_strs, " aqinvoices.billingdate >= ? ";
2279 push @bind_args, $args{billingdatefrom};
2281 if($args{billingdateto}) {
2282 push @bind_strs, " aqinvoices.billingdate <= ? ";
2283 push @bind_args, $args{billingdateto};
2285 if($args{isbneanissn}) {
2286 push @bind_strs, " (biblioitems.isbn LIKE ? OR biblioitems.ean LIKE ? OR biblioitems.issn LIKE ? ) ";
2287 push @bind_args, $args{isbneanissn}, $args{isbneanissn}, $args{isbneanissn};
2290 push @bind_strs, " biblio.title LIKE ? ";
2291 push @bind_args, $args{title};
2294 push @bind_strs, " biblio.author LIKE ? ";
2295 push @bind_args, $args{author};
2297 if($args{publisher}) {
2298 push @bind_strs, " biblioitems.publishercode LIKE ? ";
2299 push @bind_args, $args{publisher};
2301 if($args{publicationyear}) {
2302 push @bind_strs, " biblioitems.publicationyear = ? ";
2303 push @bind_args, $args{publicationyear};
2305 if($args{branchcode}) {
2306 push @bind_strs, " aqorders.branchcode = ? ";
2307 push @bind_args, $args{branchcode};
2310 $query .= " WHERE " . join(" AND ", @bind_strs) if @bind_strs;
2311 $query .= " GROUP BY aqinvoices.invoiceid ";
2313 if($args{order_by}) {
2314 my ($column, $direction) = split / /, $args{order_by};
2315 if(grep /^$column$/, @columns) {
2316 $direction ||= 'ASC';
2317 $query .= " ORDER BY $column $direction";
2321 my $sth = $dbh->prepare($query);
2322 $sth->execute(@bind_args);
2324 my $results = $sth->fetchall_arrayref({});
2330 my $invoice = GetInvoice($invoiceid);
2332 Get informations about invoice with given $invoiceid
2334 Return a hash filled with aqinvoices.* fields
2339 my ($invoiceid) = @_;
2342 return unless $invoiceid;
2344 my $dbh = C4::Context->dbh;
2350 my $sth = $dbh->prepare($query);
2351 $sth->execute($invoiceid);
2353 $invoice = $sth->fetchrow_hashref;
2357 =head3 GetInvoiceDetails
2359 my $invoice = GetInvoiceDetails($invoiceid)
2361 Return informations about an invoice + the list of related order lines
2363 Orders informations are in $invoice->{orders} (array ref)
2367 sub GetInvoiceDetails {
2368 my ($invoiceid) = @_;
2370 if ( !defined $invoiceid ) {
2371 carp 'GetInvoiceDetails called without an invoiceid';
2375 my $dbh = C4::Context->dbh;
2377 SELECT aqinvoices.*, aqbooksellers.name AS suppliername
2379 LEFT JOIN aqbooksellers ON aqinvoices.booksellerid = aqbooksellers.id
2382 my $sth = $dbh->prepare($query);
2383 $sth->execute($invoiceid);
2385 my $invoice = $sth->fetchrow_hashref;
2388 SELECT aqorders.*, biblio.*,
2391 LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
2392 LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
2395 $sth = $dbh->prepare($query);
2396 $sth->execute($invoiceid);
2397 $invoice->{orders} = $sth->fetchall_arrayref({});
2398 $invoice->{orders} ||= []; # force an empty arrayref if fetchall_arrayref fails
2405 my $invoiceid = AddInvoice(
2406 invoicenumber => $invoicenumber,
2407 booksellerid => $booksellerid,
2408 shipmentdate => $shipmentdate,
2409 billingdate => $billingdate,
2410 closedate => $closedate,
2411 shipmentcost => $shipmentcost,
2412 shipmentcost_budgetid => $shipmentcost_budgetid
2415 Create a new invoice and return its id or undef if it fails.
2422 return unless(%invoice and $invoice{invoicenumber});
2424 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2425 closedate shipmentcost shipmentcost_budgetid);
2429 foreach my $key (keys %invoice) {
2430 if(0 < grep(/^$key$/, @columns)) {
2431 push @set_strs, "$key = ?";
2432 push @set_args, ($invoice{$key} || undef);
2438 my $dbh = C4::Context->dbh;
2439 my $query = "INSERT INTO aqinvoices SET ";
2440 $query .= join (",", @set_strs);
2441 my $sth = $dbh->prepare($query);
2442 $rv = $sth->execute(@set_args);
2444 $rv = $dbh->last_insert_id(undef, undef, 'aqinvoices', undef);
2453 invoiceid => $invoiceid, # Mandatory
2454 invoicenumber => $invoicenumber,
2455 booksellerid => $booksellerid,
2456 shipmentdate => $shipmentdate,
2457 billingdate => $billingdate,
2458 closedate => $closedate,
2459 shipmentcost => $shipmentcost,
2460 shipmentcost_budgetid => $shipmentcost_budgetid
2463 Modify an invoice, invoiceid is mandatory.
2465 Return undef if it fails.
2472 return unless(%invoice and $invoice{invoiceid});
2474 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2475 closedate shipmentcost shipmentcost_budgetid);
2479 foreach my $key (keys %invoice) {
2480 if(0 < grep(/^$key$/, @columns)) {
2481 push @set_strs, "$key = ?";
2482 push @set_args, ($invoice{$key} || undef);
2486 my $dbh = C4::Context->dbh;
2487 my $query = "UPDATE aqinvoices SET ";
2488 $query .= join(",", @set_strs);
2489 $query .= " WHERE invoiceid = ?";
2491 my $sth = $dbh->prepare($query);
2492 $sth->execute(@set_args, $invoice{invoiceid});
2497 CloseInvoice($invoiceid);
2501 Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => undef);
2506 my ($invoiceid) = @_;
2508 return unless $invoiceid;
2510 my $dbh = C4::Context->dbh;
2513 SET closedate = CAST(NOW() AS DATE)
2516 my $sth = $dbh->prepare($query);
2517 $sth->execute($invoiceid);
2520 =head3 ReopenInvoice
2522 ReopenInvoice($invoiceid);
2526 Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => C4::Dates->new()->output('iso'))
2531 my ($invoiceid) = @_;
2533 return unless $invoiceid;
2535 my $dbh = C4::Context->dbh;
2538 SET closedate = NULL
2541 my $sth = $dbh->prepare($query);
2542 $sth->execute($invoiceid);
2547 DelInvoice($invoiceid);
2549 Delete an invoice if there are no items attached to it.
2554 my ($invoiceid) = @_;
2556 return unless $invoiceid;
2558 my $dbh = C4::Context->dbh;
2564 my $sth = $dbh->prepare($query);
2565 $sth->execute($invoiceid);
2566 my $res = $sth->fetchrow_arrayref;
2567 if ( $res && $res->[0] == 0 ) {
2569 DELETE FROM aqinvoices
2572 my $sth = $dbh->prepare($query);
2573 return ( $sth->execute($invoiceid) > 0 );
2578 =head3 MergeInvoices
2580 MergeInvoices($invoiceid, \@sourceids);
2582 Merge the invoices identified by the IDs in \@sourceids into
2583 the invoice identified by $invoiceid.
2588 my ($invoiceid, $sourceids) = @_;
2590 return unless $invoiceid;
2591 foreach my $sourceid (@$sourceids) {
2592 next if $sourceid == $invoiceid;
2593 my $source = GetInvoiceDetails($sourceid);
2594 foreach my $order (@{$source->{'orders'}}) {
2595 $order->{'invoiceid'} = $invoiceid;
2598 DelInvoice($source->{'invoiceid'});
2608 Koha Development Team <http://koha-community.org/>