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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
29 use C4::Templates qw(gettemplate);
30 use Koha::DateUtils qw( dt_from_string output_pref );
31 use Koha::Acquisition::Order;
32 use Koha::Acquisition::Bookseller;
33 use Koha::Number::Price;
43 use vars qw(@ISA @EXPORT);
49 &GetBasket &NewBasket &CloseBasket &ReopenBasket &DelBasket &ModBasket
50 &GetBasketAsCSV &GetBasketGroupAsCSV
51 &GetBasketsByBookseller &GetBasketsByBasketgroup
52 &GetBasketsInfosByBookseller
54 &GetBasketUsers &ModBasketUsers
59 &ModBasketgroup &NewBasketgroup &DelBasketgroup &GetBasketgroup &CloseBasketgroup
60 &GetBasketgroups &ReOpenBasketgroup
62 &DelOrder &ModOrder &GetOrder &GetOrders &GetOrdersByBiblionumber
63 &GetLateOrders &GetOrderFromItemnumber
64 &SearchOrders &GetHistory &GetRecentAcqui
65 &ModReceiveOrder &CancelReceipt
67 &GetLastOrderNotReceivedFromSubscriptionid &GetLastOrderReceivedFromSubscriptionid
82 &GetItemnumbersFromOrder
85 &GetBiblioCountByBasketno
91 &FillWithDefaultValues
99 sub GetOrderFromItemnumber {
100 my ($itemnumber) = @_;
101 my $dbh = C4::Context->dbh;
104 SELECT * from aqorders LEFT JOIN aqorders_items
105 ON ( aqorders.ordernumber = aqorders_items.ordernumber )
106 WHERE itemnumber = ? |;
108 my $sth = $dbh->prepare($query);
112 $sth->execute($itemnumber);
114 my $order = $sth->fetchrow_hashref;
119 # Returns the itemnumber(s) associated with the ordernumber given in parameter
120 sub GetItemnumbersFromOrder {
121 my ($ordernumber) = @_;
122 my $dbh = C4::Context->dbh;
123 my $query = "SELECT itemnumber FROM aqorders_items WHERE ordernumber=?";
124 my $sth = $dbh->prepare($query);
125 $sth->execute($ordernumber);
128 while (my $order = $sth->fetchrow_hashref) {
129 push @tab, $order->{'itemnumber'};
143 C4::Acquisition - Koha functions for dealing with orders and acquisitions
151 The functions in this module deal with acquisitions, managing book
152 orders, basket and parcels.
156 =head2 FUNCTIONS ABOUT BASKETS
160 $aqbasket = &GetBasket($basketnumber);
162 get all basket informations in aqbasket for a given basket
164 B<returns:> informations for a given basket returned as a hashref.
170 my $dbh = C4::Context->dbh;
173 concat( b.firstname,' ',b.surname) AS authorisedbyname
175 LEFT JOIN borrowers b ON aqbasket.authorisedby=b.borrowernumber
178 my $sth=$dbh->prepare($query);
179 $sth->execute($basketno);
180 my $basket = $sth->fetchrow_hashref;
184 #------------------------------------------------------------#
188 $basket = &NewBasket( $booksellerid, $authorizedby, $basketname,
189 $basketnote, $basketbooksellernote, $basketcontractnumber, $deliveryplace, $billingplace, $is_standing );
191 Create a new basket in aqbasket table
195 =item C<$booksellerid> is a foreign key in the aqbasket table
197 =item C<$authorizedby> is the username of who created the basket
201 The other parameters are optional, see ModBasketHeader for more info on them.
206 my ( $booksellerid, $authorisedby, $basketname, $basketnote,
207 $basketbooksellernote, $basketcontractnumber, $deliveryplace,
208 $billingplace, $is_standing ) = @_;
209 my $dbh = C4::Context->dbh;
211 'INSERT INTO aqbasket (creationdate,booksellerid,authorisedby) '
212 . 'VALUES (now(),?,?)';
213 $dbh->do( $query, {}, $booksellerid, $authorisedby );
215 my $basket = $dbh->{mysql_insertid};
216 $basketname ||= q{}; # default to empty strings
218 $basketbooksellernote ||= q{};
219 ModBasketHeader( $basket, $basketname, $basketnote, $basketbooksellernote,
220 $basketcontractnumber, $booksellerid, $deliveryplace, $billingplace, $is_standing );
224 #------------------------------------------------------------#
228 &CloseBasket($basketno);
230 close a basket (becomes unmodifiable, except for receives)
236 my $dbh = C4::Context->dbh;
237 $dbh->do('UPDATE aqbasket SET closedate=now() WHERE basketno=?', {}, $basketno );
239 $dbh->do( q{UPDATE aqorders SET orderstatus = 'ordered' WHERE basketno = ? AND orderstatus != 'complete'},
246 &ReopenBasket($basketno);
254 my $dbh = C4::Context->dbh;
255 $dbh->do( q{UPDATE aqbasket SET closedate=NULL WHERE basketno=?}, {}, $basketno );
259 SET orderstatus = 'new'
261 AND orderstatus != 'complete'
266 #------------------------------------------------------------#
268 =head3 GetBasketAsCSV
270 &GetBasketAsCSV($basketno);
272 Export a basket as CSV
274 $cgi parameter is needed for column name translation
279 my ($basketno, $cgi) = @_;
280 my $basket = GetBasket($basketno);
281 my @orders = GetOrders($basketno);
282 my $contract = GetContract({
283 contractnumber => $basket->{'contractnumber'}
286 my $template = C4::Templates::gettemplate("acqui/csv/basket.tt", "intranet", $cgi);
289 foreach my $order (@orders) {
290 my $bd = GetBiblioData( $order->{'biblionumber'} );
292 contractname => $contract->{'contractname'},
293 ordernumber => $order->{'ordernumber'},
294 entrydate => $order->{'entrydate'},
295 isbn => $order->{'isbn'},
296 author => $bd->{'author'},
297 title => $bd->{'title'},
298 publicationyear => $bd->{'publicationyear'},
299 publishercode => $bd->{'publishercode'},
300 collectiontitle => $bd->{'collectiontitle'},
301 notes => $order->{'order_vendornote'},
302 quantity => $order->{'quantity'},
303 rrp => $order->{'rrp'},
304 deliveryplace => C4::Branch::GetBranchName( $basket->{'deliveryplace'} ),
305 billingplace => C4::Branch::GetBranchName( $basket->{'billingplace'} ),
308 contractname author title publishercode collectiontitle notes
309 deliveryplace billingplace
311 # Double the quotes to not be interpreted as a field end
312 $row->{$_} =~ s/"/""/g if $row->{$_};
318 if(defined $a->{publishercode} and defined $b->{publishercode}) {
319 $a->{publishercode} cmp $b->{publishercode};
323 $template->param(rows => \@rows);
325 return $template->output;
329 =head3 GetBasketGroupAsCSV
331 &GetBasketGroupAsCSV($basketgroupid);
333 Export a basket group as CSV
335 $cgi parameter is needed for column name translation
339 sub GetBasketGroupAsCSV {
340 my ($basketgroupid, $cgi) = @_;
341 my $baskets = GetBasketsByBasketgroup($basketgroupid);
343 my $template = C4::Templates::gettemplate('acqui/csv/basketgroup.tt', 'intranet', $cgi);
346 for my $basket (@$baskets) {
347 my @orders = GetOrders( $basket->{basketno} );
348 my $contract = GetContract({
349 contractnumber => $basket->{contractnumber}
351 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $basket->{booksellerid} });
352 my $basketgroup = GetBasketgroup( $$basket{basketgroupid} );
354 foreach my $order (@orders) {
355 my $bd = GetBiblioData( $order->{'biblionumber'} );
357 clientnumber => $bookseller->{accountnumber},
358 basketname => $basket->{basketname},
359 ordernumber => $order->{ordernumber},
360 author => $bd->{author},
361 title => $bd->{title},
362 publishercode => $bd->{publishercode},
363 publicationyear => $bd->{publicationyear},
364 collectiontitle => $bd->{collectiontitle},
365 isbn => $order->{isbn},
366 quantity => $order->{quantity},
367 rrp => $order->{rrp},
368 discount => $bookseller->{discount},
369 ecost => $order->{ecost},
370 notes => $order->{order_vendornote},
371 entrydate => $order->{entrydate},
372 booksellername => $bookseller->{name},
373 bookselleraddress => $bookseller->{address1},
374 booksellerpostal => $bookseller->{postal},
375 contractnumber => $contract->{contractnumber},
376 contractname => $contract->{contractname},
377 basketgroupdeliveryplace => C4::Branch::GetBranchName( $basketgroup->{deliveryplace} ),
378 basketgroupbillingplace => C4::Branch::GetBranchName( $basketgroup->{billingplace} ),
379 basketdeliveryplace => C4::Branch::GetBranchName( $basket->{deliveryplace} ),
380 basketbillingplace => C4::Branch::GetBranchName( $basket->{billingplace} ),
383 basketname author title publishercode collectiontitle notes
384 booksellername bookselleraddress booksellerpostal contractname
385 basketgroupdeliveryplace basketgroupbillingplace
386 basketdeliveryplace basketbillingplace
388 # Double the quotes to not be interpreted as a field end
389 $row->{$_} =~ s/"/""/g if $row->{$_};
394 $template->param(rows => \@rows);
396 return $template->output;
400 =head3 CloseBasketgroup
402 &CloseBasketgroup($basketgroupno);
408 sub CloseBasketgroup {
409 my ($basketgroupno) = @_;
410 my $dbh = C4::Context->dbh;
411 my $sth = $dbh->prepare("
412 UPDATE aqbasketgroups
416 $sth->execute($basketgroupno);
419 #------------------------------------------------------------#
421 =head3 ReOpenBaskergroup($basketgroupno)
423 &ReOpenBaskergroup($basketgroupno);
429 sub ReOpenBasketgroup {
430 my ($basketgroupno) = @_;
431 my $dbh = C4::Context->dbh;
432 my $sth = $dbh->prepare("
433 UPDATE aqbasketgroups
437 $sth->execute($basketgroupno);
440 #------------------------------------------------------------#
445 &DelBasket($basketno);
447 Deletes the basket that has basketno field $basketno in the aqbasket table.
451 =item C<$basketno> is the primary key of the basket in the aqbasket table.
458 my ( $basketno ) = @_;
459 my $query = "DELETE FROM aqbasket WHERE basketno=?";
460 my $dbh = C4::Context->dbh;
461 my $sth = $dbh->prepare($query);
462 $sth->execute($basketno);
466 #------------------------------------------------------------#
470 &ModBasket($basketinfo);
472 Modifies a basket, using a hashref $basketinfo for the relevant information, only $basketinfo->{'basketno'} is required.
476 =item C<$basketno> is the primary key of the basket in the aqbasket table.
483 my $basketinfo = shift;
484 my $query = "UPDATE aqbasket SET ";
486 foreach my $key (keys %$basketinfo){
487 if ($key ne 'basketno'){
488 $query .= "$key=?, ";
489 push(@params, $basketinfo->{$key} || undef );
492 # get rid of the "," at the end of $query
493 if (substr($query, length($query)-2) eq ', '){
498 $query .= "WHERE basketno=?";
499 push(@params, $basketinfo->{'basketno'});
500 my $dbh = C4::Context->dbh;
501 my $sth = $dbh->prepare($query);
502 $sth->execute(@params);
507 #------------------------------------------------------------#
509 =head3 ModBasketHeader
511 &ModBasketHeader($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid);
513 Modifies a basket's header.
517 =item C<$basketno> is the "basketno" field in the "aqbasket" table;
519 =item C<$basketname> is the "basketname" field in the "aqbasket" table;
521 =item C<$note> is the "note" field in the "aqbasket" table;
523 =item C<$booksellernote> is the "booksellernote" field in the "aqbasket" table;
525 =item C<$contractnumber> is the "contractnumber" (foreign) key in the "aqbasket" table.
527 =item C<$booksellerid> is the id (foreign) key in the "aqbooksellers" table for the vendor.
529 =item C<$deliveryplace> is the "deliveryplace" field in the aqbasket table.
531 =item C<$billingplace> is the "billingplace" field in the aqbasket table.
533 =item C<$is_standing> is the "is_standing" field in the aqbasket table.
539 sub ModBasketHeader {
540 my ($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid, $deliveryplace, $billingplace, $is_standing) = @_;
543 SET basketname=?, note=?, booksellernote=?, booksellerid=?, deliveryplace=?, billingplace=?, is_standing=?
547 my $dbh = C4::Context->dbh;
548 my $sth = $dbh->prepare($query);
549 $sth->execute($basketname, $note, $booksellernote, $booksellerid, $deliveryplace, $billingplace, $is_standing, $basketno);
551 if ( $contractnumber ) {
552 my $query2 ="UPDATE aqbasket SET contractnumber=? WHERE basketno=?";
553 my $sth2 = $dbh->prepare($query2);
554 $sth2->execute($contractnumber,$basketno);
559 #------------------------------------------------------------#
561 =head3 GetBasketsByBookseller
563 @results = &GetBasketsByBookseller($booksellerid, $extra);
565 Returns a list of hashes of all the baskets that belong to bookseller 'booksellerid'.
569 =item C<$booksellerid> is the 'id' field of the bookseller in the aqbooksellers table
571 =item C<$extra> is the extra sql parameters, can be
573 $extra->{groupby}: group baskets by column
574 ex. $extra->{groupby} = aqbasket.basketgroupid
575 $extra->{orderby}: order baskets by column
576 $extra->{limit}: limit number of results (can be helpful for pagination)
582 sub GetBasketsByBookseller {
583 my ($booksellerid, $extra) = @_;
584 my $query = "SELECT * FROM aqbasket WHERE booksellerid=?";
586 if ($extra->{groupby}) {
587 $query .= " GROUP by $extra->{groupby}";
589 if ($extra->{orderby}){
590 $query .= " ORDER by $extra->{orderby}";
592 if ($extra->{limit}){
593 $query .= " LIMIT $extra->{limit}";
596 my $dbh = C4::Context->dbh;
597 my $sth = $dbh->prepare($query);
598 $sth->execute($booksellerid);
599 return $sth->fetchall_arrayref({});
602 =head3 GetBasketsInfosByBookseller
604 my $baskets = GetBasketsInfosByBookseller($supplierid, $allbaskets);
606 The optional second parameter allbaskets is a boolean allowing you to
607 select all baskets from the supplier; by default only active baskets (open or
608 closed but still something to receive) are returned.
610 Returns in a arrayref of hashref all about booksellers baskets, plus:
611 total_biblios: Number of distinct biblios in basket
612 total_items: Number of items in basket
613 expected_items: Number of non-received items in basket
617 sub GetBasketsInfosByBookseller {
618 my ($supplierid, $allbaskets) = @_;
620 return unless $supplierid;
622 my $dbh = C4::Context->dbh;
625 SUM(aqorders.quantity) AS total_items,
627 IF ( aqorders.orderstatus = 'cancelled', aqorders.quantity, 0 )
628 ) AS total_items_cancelled,
629 COUNT(DISTINCT aqorders.biblionumber) AS total_biblios,
631 IF(aqorders.datereceived IS NULL
632 AND aqorders.datecancellationprinted IS NULL
637 LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
638 WHERE booksellerid = ?};
640 unless ( $allbaskets ) {
641 $query.=" AND (closedate IS NULL OR (aqorders.quantity > aqorders.quantityreceived AND datecancellationprinted IS NULL))";
643 $query.=" GROUP BY aqbasket.basketno";
645 my $sth = $dbh->prepare($query);
646 $sth->execute($supplierid);
647 my $baskets = $sth->fetchall_arrayref({});
649 # Retrieve the number of biblios cancelled
650 my $cancelled_biblios = $dbh->selectall_hashref( q|
651 SELECT COUNT(DISTINCT(biblionumber)) AS total_biblios_cancelled, aqbasket.basketno
653 LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
654 WHERE booksellerid = ?
655 AND aqorders.orderstatus = 'cancelled'
656 GROUP BY aqbasket.basketno
657 |, 'basketno', {}, $supplierid );
659 $_->{total_biblios_cancelled} = $cancelled_biblios->{$_->{basketno}}{total_biblios_cancelled} || 0
665 =head3 GetBasketUsers
667 $basketusers_ids = &GetBasketUsers($basketno);
669 Returns a list of all borrowernumbers that are in basket users list
674 my $basketno = shift;
676 return unless $basketno;
679 SELECT borrowernumber
683 my $dbh = C4::Context->dbh;
684 my $sth = $dbh->prepare($query);
685 $sth->execute($basketno);
686 my $results = $sth->fetchall_arrayref( {} );
689 foreach (@$results) {
690 push @borrowernumbers, $_->{'borrowernumber'};
693 return @borrowernumbers;
696 =head3 ModBasketUsers
698 my @basketusers_ids = (1, 2, 3);
699 &ModBasketUsers($basketno, @basketusers_ids);
701 Delete all users from basket users list, and add users in C<@basketusers_ids>
707 my ($basketno, @basketusers_ids) = @_;
709 return unless $basketno;
711 my $dbh = C4::Context->dbh;
713 DELETE FROM aqbasketusers
716 my $sth = $dbh->prepare($query);
717 $sth->execute($basketno);
720 INSERT INTO aqbasketusers (basketno, borrowernumber)
723 $sth = $dbh->prepare($query);
724 foreach my $basketuser_id (@basketusers_ids) {
725 $sth->execute($basketno, $basketuser_id);
730 =head3 CanUserManageBasket
732 my $bool = CanUserManageBasket($borrower, $basket[, $userflags]);
733 my $bool = CanUserManageBasket($borrowernumber, $basketno[, $userflags]);
735 Check if a borrower can manage a basket, according to system preference
736 AcqViewBaskets, user permissions and basket properties (creator, users list,
739 First parameter can be either a borrowernumber or a hashref as returned by
740 C4::Members::GetMember.
742 Second parameter can be either a basketno or a hashref as returned by
743 C4::Acquisition::GetBasket.
745 The third parameter is optional. If given, it should be a hashref as returned
746 by C4::Auth::getuserflags. If not, getuserflags is called.
748 If user is authorised to manage basket, returns 1.
753 sub CanUserManageBasket {
754 my ($borrower, $basket, $userflags) = @_;
756 if (!ref $borrower) {
757 $borrower = C4::Members::GetMember(borrowernumber => $borrower);
760 $basket = GetBasket($basket);
763 return 0 unless ($basket and $borrower);
765 my $borrowernumber = $borrower->{borrowernumber};
766 my $basketno = $basket->{basketno};
768 my $AcqViewBaskets = C4::Context->preference('AcqViewBaskets');
770 if (!defined $userflags) {
771 my $dbh = C4::Context->dbh;
772 my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE borrowernumber = ?");
773 $sth->execute($borrowernumber);
774 my ($flags) = $sth->fetchrow_array;
777 $userflags = C4::Auth::getuserflags($flags, $borrower->{userid}, $dbh);
780 unless ($userflags->{superlibrarian}
781 || (ref $userflags->{acquisition} && $userflags->{acquisition}->{order_manage_all})
782 || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
784 if (not exists $userflags->{acquisition}) {
788 if ( (ref $userflags->{acquisition} && !$userflags->{acquisition}->{order_manage})
789 || (!ref $userflags->{acquisition} && !$userflags->{acquisition}) ) {
793 if ($AcqViewBaskets eq 'user'
794 && $basket->{authorisedby} != $borrowernumber
795 && ! grep { $borrowernumber eq $_ } GetBasketUsers($basketno)) {
799 if ($AcqViewBaskets eq 'branch' && defined $basket->{branch}
800 && $basket->{branch} ne $borrower->{branchcode}) {
808 #------------------------------------------------------------#
810 =head3 GetBasketsByBasketgroup
812 $baskets = &GetBasketsByBasketgroup($basketgroupid);
814 Returns a reference to all baskets that belong to basketgroup $basketgroupid.
818 sub GetBasketsByBasketgroup {
819 my $basketgroupid = shift;
821 SELECT *, aqbasket.booksellerid as booksellerid
823 LEFT JOIN aqcontract USING(contractnumber) WHERE basketgroupid=?
825 my $dbh = C4::Context->dbh;
826 my $sth = $dbh->prepare($query);
827 $sth->execute($basketgroupid);
828 return $sth->fetchall_arrayref({});
831 #------------------------------------------------------------#
833 =head3 NewBasketgroup
835 $basketgroupid = NewBasketgroup(\%hashref);
837 Adds a basketgroup to the aqbasketgroups table, and add the initial baskets to it.
839 $hashref->{'booksellerid'} is the 'id' field of the bookseller in the aqbooksellers table,
841 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
843 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
845 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
847 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
849 $hashref->{'freedeliveryplace'} is the 'freedeliveryplace' field of the basketgroup in the aqbasketgroups table,
851 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
853 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
858 my $basketgroupinfo = shift;
859 die "booksellerid is required to create a basketgroup" unless $basketgroupinfo->{'booksellerid'};
860 my $query = "INSERT INTO aqbasketgroups (";
862 foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
863 if ( defined $basketgroupinfo->{$field} ) {
864 $query .= "$field, ";
865 push(@params, $basketgroupinfo->{$field});
868 $query .= "booksellerid) VALUES (";
873 push(@params, $basketgroupinfo->{'booksellerid'});
874 my $dbh = C4::Context->dbh;
875 my $sth = $dbh->prepare($query);
876 $sth->execute(@params);
877 my $basketgroupid = $dbh->{'mysql_insertid'};
878 if( $basketgroupinfo->{'basketlist'} ) {
879 foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
880 my $query2 = "UPDATE aqbasket SET basketgroupid=? WHERE basketno=?";
881 my $sth2 = $dbh->prepare($query2);
882 $sth2->execute($basketgroupid, $basketno);
885 return $basketgroupid;
888 #------------------------------------------------------------#
890 =head3 ModBasketgroup
892 ModBasketgroup(\%hashref);
894 Modifies a basketgroup in the aqbasketgroups table, and add the baskets to it.
896 $hashref->{'id'} is the 'id' field of the basketgroup in the aqbasketgroup table, this parameter is mandatory,
898 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
900 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
902 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
904 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
906 $hashref->{'freedeliveryplace'} is the 'freedeliveryplace' field of the basketgroup in the aqbasketgroups table,
908 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
910 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
915 my $basketgroupinfo = shift;
916 die "basketgroup id is required to edit a basketgroup" unless $basketgroupinfo->{'id'};
917 my $dbh = C4::Context->dbh;
918 my $query = "UPDATE aqbasketgroups SET ";
920 foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
921 if ( defined $basketgroupinfo->{$field} ) {
922 $query .= "$field=?, ";
923 push(@params, $basketgroupinfo->{$field});
928 $query .= " WHERE id=?";
929 push(@params, $basketgroupinfo->{'id'});
930 my $sth = $dbh->prepare($query);
931 $sth->execute(@params);
933 $sth = $dbh->prepare('UPDATE aqbasket SET basketgroupid = NULL WHERE basketgroupid = ?');
934 $sth->execute($basketgroupinfo->{'id'});
936 if($basketgroupinfo->{'basketlist'} && @{$basketgroupinfo->{'basketlist'}}){
937 $sth = $dbh->prepare("UPDATE aqbasket SET basketgroupid=? WHERE basketno=?");
938 foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
939 $sth->execute($basketgroupinfo->{'id'}, $basketno);
945 #------------------------------------------------------------#
947 =head3 DelBasketgroup
949 DelBasketgroup($basketgroupid);
951 Deletes a basketgroup in the aqbasketgroups table, and removes the reference to it from the baskets,
955 =item C<$basketgroupid> is the 'id' field of the basket in the aqbasketgroup table
962 my $basketgroupid = shift;
963 die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
964 my $query = "DELETE FROM aqbasketgroups WHERE id=?";
965 my $dbh = C4::Context->dbh;
966 my $sth = $dbh->prepare($query);
967 $sth->execute($basketgroupid);
971 #------------------------------------------------------------#
974 =head2 FUNCTIONS ABOUT ORDERS
976 =head3 GetBasketgroup
978 $basketgroup = &GetBasketgroup($basketgroupid);
980 Returns a reference to the hash containing all information about the basketgroup.
985 my $basketgroupid = shift;
986 die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
987 my $dbh = C4::Context->dbh;
988 my $result_set = $dbh->selectall_arrayref(
989 'SELECT * FROM aqbasketgroups WHERE id=?',
993 return $result_set->[0]; # id is unique
996 #------------------------------------------------------------#
998 =head3 GetBasketgroups
1000 $basketgroups = &GetBasketgroups($booksellerid);
1002 Returns a reference to the array of all the basketgroups of bookseller $booksellerid.
1006 sub GetBasketgroups {
1007 my $booksellerid = shift;
1008 die 'bookseller id is required to edit a basketgroup' unless $booksellerid;
1009 my $query = 'SELECT * FROM aqbasketgroups WHERE booksellerid=? ORDER BY id DESC';
1010 my $dbh = C4::Context->dbh;
1011 my $sth = $dbh->prepare($query);
1012 $sth->execute($booksellerid);
1013 return $sth->fetchall_arrayref({});
1016 #------------------------------------------------------------#
1018 =head2 FUNCTIONS ABOUT ORDERS
1022 @orders = &GetOrders( $basketno, { orderby => 'biblio.title', cancelled => 0|1 } );
1024 Looks up the pending (non-cancelled) orders with the given basket
1027 If cancelled is set, only cancelled orders will be returned.
1032 my ( $basketno, $params ) = @_;
1034 return () unless $basketno;
1036 my $orderby = $params->{orderby};
1037 my $cancelled = $params->{cancelled} || 0;
1039 my $dbh = C4::Context->dbh;
1041 SELECT biblio.*,biblioitems.*,
1045 $query .= $cancelled
1047 aqorders_transfers.ordernumber_to AS transferred_to,
1048 aqorders_transfers.timestamp AS transferred_to_timestamp
1051 aqorders_transfers.ordernumber_from AS transferred_from,
1052 aqorders_transfers.timestamp AS transferred_from_timestamp
1056 LEFT JOIN aqbudgets ON aqbudgets.budget_id = aqorders.budget_id
1057 LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1058 LEFT JOIN biblioitems ON biblioitems.biblionumber =biblio.biblionumber
1060 $query .= $cancelled
1062 LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_from = aqorders.ordernumber
1065 LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_to = aqorders.ordernumber
1073 $orderby ||= q|biblioitems.publishercode, biblio.title|;
1075 AND (datecancellationprinted IS NOT NULL
1076 AND datecancellationprinted <> '0000-00-00')
1081 q|aqorders.datecancellationprinted desc, aqorders.timestamp desc|;
1083 AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
1087 $query .= " ORDER BY $orderby";
1089 $dbh->selectall_arrayref( $query, { Slice => {} }, $basketno );
1094 #------------------------------------------------------------#
1096 =head3 GetOrdersByBiblionumber
1098 @orders = &GetOrdersByBiblionumber($biblionumber);
1100 Looks up the orders with linked to a specific $biblionumber, including
1101 cancelled orders and received orders.
1104 C<@orders> is an array of references-to-hash, whose keys are the
1105 fields from the aqorders, biblio, and biblioitems tables in the Koha database.
1109 sub GetOrdersByBiblionumber {
1110 my $biblionumber = shift;
1111 return unless $biblionumber;
1112 my $dbh = C4::Context->dbh;
1114 SELECT biblio.*,biblioitems.*,
1118 LEFT JOIN aqbudgets ON aqbudgets.budget_id = aqorders.budget_id
1119 LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1120 LEFT JOIN biblioitems ON biblioitems.biblionumber =biblio.biblionumber
1121 WHERE aqorders.biblionumber=?
1124 $dbh->selectall_arrayref( $query, { Slice => {} }, $biblionumber );
1125 return @{$result_set};
1129 #------------------------------------------------------------#
1133 $order = &GetOrder($ordernumber);
1135 Looks up an order by order number.
1137 Returns a reference-to-hash describing the order. The keys of
1138 C<$order> are fields from the biblio, biblioitems, aqorders tables of the Koha database.
1143 my ($ordernumber) = @_;
1144 return unless $ordernumber;
1146 my $dbh = C4::Context->dbh;
1147 my $query = qq{SELECT
1151 aqbasket.basketname,
1152 borrowers.branchcode,
1153 biblioitems.publicationyear,
1154 biblio.copyrightdate,
1155 biblioitems.editionstatement,
1159 biblioitems.publishercode,
1160 aqorders.rrp AS unitpricesupplier,
1161 aqorders.ecost AS unitpricelib,
1162 aqorders.claims_count AS claims_count,
1163 aqorders.claimed_date AS claimed_date,
1164 aqbudgets.budget_name AS budget,
1165 aqbooksellers.name AS supplier,
1166 aqbooksellers.id AS supplierid,
1167 biblioitems.publishercode AS publisher,
1168 ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) AS estimateddeliverydate,
1169 DATE(aqbasket.closedate) AS orderdate,
1170 aqorders.quantity - COALESCE(aqorders.quantityreceived,0) AS quantity_to_receive,
1171 (aqorders.quantity - COALESCE(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
1172 DATEDIFF(CURDATE( ),closedate) AS latesince
1173 FROM aqorders LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1174 LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
1175 LEFT JOIN aqbudgets ON aqorders.budget_id = aqbudgets.budget_id,
1176 aqbasket LEFT JOIN borrowers ON aqbasket.authorisedby = borrowers.borrowernumber
1177 LEFT JOIN aqbooksellers ON aqbasket.booksellerid = aqbooksellers.id
1178 WHERE aqorders.basketno = aqbasket.basketno
1181 $dbh->selectall_arrayref( $query, { Slice => {} }, $ordernumber );
1183 # result_set assumed to contain 1 match
1184 return $result_set->[0];
1187 =head3 GetLastOrderNotReceivedFromSubscriptionid
1189 $order = &GetLastOrderNotReceivedFromSubscriptionid($subscriptionid);
1191 Returns a reference-to-hash describing the last order not received for a subscription.
1195 sub GetLastOrderNotReceivedFromSubscriptionid {
1196 my ( $subscriptionid ) = @_;
1197 my $dbh = C4::Context->dbh;
1199 SELECT * FROM aqorders
1200 LEFT JOIN subscription
1201 ON ( aqorders.subscriptionid = subscription.subscriptionid )
1202 WHERE aqorders.subscriptionid = ?
1203 AND aqorders.datereceived IS NULL
1207 $dbh->selectall_arrayref( $query, { Slice => {} }, $subscriptionid );
1209 # result_set assumed to contain 1 match
1210 return $result_set->[0];
1213 =head3 GetLastOrderReceivedFromSubscriptionid
1215 $order = &GetLastOrderReceivedFromSubscriptionid($subscriptionid);
1217 Returns a reference-to-hash describing the last order received for a subscription.
1221 sub GetLastOrderReceivedFromSubscriptionid {
1222 my ( $subscriptionid ) = @_;
1223 my $dbh = C4::Context->dbh;
1225 SELECT * FROM aqorders
1226 LEFT JOIN subscription
1227 ON ( aqorders.subscriptionid = subscription.subscriptionid )
1228 WHERE aqorders.subscriptionid = ?
1229 AND aqorders.datereceived =
1231 SELECT MAX( aqorders.datereceived )
1233 LEFT JOIN subscription
1234 ON ( aqorders.subscriptionid = subscription.subscriptionid )
1235 WHERE aqorders.subscriptionid = ?
1236 AND aqorders.datereceived IS NOT NULL
1238 ORDER BY ordernumber DESC
1242 $dbh->selectall_arrayref( $query, { Slice => {} }, $subscriptionid, $subscriptionid );
1244 # result_set assumed to contain 1 match
1245 return $result_set->[0];
1249 #------------------------------------------------------------#
1253 &ModOrder(\%hashref);
1255 Modifies an existing order. Updates the order with order number
1256 $hashref->{'ordernumber'} and biblionumber $hashref->{'biblionumber'}. All
1257 other keys of the hash update the fields with the same name in the aqorders
1258 table of the Koha database.
1263 my $orderinfo = shift;
1265 die "Ordernumber is required" if $orderinfo->{'ordernumber'} eq '';
1267 my $dbh = C4::Context->dbh;
1270 # update uncertainprice to an integer, just in case (under FF, checked boxes have the value "ON" by default)
1271 $orderinfo->{uncertainprice}=1 if $orderinfo->{uncertainprice};
1273 # delete($orderinfo->{'branchcode'});
1274 # the hash contains a lot of entries not in aqorders, so get the columns ...
1275 my $sth = $dbh->prepare("SELECT * FROM aqorders LIMIT 1;");
1277 my $colnames = $sth->{NAME};
1278 #FIXME Be careful. If aqorders would have columns with diacritics,
1279 #you should need to decode what you get back from NAME.
1280 #See report 10110 and guided_reports.pl
1281 my $query = "UPDATE aqorders SET ";
1283 foreach my $orderinfokey (grep(!/ordernumber/, keys %$orderinfo)){
1284 # ... and skip hash entries that are not in the aqorders table
1285 # FIXME : probably not the best way to do it (would be better to have a correct hash)
1286 next unless grep(/^$orderinfokey$/, @$colnames);
1287 $query .= "$orderinfokey=?, ";
1288 push(@params, $orderinfo->{$orderinfokey});
1291 $query .= "timestamp=NOW() WHERE ordernumber=?";
1292 push(@params, $orderinfo->{'ordernumber'} );
1293 $sth = $dbh->prepare($query);
1294 $sth->execute(@params);
1298 #------------------------------------------------------------#
1302 ModItemOrder($itemnumber, $ordernumber);
1304 Modifies the ordernumber of an item in aqorders_items.
1309 my ($itemnumber, $ordernumber) = @_;
1311 return unless ($itemnumber and $ordernumber);
1313 my $dbh = C4::Context->dbh;
1315 UPDATE aqorders_items
1317 WHERE itemnumber = ?
1319 my $sth = $dbh->prepare($query);
1320 return $sth->execute($ordernumber, $itemnumber);
1323 #------------------------------------------------------------#
1325 =head3 ModReceiveOrder
1328 biblionumber => $biblionumber,
1329 ordernumber => $ordernumber,
1330 quantityreceived => $quantityreceived,
1334 invoiceid => $invoiceid,
1336 budget_id => $budget_id,
1337 datereceived => $datereceived,
1338 received_itemnumbers => \@received_itemnumbers,
1339 order_internalnote => $order_internalnote,
1340 order_vendornote => $order_vendornote,
1343 Updates an order, to reflect the fact that it was received, at least
1344 in part. All arguments not mentioned below update the fields with the
1345 same name in the aqorders table of the Koha database.
1347 If a partial order is received, splits the order into two.
1349 Updates the order with bibilionumber C<$biblionumber> and ordernumber
1355 sub ModReceiveOrder {
1356 my ( $params ) = @_;
1357 my $biblionumber = $params->{biblionumber};
1358 my $ordernumber = $params->{ordernumber};
1359 my $quantrec = $params->{quantityreceived};
1360 my $user = $params->{user};
1361 my $cost = $params->{cost};
1362 my $ecost = $params->{ecost};
1363 my $invoiceid = $params->{invoiceid};
1364 my $rrp = $params->{rrp};
1365 my $budget_id = $params->{budget_id};
1366 my $datereceived = $params->{datereceived};
1367 my $received_items = $params->{received_items};
1368 my $order_internalnote = $params->{order_internalnote};
1369 my $order_vendornote = $params->{order_vendornote};
1371 my $dbh = C4::Context->dbh;
1372 $datereceived = output_pref(
1374 dt => ( $datereceived ? dt_from_string( $datereceived ) : dt_from_string ),
1375 dateformat => 'iso',
1379 my $suggestionid = GetSuggestionFromBiblionumber( $biblionumber );
1380 if ($suggestionid) {
1381 ModSuggestion( {suggestionid=>$suggestionid,
1382 STATUS=>'AVAILABLE',
1383 biblionumber=> $biblionumber}
1387 my $result_set = $dbh->selectall_arrayref(
1388 q{SELECT *, aqbasket.is_standing FROM aqorders LEFT JOIN aqbasket USING (basketno) WHERE biblionumber=? AND aqorders.ordernumber=?},
1389 { Slice => {} }, $biblionumber, $ordernumber
1392 # we assume we have a unique order
1393 my $order = $result_set->[0];
1395 my $new_ordernumber = $ordernumber;
1396 if ( $order->{is_standing} || $order->{quantity} > $quantrec ) {
1397 # Split order line in two parts: the first is the original order line
1398 # without received items (the quantity is decreased),
1399 # the second part is a new order line with quantity=quantityrec
1400 # (entirely received)
1404 orderstatus = 'partial'|;
1405 $query .= q|, order_internalnote = ?| if defined $order_internalnote;
1406 $query .= q|, order_vendornote = ?| if defined $order_vendornote;
1407 $query .= q| WHERE ordernumber = ?|;
1408 my $sth = $dbh->prepare($query);
1411 ( $order->{is_standing} ? 1 : ( $order->{quantity} - $quantrec ) ),
1412 ( defined $order_internalnote ? $order_internalnote : () ),
1413 ( defined $order_vendornote ? $order_vendornote : () ),
1417 delete $order->{'ordernumber'};
1418 $order->{'budget_id'} = ( $budget_id || $order->{'budget_id'} );
1419 $order->{'quantity'} = $quantrec;
1420 $order->{'quantityreceived'} = $quantrec;
1421 $order->{'datereceived'} = $datereceived;
1422 $order->{'invoiceid'} = $invoiceid;
1423 $order->{'unitprice'} = $cost;
1424 $order->{'rrp'} = $rrp;
1425 $order->{ecost} = $ecost;
1426 $order->{'orderstatus'} = 'complete';
1427 $new_ordernumber = Koha::Acquisition::Order->new($order)->insert->{ordernumber};
1429 if ($received_items) {
1430 foreach my $itemnumber (@$received_items) {
1431 ModItemOrder($itemnumber, $new_ordernumber);
1437 set quantityreceived=?,datereceived=?,invoiceid=?,
1438 unitprice=?,rrp=?,ecost=?,budget_id=?,orderstatus='complete'|;
1439 $query .= q|, order_internalnote = ?| if defined $order_internalnote;
1440 $query .= q|, order_vendornote = ?| if defined $order_vendornote;
1441 $query .= q| where biblionumber=? and ordernumber=?|;
1442 my $sth = $dbh->prepare( $query );
1450 ( $budget_id ? $budget_id : $order->{budget_id} ),
1451 ( defined $order_internalnote ? $order_internalnote : () ),
1452 ( defined $order_vendornote ? $order_vendornote : () ),
1457 # All items have been received, sent a notification to users
1458 NotifyOrderUsers( $ordernumber );
1461 return ($datereceived, $new_ordernumber);
1464 =head3 CancelReceipt
1466 my $parent_ordernumber = CancelReceipt($ordernumber);
1468 Cancel an order line receipt and update the parent order line, as if no
1470 If items are created at receipt (AcqCreateItem = receiving) then delete
1476 my $ordernumber = shift;
1478 return unless $ordernumber;
1480 my $dbh = C4::Context->dbh;
1482 SELECT datereceived, parent_ordernumber, quantity
1484 WHERE ordernumber = ?
1486 my $sth = $dbh->prepare($query);
1487 $sth->execute($ordernumber);
1488 my $order = $sth->fetchrow_hashref;
1490 warn "CancelReceipt: order $ordernumber does not exist";
1493 unless($order->{'datereceived'}) {
1494 warn "CancelReceipt: order $ordernumber is not received";
1498 my $parent_ordernumber = $order->{'parent_ordernumber'};
1500 my @itemnumbers = GetItemnumbersFromOrder( $ordernumber );
1502 if($parent_ordernumber == $ordernumber || not $parent_ordernumber) {
1503 # The order line has no parent, just mark it as not received
1506 SET quantityreceived = ?,
1509 orderstatus = 'ordered'
1510 WHERE ordernumber = ?
1512 $sth = $dbh->prepare($query);
1513 $sth->execute(0, undef, undef, $ordernumber);
1514 _cancel_items_receipt( $ordernumber );
1516 # The order line has a parent, increase parent quantity and delete
1519 SELECT quantity, datereceived
1521 WHERE ordernumber = ?
1523 $sth = $dbh->prepare($query);
1524 $sth->execute($parent_ordernumber);
1525 my $parent_order = $sth->fetchrow_hashref;
1526 unless($parent_order) {
1527 warn "Parent order $parent_ordernumber does not exist.";
1530 if($parent_order->{'datereceived'}) {
1531 warn "CancelReceipt: parent order is received.".
1532 " Can't cancel receipt.";
1538 orderstatus = 'ordered'
1539 WHERE ordernumber = ?
1541 $sth = $dbh->prepare($query);
1542 my $rv = $sth->execute(
1543 $order->{'quantity'} + $parent_order->{'quantity'},
1547 warn "Cannot update parent order line, so do not cancel".
1551 _cancel_items_receipt( $ordernumber, $parent_ordernumber );
1554 DELETE FROM aqorders
1555 WHERE ordernumber = ?
1557 $sth = $dbh->prepare($query);
1558 $sth->execute($ordernumber);
1562 if(C4::Context->preference('AcqCreateItem') eq 'ordering') {
1563 my @affects = split q{\|}, C4::Context->preference("AcqItemSetSubfieldsWhenReceiptIsCancelled");
1565 for my $in ( @itemnumbers ) {
1566 my $biblionumber = C4::Biblio::GetBiblionumberFromItemnumber( $in );
1567 my $frameworkcode = GetFrameworkCode($biblionumber);
1568 my ( $itemfield ) = GetMarcFromKohaField( 'items.itemnumber', $frameworkcode );
1569 my $item = C4::Items::GetMarcItem( $biblionumber, $in );
1570 for my $affect ( @affects ) {
1571 my ( $sf, $v ) = split q{=}, $affect, 2;
1572 foreach ( $item->field($itemfield) ) {
1573 $_->update( $sf => $v );
1576 C4::Items::ModItemFromMarc( $item, $biblionumber, $in );
1581 return $parent_ordernumber;
1584 sub _cancel_items_receipt {
1585 my ( $ordernumber, $parent_ordernumber ) = @_;
1586 $parent_ordernumber ||= $ordernumber;
1588 my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
1589 if(C4::Context->preference('AcqCreateItem') eq 'receiving') {
1590 # Remove items that were created at receipt
1592 DELETE FROM items, aqorders_items
1593 USING items, aqorders_items
1594 WHERE items.itemnumber = ? AND aqorders_items.itemnumber = ?
1596 my $dbh = C4::Context->dbh;
1597 my $sth = $dbh->prepare($query);
1598 foreach my $itemnumber (@itemnumbers) {
1599 $sth->execute($itemnumber, $itemnumber);
1603 foreach my $itemnumber (@itemnumbers) {
1604 ModItemOrder($itemnumber, $parent_ordernumber);
1609 #------------------------------------------------------------#
1613 @results = &SearchOrders({
1614 ordernumber => $ordernumber,
1617 booksellerid => $booksellerid,
1618 basketno => $basketno,
1619 basketname => $basketname,
1620 basketgroupname => $basketgroupname,
1624 biblionumber => $biblionumber,
1625 budget_id => $budget_id
1628 Searches for orders filtered by criteria.
1630 C<$ordernumber> Finds matching orders or transferred orders by ordernumber.
1631 C<$search> Finds orders matching %$search% in title, author, or isbn.
1632 C<$owner> Finds order for the logged in user.
1633 C<$pending> Finds pending orders. Ignores completed and cancelled orders.
1634 C<$ordered> Finds orders to receive only (status 'ordered' or 'partial').
1637 C<@results> is an array of references-to-hash with the keys are fields
1638 from aqorders, biblio, biblioitems and aqbasket tables.
1643 my ( $params ) = @_;
1644 my $ordernumber = $params->{ordernumber};
1645 my $search = $params->{search};
1646 my $ean = $params->{ean};
1647 my $booksellerid = $params->{booksellerid};
1648 my $basketno = $params->{basketno};
1649 my $basketname = $params->{basketname};
1650 my $basketgroupname = $params->{basketgroupname};
1651 my $owner = $params->{owner};
1652 my $pending = $params->{pending};
1653 my $ordered = $params->{ordered};
1654 my $biblionumber = $params->{biblionumber};
1655 my $budget_id = $params->{budget_id};
1657 my $dbh = C4::Context->dbh;
1660 SELECT aqbasket.basketno,
1662 borrowers.firstname,
1665 biblioitems.biblioitemnumber,
1666 aqbasket.authorisedby,
1667 aqbasket.booksellerid,
1669 aqbasket.creationdate,
1670 aqbasket.basketname,
1671 aqbasketgroups.id as basketgroupid,
1672 aqbasketgroups.name as basketgroupname,
1675 LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
1676 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid = aqbasketgroups.id
1677 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
1678 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1679 LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
1682 # If we search on ordernumber, we retrieve the transferred order if a transfer has been done.
1684 LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_to = aqorders.ordernumber
1688 WHERE (datecancellationprinted is NULL)
1691 if ( $pending or $ordered ) {
1694 ( aqbasket.is_standing AND aqorders.orderstatus IN ( "new", "ordered", "partial" ) )
1696 ( quantity > quantityreceived OR quantityreceived is NULL )
1700 $query .= q{ AND aqorders.orderstatus IN ( "ordered", "partial" )};
1708 my $userenv = C4::Context->userenv;
1709 if ( C4::Context->preference("IndependentBranches") ) {
1710 unless ( C4::Context->IsSuperLibrarian() ) {
1713 borrowers.branchcode = ?
1714 OR borrowers.branchcode = ''
1717 push @args, $userenv->{branch};
1721 if ( $ordernumber ) {
1722 $query .= ' AND ( aqorders.ordernumber = ? OR aqorders_transfers.ordernumber_from = ? ) ';
1723 push @args, ( $ordernumber, $ordernumber );
1725 if ( $biblionumber ) {
1726 $query .= 'AND aqorders.biblionumber = ?';
1727 push @args, $biblionumber;
1730 $query .= ' AND (biblio.title LIKE ? OR biblio.author LIKE ? OR biblioitems.isbn LIKE ?)';
1731 push @args, ("%$search%","%$search%","%$search%");
1734 $query .= ' AND biblioitems.ean = ?';
1737 if ( $booksellerid ) {
1738 $query .= 'AND aqbasket.booksellerid = ?';
1739 push @args, $booksellerid;
1742 $query .= 'AND aqbasket.basketno = ?';
1743 push @args, $basketno;
1746 $query .= 'AND aqbasket.basketname LIKE ?';
1747 push @args, "%$basketname%";
1749 if( $basketgroupname ) {
1750 $query .= ' AND aqbasketgroups.name LIKE ?';
1751 push @args, "%$basketgroupname%";
1755 $query .= ' AND aqbasket.authorisedby=? ';
1756 push @args, $userenv->{'number'};
1760 $query .= ' AND aqorders.budget_id = ?';
1761 push @args, $budget_id;
1764 $query .= ' ORDER BY aqbasket.basketno';
1766 my $sth = $dbh->prepare($query);
1767 $sth->execute(@args);
1768 return $sth->fetchall_arrayref({});
1771 #------------------------------------------------------------#
1775 &DelOrder($biblionumber, $ordernumber);
1777 Cancel the order with the given order and biblio numbers. It does not
1778 delete any entries in the aqorders table, it merely marks them as
1784 my ( $bibnum, $ordernumber, $delete_biblio, $reason ) = @_;
1787 my $dbh = C4::Context->dbh;
1790 SET datecancellationprinted=now(), orderstatus='cancelled'
1793 $query .= ", cancellationreason = ? ";
1796 WHERE biblionumber=? AND ordernumber=?
1798 my $sth = $dbh->prepare($query);
1800 $sth->execute($reason, $bibnum, $ordernumber);
1802 $sth->execute( $bibnum, $ordernumber );
1806 my @itemnumbers = GetItemnumbersFromOrder( $ordernumber );
1807 foreach my $itemnumber (@itemnumbers){
1808 my $delcheck = C4::Items::DelItemCheck( $dbh, $bibnum, $itemnumber );
1810 if($delcheck != 1) {
1811 $error->{'delitem'} = 1;
1815 if($delete_biblio) {
1816 # We get the number of remaining items
1817 my $itemcount = C4::Items::GetItemsCount($bibnum);
1819 # If there are no items left,
1820 if ( $itemcount == 0 ) {
1821 # We delete the record
1822 my $delcheck = DelBiblio($bibnum);
1825 $error->{'delbiblio'} = 1;
1833 =head3 TransferOrder
1835 my $newordernumber = TransferOrder($ordernumber, $basketno);
1837 Transfer an order line to a basket.
1838 Mark $ordernumber as cancelled with an internal note 'Cancelled and transferred
1839 to BOOKSELLER on DATE' and create new order with internal note
1840 'Transferred from BOOKSELLER on DATE'.
1841 Move all attached items to the new order.
1842 Received orders cannot be transferred.
1843 Return the ordernumber of created order.
1848 my ($ordernumber, $basketno) = @_;
1850 return unless ($ordernumber and $basketno);
1852 my $order = GetOrder( $ordernumber );
1853 return if $order->{datereceived};
1854 my $basket = GetBasket($basketno);
1855 return unless $basket;
1857 my $dbh = C4::Context->dbh;
1858 my ($query, $sth, $rv);
1862 SET datecancellationprinted = CAST(NOW() AS date), orderstatus = ?
1863 WHERE ordernumber = ?
1865 $sth = $dbh->prepare($query);
1866 $rv = $sth->execute('cancelled', $ordernumber);
1868 delete $order->{'ordernumber'};
1869 delete $order->{parent_ordernumber};
1870 $order->{'basketno'} = $basketno;
1872 my $newordernumber = Koha::Acquisition::Order->new($order)->insert->{ordernumber};
1875 UPDATE aqorders_items
1877 WHERE ordernumber = ?
1879 $sth = $dbh->prepare($query);
1880 $sth->execute($newordernumber, $ordernumber);
1883 INSERT INTO aqorders_transfers (ordernumber_from, ordernumber_to)
1886 $sth = $dbh->prepare($query);
1887 $sth->execute($ordernumber, $newordernumber);
1889 return $newordernumber;
1892 =head2 FUNCTIONS ABOUT PARCELS
1896 $results = &GetParcels($bookseller, $order, $code, $datefrom, $dateto);
1898 get a lists of parcels.
1905 is the bookseller this function has to get parcels.
1908 To know on what criteria the results list has to be ordered.
1911 is the booksellerinvoicenumber.
1913 =item $datefrom & $dateto
1914 to know on what date this function has to filter its search.
1919 a pointer on a hash list containing parcel informations as such :
1925 =item Last operation
1927 =item Number of biblio
1929 =item Number of items
1936 my ($bookseller,$order, $code, $datefrom, $dateto) = @_;
1937 my $dbh = C4::Context->dbh;
1938 my @query_params = ();
1940 SELECT aqinvoices.invoicenumber,
1941 datereceived,purchaseordernumber,
1942 count(DISTINCT biblionumber) AS biblio,
1943 sum(quantity) AS itemsexpected,
1944 sum(quantityreceived) AS itemsreceived
1945 FROM aqorders LEFT JOIN aqbasket ON aqbasket.basketno = aqorders.basketno
1946 LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
1947 WHERE aqbasket.booksellerid = ? and datereceived IS NOT NULL
1949 push @query_params, $bookseller;
1951 if ( defined $code ) {
1952 $strsth .= ' and aqinvoices.invoicenumber like ? ';
1953 # add a % to the end of the code to allow stemming.
1954 push @query_params, "$code%";
1957 if ( defined $datefrom ) {
1958 $strsth .= ' and datereceived >= ? ';
1959 push @query_params, $datefrom;
1962 if ( defined $dateto ) {
1963 $strsth .= 'and datereceived <= ? ';
1964 push @query_params, $dateto;
1967 $strsth .= "group by aqinvoices.invoicenumber,datereceived ";
1969 # can't use a placeholder to place this column name.
1970 # but, we could probably be checking to make sure it is a column that will be fetched.
1971 $strsth .= "order by $order " if ($order);
1973 my $sth = $dbh->prepare($strsth);
1975 $sth->execute( @query_params );
1976 my $results = $sth->fetchall_arrayref({});
1980 #------------------------------------------------------------#
1982 =head3 GetLateOrders
1984 @results = &GetLateOrders;
1986 Searches for bookseller with late orders.
1989 the table of supplier with late issues. This table is full of hashref.
1995 my $supplierid = shift;
1997 my $estimateddeliverydatefrom = shift;
1998 my $estimateddeliverydateto = shift;
2000 my $dbh = C4::Context->dbh;
2002 #BEWARE, order of parenthesis and LEFT JOIN is important for speed
2003 my $dbdriver = C4::Context->config("db_scheme") || "mysql";
2005 my @query_params = ();
2007 SELECT aqbasket.basketno,
2008 aqorders.ordernumber,
2009 DATE(aqbasket.closedate) AS orderdate,
2010 aqbasket.basketname AS basketname,
2011 aqbasket.basketgroupid AS basketgroupid,
2012 aqbasketgroups.name AS basketgroupname,
2013 aqorders.rrp AS unitpricesupplier,
2014 aqorders.ecost AS unitpricelib,
2015 aqorders.claims_count AS claims_count,
2016 aqorders.claimed_date AS claimed_date,
2017 aqbudgets.budget_name AS budget,
2018 borrowers.branchcode AS branch,
2019 aqbooksellers.name AS supplier,
2020 aqbooksellers.id AS supplierid,
2021 biblio.author, biblio.title,
2022 biblioitems.publishercode AS publisher,
2023 biblioitems.publicationyear,
2024 ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) AS estimateddeliverydate,
2028 aqorders LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
2029 LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
2030 LEFT JOIN aqbudgets ON aqorders.budget_id = aqbudgets.budget_id,
2031 aqbasket LEFT JOIN borrowers ON aqbasket.authorisedby = borrowers.borrowernumber
2032 LEFT JOIN aqbooksellers ON aqbasket.booksellerid = aqbooksellers.id
2033 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid = aqbasketgroups.id
2034 WHERE aqorders.basketno = aqbasket.basketno
2035 AND ( datereceived = ''
2036 OR datereceived IS NULL
2037 OR aqorders.quantityreceived < aqorders.quantity
2039 AND aqbasket.closedate IS NOT NULL
2040 AND (aqorders.datecancellationprinted IS NULL OR aqorders.datecancellationprinted='0000-00-00')
2043 if ($dbdriver eq "mysql") {
2045 aqorders.quantity - COALESCE(aqorders.quantityreceived,0) AS quantity,
2046 (aqorders.quantity - COALESCE(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
2047 DATEDIFF(CAST(now() AS date),closedate) AS latesince
2049 if ( defined $delay ) {
2050 $from .= " AND (closedate <= DATE_SUB(CAST(now() AS date),INTERVAL ? DAY)) " ;
2051 push @query_params, $delay;
2053 $having = "HAVING quantity <> 0";
2055 # FIXME: account for IFNULL as above
2057 aqorders.quantity AS quantity,
2058 aqorders.quantity * aqorders.rrp AS subtotal,
2059 (CAST(now() AS date) - closedate) AS latesince
2061 if ( defined $delay ) {
2062 $from .= " AND (closedate <= (CAST(now() AS date) -(INTERVAL ? DAY)) ";
2063 push @query_params, $delay;
2066 if (defined $supplierid) {
2067 $from .= ' AND aqbasket.booksellerid = ? ';
2068 push @query_params, $supplierid;
2070 if (defined $branch) {
2071 $from .= ' AND borrowers.branchcode LIKE ? ';
2072 push @query_params, $branch;
2075 if ( defined $estimateddeliverydatefrom or defined $estimateddeliverydateto ) {
2076 $from .= ' AND aqbooksellers.deliverytime IS NOT NULL ';
2078 if ( defined $estimateddeliverydatefrom ) {
2079 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) >= ?';
2080 push @query_params, $estimateddeliverydatefrom;
2082 if ( defined $estimateddeliverydateto ) {
2083 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= ?';
2084 push @query_params, $estimateddeliverydateto;
2086 if ( defined $estimateddeliverydatefrom and not defined $estimateddeliverydateto ) {
2087 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= CAST(now() AS date)';
2089 if (C4::Context->preference("IndependentBranches")
2090 && !C4::Context->IsSuperLibrarian() ) {
2091 $from .= ' AND borrowers.branchcode LIKE ? ';
2092 push @query_params, C4::Context->userenv->{branch};
2094 $from .= " AND orderstatus <> 'cancelled' ";
2095 my $query = "$select $from $having\nORDER BY latesince, basketno, borrowers.branchcode, supplier";
2096 $debug and print STDERR "GetLateOrders query: $query\nGetLateOrders args: " . join(" ",@query_params);
2097 my $sth = $dbh->prepare($query);
2098 $sth->execute(@query_params);
2100 while (my $data = $sth->fetchrow_hashref) {
2101 push @results, $data;
2106 #------------------------------------------------------------#
2110 \@order_loop = GetHistory( %params );
2112 Retreives some acquisition history information
2122 basket - search both basket name and number
2123 booksellerinvoicenumber
2126 orderstatus (note that orderstatus '' will retrieve orders
2127 of any status except cancelled)
2129 get_canceled_order (if set to a true value, cancelled orders will
2133 $order_loop is a list of hashrefs that each look like this:
2135 'author' => 'Twain, Mark',
2137 'biblionumber' => '215',
2139 'creationdate' => 'MM/DD/YYYY',
2140 'datereceived' => undef,
2143 'invoicenumber' => undef,
2145 'ordernumber' => '1',
2147 'quantityreceived' => undef,
2148 'title' => 'The Adventures of Huckleberry Finn'
2154 # don't run the query if there are no parameters (list would be too long for sure !)
2155 croak "No search params" unless @_;
2157 my $title = $params{title};
2158 my $author = $params{author};
2159 my $isbn = $params{isbn};
2160 my $ean = $params{ean};
2161 my $name = $params{name};
2162 my $from_placed_on = $params{from_placed_on};
2163 my $to_placed_on = $params{to_placed_on};
2164 my $basket = $params{basket};
2165 my $booksellerinvoicenumber = $params{booksellerinvoicenumber};
2166 my $basketgroupname = $params{basketgroupname};
2167 my $budget = $params{budget};
2168 my $orderstatus = $params{orderstatus};
2169 my $biblionumber = $params{biblionumber};
2170 my $get_canceled_order = $params{get_canceled_order} || 0;
2171 my $ordernumber = $params{ordernumber};
2172 my $search_children_too = $params{search_children_too} || 0;
2173 my $created_by = $params{created_by} || [];
2177 my $total_qtyreceived = 0;
2178 my $total_price = 0;
2180 my $dbh = C4::Context->dbh;
2183 COALESCE(biblio.title, deletedbiblio.title) AS title,
2184 COALESCE(biblio.author, deletedbiblio.author) AS author,
2185 COALESCE(biblioitems.isbn, deletedbiblioitems.isbn) AS isbn,
2186 COALESCE(biblioitems.ean, deletedbiblioitems.ean) AS ean,
2188 aqbasket.basketname,
2189 aqbasket.basketgroupid,
2190 aqbasket.authorisedby,
2191 concat( borrowers.firstname,' ',borrowers.surname) AS authorisedbyname,
2192 aqbasketgroups.name as groupname,
2194 aqbasket.creationdate,
2195 aqorders.datereceived,
2197 aqorders.quantityreceived,
2199 aqorders.ordernumber,
2201 aqinvoices.invoicenumber,
2202 aqbooksellers.id as id,
2203 aqorders.biblionumber,
2204 aqorders.orderstatus,
2205 aqorders.parent_ordernumber,
2206 aqbudgets.budget_name
2208 $query .= ", aqbudgets.budget_id AS budget" if defined $budget;
2211 LEFT JOIN aqbasket ON aqorders.basketno=aqbasket.basketno
2212 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid=aqbasketgroups.id
2213 LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
2214 LEFT JOIN biblioitems ON biblioitems.biblionumber=aqorders.biblionumber
2215 LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
2216 LEFT JOIN aqbudgets ON aqorders.budget_id=aqbudgets.budget_id
2217 LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
2218 LEFT JOIN deletedbiblio ON deletedbiblio.biblionumber=aqorders.biblionumber
2219 LEFT JOIN deletedbiblioitems ON deletedbiblioitems.biblionumber=aqorders.biblionumber
2220 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
2223 $query .= " WHERE 1 ";
2225 unless ($get_canceled_order or (defined $orderstatus and $orderstatus eq 'cancelled')) {
2226 $query .= " AND (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') ";
2229 my @query_params = ();
2231 if ( $biblionumber ) {
2232 $query .= " AND biblio.biblionumber = ?";
2233 push @query_params, $biblionumber;
2237 $query .= " AND biblio.title LIKE ? ";
2238 $title =~ s/\s+/%/g;
2239 push @query_params, "%$title%";
2243 $query .= " AND biblio.author LIKE ? ";
2244 push @query_params, "%$author%";
2248 $query .= " AND biblioitems.isbn LIKE ? ";
2249 push @query_params, "%$isbn%";
2252 $query .= " AND biblioitems.ean = ? ";
2253 push @query_params, "$ean";
2256 $query .= " AND aqbooksellers.name LIKE ? ";
2257 push @query_params, "%$name%";
2261 $query .= " AND aqbudgets.budget_id = ? ";
2262 push @query_params, "$budget";
2265 if ( $from_placed_on ) {
2266 $query .= " AND creationdate >= ? ";
2267 push @query_params, $from_placed_on;
2270 if ( $to_placed_on ) {
2271 $query .= " AND creationdate <= ? ";
2272 push @query_params, $to_placed_on;
2275 if ( defined $orderstatus and $orderstatus ne '') {
2276 $query .= " AND aqorders.orderstatus = ? ";
2277 push @query_params, "$orderstatus";
2281 if ($basket =~ m/^\d+$/) {
2282 $query .= " AND aqorders.basketno = ? ";
2283 push @query_params, $basket;
2285 $query .= " AND aqbasket.basketname LIKE ? ";
2286 push @query_params, "%$basket%";
2290 if ($booksellerinvoicenumber) {
2291 $query .= " AND aqinvoices.invoicenumber LIKE ? ";
2292 push @query_params, "%$booksellerinvoicenumber%";
2295 if ($basketgroupname) {
2296 $query .= " AND aqbasketgroups.name LIKE ? ";
2297 push @query_params, "%$basketgroupname%";
2301 $query .= " AND (aqorders.ordernumber = ? ";
2302 push @query_params, $ordernumber;
2303 if ($search_children_too) {
2304 $query .= " OR aqorders.parent_ordernumber = ? ";
2305 push @query_params, $ordernumber;
2310 if ( @$created_by ) {
2311 $query .= ' AND aqbasket.authorisedby IN ( ' . join( ',', ('?') x @$created_by ) . ')';
2312 push @query_params, @$created_by;
2316 if ( C4::Context->preference("IndependentBranches") ) {
2317 unless ( C4::Context->IsSuperLibrarian() ) {
2318 $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
2319 push @query_params, C4::Context->userenv->{branch};
2322 $query .= " ORDER BY id";
2324 return $dbh->selectall_arrayref( $query, { Slice => {} }, @query_params );
2327 =head2 GetRecentAcqui
2329 $results = GetRecentAcqui($days);
2331 C<$results> is a ref to a table which containts hashref
2335 sub GetRecentAcqui {
2337 my $dbh = C4::Context->dbh;
2341 ORDER BY timestamp DESC
2344 my $sth = $dbh->prepare($query);
2346 my $results = $sth->fetchall_arrayref({});
2350 #------------------------------------------------------------#
2354 &AddClaim($ordernumber);
2356 Add a claim for an order
2361 my ($ordernumber) = @_;
2362 my $dbh = C4::Context->dbh;
2365 claims_count = claims_count + 1,
2366 claimed_date = CURDATE()
2367 WHERE ordernumber = ?
2369 my $sth = $dbh->prepare($query);
2370 $sth->execute($ordernumber);
2375 my @invoices = GetInvoices(
2376 invoicenumber => $invoicenumber,
2377 supplierid => $supplierid,
2378 suppliername => $suppliername,
2379 shipmentdatefrom => $shipmentdatefrom, # ISO format
2380 shipmentdateto => $shipmentdateto, # ISO format
2381 billingdatefrom => $billingdatefrom, # ISO format
2382 billingdateto => $billingdateto, # ISO format
2383 isbneanissn => $isbn_or_ean_or_issn,
2386 publisher => $publisher,
2387 publicationyear => $publicationyear,
2388 branchcode => $branchcode,
2389 order_by => $order_by
2392 Return a list of invoices that match all given criteria.
2394 $order_by is "column_name (asc|desc)", where column_name is any of
2395 'invoicenumber', 'booksellerid', 'shipmentdate', 'billingdate', 'closedate',
2396 'shipmentcost', 'shipmentcost_budgetid'.
2398 asc is the default if omitted
2405 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2406 closedate shipmentcost shipmentcost_budgetid);
2408 my $dbh = C4::Context->dbh;
2410 SELECT aqinvoices.*, aqbooksellers.name AS suppliername,
2413 aqorders.datereceived IS NOT NULL,
2414 aqorders.biblionumber,
2417 ) AS receivedbiblios,
2420 aqorders.subscriptionid IS NOT NULL,
2421 aqorders.subscriptionid,
2424 ) AS is_linked_to_subscriptions,
2425 SUM(aqorders.quantityreceived) AS receiveditems
2427 LEFT JOIN aqbooksellers ON aqbooksellers.id = aqinvoices.booksellerid
2428 LEFT JOIN aqorders ON aqorders.invoiceid = aqinvoices.invoiceid
2429 LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
2430 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
2431 LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
2432 LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
2433 LEFT JOIN subscription ON biblio.biblionumber = subscription.biblionumber
2438 if($args{supplierid}) {
2439 push @bind_strs, " aqinvoices.booksellerid = ? ";
2440 push @bind_args, $args{supplierid};
2442 if($args{invoicenumber}) {
2443 push @bind_strs, " aqinvoices.invoicenumber LIKE ? ";
2444 push @bind_args, "%$args{invoicenumber}%";
2446 if($args{suppliername}) {
2447 push @bind_strs, " aqbooksellers.name LIKE ? ";
2448 push @bind_args, "%$args{suppliername}%";
2450 if($args{shipmentdatefrom}) {
2451 push @bind_strs, " aqinvoices.shipmentdate >= ? ";
2452 push @bind_args, $args{shipmentdatefrom};
2454 if($args{shipmentdateto}) {
2455 push @bind_strs, " aqinvoices.shipmentdate <= ? ";
2456 push @bind_args, $args{shipmentdateto};
2458 if($args{billingdatefrom}) {
2459 push @bind_strs, " aqinvoices.billingdate >= ? ";
2460 push @bind_args, $args{billingdatefrom};
2462 if($args{billingdateto}) {
2463 push @bind_strs, " aqinvoices.billingdate <= ? ";
2464 push @bind_args, $args{billingdateto};
2466 if($args{isbneanissn}) {
2467 push @bind_strs, " (biblioitems.isbn LIKE CONCAT('%', ?, '%') OR biblioitems.ean LIKE CONCAT('%', ?, '%') OR biblioitems.issn LIKE CONCAT('%', ?, '%') ) ";
2468 push @bind_args, $args{isbneanissn}, $args{isbneanissn}, $args{isbneanissn};
2471 push @bind_strs, " biblio.title LIKE CONCAT('%', ?, '%') ";
2472 push @bind_args, $args{title};
2475 push @bind_strs, " biblio.author LIKE CONCAT('%', ?, '%') ";
2476 push @bind_args, $args{author};
2478 if($args{publisher}) {
2479 push @bind_strs, " biblioitems.publishercode LIKE CONCAT('%', ?, '%') ";
2480 push @bind_args, $args{publisher};
2482 if($args{publicationyear}) {
2483 push @bind_strs, " ((biblioitems.publicationyear LIKE CONCAT('%', ?, '%')) OR (biblio.copyrightdate LIKE CONCAT('%', ?, '%'))) ";
2484 push @bind_args, $args{publicationyear}, $args{publicationyear};
2486 if($args{branchcode}) {
2487 push @bind_strs, " borrowers.branchcode = ? ";
2488 push @bind_args, $args{branchcode};
2490 if($args{message_id}) {
2491 push @bind_strs, " aqinvoices.message_id = ? ";
2492 push @bind_args, $args{message_id};
2495 $query .= " WHERE " . join(" AND ", @bind_strs) if @bind_strs;
2496 $query .= " GROUP BY aqinvoices.invoiceid ";
2498 if($args{order_by}) {
2499 my ($column, $direction) = split / /, $args{order_by};
2500 if(grep /^$column$/, @columns) {
2501 $direction ||= 'ASC';
2502 $query .= " ORDER BY $column $direction";
2506 my $sth = $dbh->prepare($query);
2507 $sth->execute(@bind_args);
2509 my $results = $sth->fetchall_arrayref({});
2515 my $invoice = GetInvoice($invoiceid);
2517 Get informations about invoice with given $invoiceid
2519 Return a hash filled with aqinvoices.* fields
2524 my ($invoiceid) = @_;
2527 return unless $invoiceid;
2529 my $dbh = C4::Context->dbh;
2535 my $sth = $dbh->prepare($query);
2536 $sth->execute($invoiceid);
2538 $invoice = $sth->fetchrow_hashref;
2542 =head3 GetInvoiceDetails
2544 my $invoice = GetInvoiceDetails($invoiceid)
2546 Return informations about an invoice + the list of related order lines
2548 Orders informations are in $invoice->{orders} (array ref)
2552 sub GetInvoiceDetails {
2553 my ($invoiceid) = @_;
2555 if ( !defined $invoiceid ) {
2556 carp 'GetInvoiceDetails called without an invoiceid';
2560 my $dbh = C4::Context->dbh;
2562 SELECT aqinvoices.*, aqbooksellers.name AS suppliername
2564 LEFT JOIN aqbooksellers ON aqinvoices.booksellerid = aqbooksellers.id
2567 my $sth = $dbh->prepare($query);
2568 $sth->execute($invoiceid);
2570 my $invoice = $sth->fetchrow_hashref;
2575 biblio.copyrightdate,
2576 biblioitems.publishercode,
2577 biblioitems.publicationyear,
2578 aqbasket.basketname,
2579 aqbasketgroups.id AS basketgroupid,
2580 aqbasketgroups.name AS basketgroupname
2582 LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
2583 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid = aqbasketgroups.id
2584 LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
2585 LEFT JOIN biblioitems ON aqorders.biblionumber = biblioitems.biblionumber
2588 $sth = $dbh->prepare($query);
2589 $sth->execute($invoiceid);
2590 $invoice->{orders} = $sth->fetchall_arrayref({});
2591 $invoice->{orders} ||= []; # force an empty arrayref if fetchall_arrayref fails
2598 my $invoiceid = AddInvoice(
2599 invoicenumber => $invoicenumber,
2600 booksellerid => $booksellerid,
2601 shipmentdate => $shipmentdate,
2602 billingdate => $billingdate,
2603 closedate => $closedate,
2604 shipmentcost => $shipmentcost,
2605 shipmentcost_budgetid => $shipmentcost_budgetid
2608 Create a new invoice and return its id or undef if it fails.
2615 return unless(%invoice and $invoice{invoicenumber});
2617 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2618 closedate shipmentcost shipmentcost_budgetid message_id);
2622 foreach my $key (keys %invoice) {
2623 if(0 < grep(/^$key$/, @columns)) {
2624 push @set_strs, "$key = ?";
2625 push @set_args, ($invoice{$key} || undef);
2631 my $dbh = C4::Context->dbh;
2632 my $query = "INSERT INTO aqinvoices SET ";
2633 $query .= join (",", @set_strs);
2634 my $sth = $dbh->prepare($query);
2635 $rv = $sth->execute(@set_args);
2637 $rv = $dbh->last_insert_id(undef, undef, 'aqinvoices', undef);
2646 invoiceid => $invoiceid, # Mandatory
2647 invoicenumber => $invoicenumber,
2648 booksellerid => $booksellerid,
2649 shipmentdate => $shipmentdate,
2650 billingdate => $billingdate,
2651 closedate => $closedate,
2652 shipmentcost => $shipmentcost,
2653 shipmentcost_budgetid => $shipmentcost_budgetid
2656 Modify an invoice, invoiceid is mandatory.
2658 Return undef if it fails.
2665 return unless(%invoice and $invoice{invoiceid});
2667 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2668 closedate shipmentcost shipmentcost_budgetid);
2672 foreach my $key (keys %invoice) {
2673 if(0 < grep(/^$key$/, @columns)) {
2674 push @set_strs, "$key = ?";
2675 push @set_args, ($invoice{$key} || undef);
2679 my $dbh = C4::Context->dbh;
2680 my $query = "UPDATE aqinvoices SET ";
2681 $query .= join(",", @set_strs);
2682 $query .= " WHERE invoiceid = ?";
2684 my $sth = $dbh->prepare($query);
2685 $sth->execute(@set_args, $invoice{invoiceid});
2690 CloseInvoice($invoiceid);
2694 Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => undef);
2699 my ($invoiceid) = @_;
2701 return unless $invoiceid;
2703 my $dbh = C4::Context->dbh;
2706 SET closedate = CAST(NOW() AS DATE)
2709 my $sth = $dbh->prepare($query);
2710 $sth->execute($invoiceid);
2713 =head3 ReopenInvoice
2715 ReopenInvoice($invoiceid);
2719 Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => output_pref({ dt=>dt_from_string, dateonly=>1, otputpref=>'iso' }))
2724 my ($invoiceid) = @_;
2726 return unless $invoiceid;
2728 my $dbh = C4::Context->dbh;
2731 SET closedate = NULL
2734 my $sth = $dbh->prepare($query);
2735 $sth->execute($invoiceid);
2740 DelInvoice($invoiceid);
2742 Delete an invoice if there are no items attached to it.
2747 my ($invoiceid) = @_;
2749 return unless $invoiceid;
2751 my $dbh = C4::Context->dbh;
2757 my $sth = $dbh->prepare($query);
2758 $sth->execute($invoiceid);
2759 my $res = $sth->fetchrow_arrayref;
2760 if ( $res && $res->[0] == 0 ) {
2762 DELETE FROM aqinvoices
2765 my $sth = $dbh->prepare($query);
2766 return ( $sth->execute($invoiceid) > 0 );
2771 =head3 MergeInvoices
2773 MergeInvoices($invoiceid, \@sourceids);
2775 Merge the invoices identified by the IDs in \@sourceids into
2776 the invoice identified by $invoiceid.
2781 my ($invoiceid, $sourceids) = @_;
2783 return unless $invoiceid;
2784 foreach my $sourceid (@$sourceids) {
2785 next if $sourceid == $invoiceid;
2786 my $source = GetInvoiceDetails($sourceid);
2787 foreach my $order (@{$source->{'orders'}}) {
2788 $order->{'invoiceid'} = $invoiceid;
2791 DelInvoice($source->{'invoiceid'});
2796 =head3 GetBiblioCountByBasketno
2798 $biblio_count = &GetBiblioCountByBasketno($basketno);
2800 Looks up the biblio's count that has basketno value $basketno
2806 sub GetBiblioCountByBasketno {
2807 my ($basketno) = @_;
2808 my $dbh = C4::Context->dbh;
2810 SELECT COUNT( DISTINCT( biblionumber ) )
2813 AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
2816 my $sth = $dbh->prepare($query);
2817 $sth->execute($basketno);
2818 return $sth->fetchrow;
2821 # This is *not* the good way to calcul prices
2822 # But it's how it works at the moment into Koha
2823 # This will be fixed later.
2824 # Note this subroutine should be moved to Koha::Acquisition::Order
2825 # Will do when a DBIC decision will be taken.
2826 sub populate_order_with_prices {
2829 my $order = $params->{order};
2830 my $booksellerid = $params->{booksellerid};
2831 return unless $booksellerid;
2833 my $bookseller = Koha::Acquisition::Bookseller->fetch({ id => $booksellerid });
2835 my $receiving = $params->{receiving};
2836 my $ordering = $params->{ordering};
2837 my $discount = $order->{discount};
2838 $discount /= 100 if $discount > 1;
2840 $order->{rrp} = Koha::Number::Price->new( $order->{rrp} )->round;
2841 $order->{ecost} = Koha::Number::Price->new( $order->{ecost} )->round;
2843 if ( $bookseller->{listincgst} ) {
2844 $order->{rrpgsti} = $order->{rrp};
2845 $order->{rrpgste} = Koha::Number::Price->new(
2846 $order->{rrpgsti} / ( 1 + $order->{gstrate} ) )->round;
2847 $order->{ecostgsti} = $order->{ecost};
2848 $order->{ecostgste} = Koha::Number::Price->new(
2849 $order->{ecost} / ( 1 + $order->{gstrate} ) )->round;
2850 $order->{gstvalue} = Koha::Number::Price->new(
2851 ( $order->{ecostgsti} - $order->{ecostgste} ) *
2852 $order->{quantity} )->round;
2853 $order->{totalgste} = $order->{ecostgste} * $order->{quantity};
2854 $order->{totalgsti} = $order->{ecostgsti} * $order->{quantity};
2857 $order->{rrpgste} = $order->{rrp};
2858 $order->{rrpgsti} = Koha::Number::Price->new(
2859 $order->{rrp} * ( 1 + $order->{gstrate} ) )->round;
2860 $order->{ecostgste} = $order->{ecost};
2861 $order->{ecostgsti} = Koha::Number::Price->new(
2862 $order->{ecost} * ( 1 + $order->{gstrate} ) )->round;
2863 $order->{gstvalue} = Koha::Number::Price->new(
2864 ( $order->{ecostgsti} - $order->{ecostgste} ) *
2865 $order->{quantity} )->round;
2866 $order->{totalgste} = $order->{ecostgste} * $order->{quantity};
2867 $order->{totalgsti} = $order->{ecostgsti} * $order->{quantity};
2872 if ( $bookseller->{listincgst} ) {
2873 $order->{unitpricegsti} = Koha::Number::Price->new( $order->{unitprice} )->round;
2874 $order->{unitpricegste} = Koha::Number::Price->new(
2875 $order->{unitpricegsti} / ( 1 + $order->{gstrate} ) )->round;
2878 $order->{unitpricegste} = Koha::Number::Price->new( $order->{unitprice} )->round;
2879 $order->{unitpricegsti} = Koha::Number::Price->new(
2880 $order->{unitpricegste} * ( 1 + $order->{gstrate} ) )->round;
2882 $order->{gstvalue} = Koha::Number::Price->new(
2883 ( $order->{unitpricegsti} - $order->{unitpricegste} )
2884 * $order->{quantityreceived} )->round;
2886 $order->{totalgste} = $order->{unitpricegste} * $order->{quantity};
2887 $order->{totalgsti} = $order->{unitpricegsti} * $order->{quantity};
2893 =head3 GetOrderUsers
2895 $order_users_ids = &GetOrderUsers($ordernumber);
2897 Returns a list of all borrowernumbers that are in order users list
2902 my ($ordernumber) = @_;
2904 return unless $ordernumber;
2907 SELECT borrowernumber
2909 WHERE ordernumber = ?
2911 my $dbh = C4::Context->dbh;
2912 my $sth = $dbh->prepare($query);
2913 $sth->execute($ordernumber);
2914 my $results = $sth->fetchall_arrayref( {} );
2916 my @borrowernumbers;
2917 foreach (@$results) {
2918 push @borrowernumbers, $_->{'borrowernumber'};
2921 return @borrowernumbers;
2924 =head3 ModOrderUsers
2926 my @order_users_ids = (1, 2, 3);
2927 &ModOrderUsers($ordernumber, @basketusers_ids);
2929 Delete all users from order users list, and add users in C<@order_users_ids>
2935 my ( $ordernumber, @order_users_ids ) = @_;
2937 return unless $ordernumber;
2939 my $dbh = C4::Context->dbh;
2941 DELETE FROM aqorder_users
2942 WHERE ordernumber = ?
2944 my $sth = $dbh->prepare($query);
2945 $sth->execute($ordernumber);
2948 INSERT INTO aqorder_users (ordernumber, borrowernumber)
2951 $sth = $dbh->prepare($query);
2952 foreach my $order_user_id (@order_users_ids) {
2953 $sth->execute( $ordernumber, $order_user_id );
2957 sub NotifyOrderUsers {
2958 my ($ordernumber) = @_;
2960 my @borrowernumbers = GetOrderUsers($ordernumber);
2961 return unless @borrowernumbers;
2963 my $order = GetOrder( $ordernumber );
2964 for my $borrowernumber (@borrowernumbers) {
2965 my $borrower = C4::Members::GetMember( borrowernumber => $borrowernumber );
2966 my $library = Koha::Libraries->find( $borrower->{branchcode} )->unblessed;
2967 my $biblio = C4::Biblio::GetBiblio( $order->{biblionumber} );
2968 my $letter = C4::Letters::GetPreparedLetter(
2969 module => 'acquisition',
2970 letter_code => 'ACQ_NOTIF_ON_RECEIV',
2971 branchcode => $library->{branchcode},
2973 'branches' => $library,
2974 'borrowers' => $borrower,
2975 'biblio' => $biblio,
2976 'aqorders' => $order,
2980 C4::Letters::EnqueueLetter(
2983 borrowernumber => $borrowernumber,
2984 LibraryName => C4::Context->preference("LibraryName"),
2985 message_transport_type => 'email',
2987 ) or warn "can't enqueue letter $letter";
2992 =head3 FillWithDefaultValues
2994 FillWithDefaultValues( $marc_record );
2996 This will update the record with default value defined in the ACQ framework.
2997 For all existing fields, if a default value exists and there are no subfield, it will be created.
2998 If the field does not exist, it will be created too.
3002 sub FillWithDefaultValues {
3004 my $tagslib = C4::Biblio::GetMarcStructure( 1, 'ACQ' );
3007 C4::Biblio::GetMarcFromKohaField( 'items.itemnumber', '' );
3008 for my $tag ( sort keys %$tagslib ) {
3010 next if $tag == $itemfield;
3011 for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
3012 next if IsMarcStructureInternal($tagslib->{$tag}{$subfield});
3013 my $defaultvalue = $tagslib->{$tag}{$subfield}{defaultvalue};
3014 if ( defined $defaultvalue and $defaultvalue ne '' ) {
3015 my @fields = $record->field($tag);
3017 for my $field (@fields) {
3018 unless ( defined $field->subfield($subfield) ) {
3019 $field->add_subfields(
3020 $subfield => $defaultvalue );
3025 $record->insert_fields_ordered(
3027 $tag, '', '', $subfield => $defaultvalue
3042 Koha Development Team <http://koha-community.org/>