Bug 9044: (follow-up) fix merge conflict typo that broke this script
[koha.git] / C4 / Acquisition.pm
1 package C4::Acquisition;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
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
10 # version.
11 #
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.
15 #
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.
19
20
21 use strict;
22 use warnings;
23 use Carp;
24 use C4::Context;
25 use C4::Debug;
26 use C4::Dates qw(format_date format_date_in_iso);
27 use MARC::Record;
28 use C4::Suggestions;
29 use C4::Biblio;
30 use C4::Debug;
31 use C4::SQLHelper qw(InsertInTable UpdateInTable);
32 use C4::Bookseller qw(GetBookSellerFromId);
33 use C4::Templates qw(gettemplate);
34
35 use Time::localtime;
36 use HTML::Entities;
37
38 use vars qw($VERSION @ISA @EXPORT);
39
40 BEGIN {
41     # set the version for version checking
42     $VERSION = 3.07.00.049;
43     require Exporter;
44     @ISA    = qw(Exporter);
45     @EXPORT = qw(
46         &GetBasket &NewBasket &CloseBasket &ReopenBasket &DelBasket &ModBasket
47         &GetBasketAsCSV &GetBasketGroupAsCSV
48         &GetBasketsByBookseller &GetBasketsByBasketgroup
49         &GetBasketsInfosByBookseller
50
51         &GetBasketUsers &ModBasketUsers
52         &CanUserManageBasket
53
54         &ModBasketHeader
55
56         &ModBasketgroup &NewBasketgroup &DelBasketgroup &GetBasketgroup &CloseBasketgroup
57         &GetBasketgroups &ReOpenBasketgroup
58
59         &NewOrder &DelOrder &ModOrder &GetOrder &GetOrders &GetOrdersByBiblionumber
60         &GetLateOrders &GetOrderFromItemnumber
61         &SearchOrders &GetHistory &GetRecentAcqui
62         &ModReceiveOrder &CancelReceipt
63         &GetCancelledOrders &TransferOrder
64         &GetLastOrderNotReceivedFromSubscriptionid &GetLastOrderReceivedFromSubscriptionid
65         &NewOrderItem &ModItemOrder
66
67         &GetParcels &GetParcel
68         &GetContracts &GetContract
69
70         &GetInvoices
71         &GetInvoice
72         &GetInvoiceDetails
73         &AddInvoice
74         &ModInvoice
75         &CloseInvoice
76         &ReopenInvoice
77         &DelInvoice
78         &MergeInvoices
79
80         &GetItemnumbersFromOrder
81
82         &AddClaim
83         &GetBiblioCountByBasketno
84     );
85 }
86
87
88
89
90
91 sub GetOrderFromItemnumber {
92     my ($itemnumber) = @_;
93     my $dbh          = C4::Context->dbh;
94     my $query        = qq|
95
96     SELECT  * from aqorders    LEFT JOIN aqorders_items
97     ON (     aqorders.ordernumber = aqorders_items.ordernumber   )
98     WHERE itemnumber = ?  |;
99
100     my $sth = $dbh->prepare($query);
101
102 #    $sth->trace(3);
103
104     $sth->execute($itemnumber);
105
106     my $order = $sth->fetchrow_hashref;
107     return ( $order  );
108
109 }
110
111 # Returns the itemnumber(s) associated with the ordernumber given in parameter
112 sub GetItemnumbersFromOrder {
113     my ($ordernumber) = @_;
114     my $dbh          = C4::Context->dbh;
115     my $query        = "SELECT itemnumber FROM aqorders_items WHERE ordernumber=?";
116     my $sth = $dbh->prepare($query);
117     $sth->execute($ordernumber);
118     my @tab;
119
120     while (my $order = $sth->fetchrow_hashref) {
121     push @tab, $order->{'itemnumber'};
122     }
123
124     return @tab;
125
126 }
127
128
129
130
131
132
133 =head1 NAME
134
135 C4::Acquisition - Koha functions for dealing with orders and acquisitions
136
137 =head1 SYNOPSIS
138
139 use C4::Acquisition;
140
141 =head1 DESCRIPTION
142
143 The functions in this module deal with acquisitions, managing book
144 orders, basket and parcels.
145
146 =head1 FUNCTIONS
147
148 =head2 FUNCTIONS ABOUT BASKETS
149
150 =head3 GetBasket
151
152   $aqbasket = &GetBasket($basketnumber);
153
154 get all basket informations in aqbasket for a given basket
155
156 B<returns:> informations for a given basket returned as a hashref.
157
158 =cut
159
160 sub GetBasket {
161     my ($basketno) = @_;
162     my $dbh        = C4::Context->dbh;
163     my $query = "
164         SELECT  aqbasket.*,
165                 concat( b.firstname,' ',b.surname) AS authorisedbyname
166         FROM    aqbasket
167         LEFT JOIN borrowers b ON aqbasket.authorisedby=b.borrowernumber
168         WHERE basketno=?
169     ";
170     my $sth=$dbh->prepare($query);
171     $sth->execute($basketno);
172     my $basket = $sth->fetchrow_hashref;
173     return ( $basket );
174 }
175
176 #------------------------------------------------------------#
177
178 =head3 NewBasket
179
180   $basket = &NewBasket( $booksellerid, $authorizedby, $basketname, 
181       $basketnote, $basketbooksellernote, $basketcontractnumber, $deliveryplace, $billingplace );
182
183 Create a new basket in aqbasket table
184
185 =over
186
187 =item C<$booksellerid> is a foreign key in the aqbasket table
188
189 =item C<$authorizedby> is the username of who created the basket
190
191 =back
192
193 The other parameters are optional, see ModBasketHeader for more info on them.
194
195 =cut
196
197 sub NewBasket {
198     my ( $booksellerid, $authorisedby, $basketname, $basketnote,
199         $basketbooksellernote, $basketcontractnumber, $deliveryplace,
200         $billingplace ) = @_;
201     my $dbh = C4::Context->dbh;
202     my $query =
203         'INSERT INTO aqbasket (creationdate,booksellerid,authorisedby) '
204       . 'VALUES  (now(),?,?)';
205     $dbh->do( $query, {}, $booksellerid, $authorisedby );
206
207     my $basket = $dbh->{mysql_insertid};
208     $basketname           ||= q{}; # default to empty strings
209     $basketnote           ||= q{};
210     $basketbooksellernote ||= q{};
211     ModBasketHeader( $basket, $basketname, $basketnote, $basketbooksellernote,
212         $basketcontractnumber, $booksellerid, $deliveryplace, $billingplace );
213     return $basket;
214 }
215
216 #------------------------------------------------------------#
217
218 =head3 CloseBasket
219
220   &CloseBasket($basketno);
221
222 close a basket (becomes unmodifiable, except for receives)
223
224 =cut
225
226 sub CloseBasket {
227     my ($basketno) = @_;
228     my $dbh        = C4::Context->dbh;
229     my $query = "
230         UPDATE aqbasket
231         SET    closedate=now()
232         WHERE  basketno=?
233     ";
234     my $sth = $dbh->prepare($query);
235     $sth->execute($basketno);
236
237     my @orders = GetOrders($basketno);
238     foreach my $order (@orders) {
239         $query = qq{
240             UPDATE aqorders
241             SET orderstatus = 'ordered'
242             WHERE ordernumber = ?;
243         };
244         $sth = $dbh->prepare($query);
245         $sth->execute($order->{'ordernumber'});
246     }
247 }
248
249 =head3 ReopenBasket
250
251   &ReopenBasket($basketno);
252
253 reopen a basket
254
255 =cut
256
257 sub ReopenBasket {
258     my ($basketno) = @_;
259     my $dbh        = C4::Context->dbh;
260     my $query = "
261         UPDATE aqbasket
262         SET    closedate=NULL
263         WHERE  basketno=?
264     ";
265     my $sth = $dbh->prepare($query);
266     $sth->execute($basketno);
267
268     my @orders = GetOrders($basketno);
269     foreach my $order (@orders) {
270         $query = qq{
271             UPDATE aqorders
272             SET orderstatus = 'new'
273             WHERE ordernumber = ?;
274         };
275         $sth = $dbh->prepare($query);
276         $sth->execute($order->{'ordernumber'});
277     }
278 }
279
280 #------------------------------------------------------------#
281
282 =head3 GetBasketAsCSV
283
284   &GetBasketAsCSV($basketno);
285
286 Export a basket as CSV
287
288 $cgi parameter is needed for column name translation
289
290 =cut
291
292 sub GetBasketAsCSV {
293     my ($basketno, $cgi) = @_;
294     my $basket = GetBasket($basketno);
295     my @orders = GetOrders($basketno);
296     my $contract = GetContract($basket->{'contractnumber'});
297
298     my $template = C4::Templates::gettemplate("acqui/csv/basket.tmpl", "intranet", $cgi);
299
300     my @rows;
301     foreach my $order (@orders) {
302         my $bd = GetBiblioData( $order->{'biblionumber'} );
303         my $row = {
304             contractname => $contract->{'contractname'},
305             ordernumber => $order->{'ordernumber'},
306             entrydate => $order->{'entrydate'},
307             isbn => $order->{'isbn'},
308             author => $bd->{'author'},
309             title => $bd->{'title'},
310             publicationyear => $bd->{'publicationyear'},
311             publishercode => $bd->{'publishercode'},
312             collectiontitle => $bd->{'collectiontitle'},
313             notes => $order->{'notes'},
314             quantity => $order->{'quantity'},
315             rrp => $order->{'rrp'},
316             deliveryplace => C4::Branch::GetBranchName( $basket->{'deliveryplace'} ),
317             billingplace => C4::Branch::GetBranchName( $basket->{'billingplace'} ),
318         };
319         foreach(qw(
320             contractname author title publishercode collectiontitle notes
321             deliveryplace billingplace
322         ) ) {
323             # Double the quotes to not be interpreted as a field end
324             $row->{$_} =~ s/"/""/g if $row->{$_};
325         }
326         push @rows, $row;
327     }
328
329     @rows = sort {
330         if(defined $a->{publishercode} and defined $b->{publishercode}) {
331             $a->{publishercode} cmp $b->{publishercode};
332         }
333     } @rows;
334
335     $template->param(rows => \@rows);
336
337     return $template->output;
338 }
339
340
341 =head3 GetBasketGroupAsCSV
342
343 =over
344
345 &GetBasketGroupAsCSV($basketgroupid);
346
347 Export a basket group as CSV
348
349 $cgi parameter is needed for column name translation
350
351 =back
352
353 =cut
354
355 sub GetBasketGroupAsCSV {
356     my ($basketgroupid, $cgi) = @_;
357     my $baskets = GetBasketsByBasketgroup($basketgroupid);
358
359     my $template = C4::Templates::gettemplate('acqui/csv/basketgroup.tmpl', 'intranet', $cgi);
360
361     my @rows;
362     for my $basket (@$baskets) {
363         my @orders     = GetOrders( $$basket{basketno} );
364         my $contract   = GetContract( $$basket{contractnumber} );
365         my $bookseller = GetBookSellerFromId( $$basket{booksellerid} );
366         my $basketgroup = GetBasketgroup( $$basket{basketgroupid} );
367
368         foreach my $order (@orders) {
369             my $bd = GetBiblioData( $order->{'biblionumber'} );
370             my $row = {
371                 clientnumber => $bookseller->{accountnumber},
372                 basketname => $basket->{basketname},
373                 ordernumber => $order->{ordernumber},
374                 author => $bd->{author},
375                 title => $bd->{title},
376                 publishercode => $bd->{publishercode},
377                 publicationyear => $bd->{publicationyear},
378                 collectiontitle => $bd->{collectiontitle},
379                 isbn => $order->{isbn},
380                 quantity => $order->{quantity},
381                 rrp => $order->{rrp},
382                 discount => $bookseller->{discount},
383                 ecost => $order->{ecost},
384                 notes => $order->{notes},
385                 entrydate => $order->{entrydate},
386                 booksellername => $bookseller->{name},
387                 bookselleraddress => $bookseller->{address1},
388                 booksellerpostal => $bookseller->{postal},
389                 contractnumber => $contract->{contractnumber},
390                 contractname => $contract->{contractname},
391                 basketgroupdeliveryplace => C4::Branch::GetBranchName( $basketgroup->{deliveryplace} ),
392                 basketgroupbillingplace => C4::Branch::GetBranchName( $basketgroup->{billingplace} ),
393                 basketdeliveryplace => C4::Branch::GetBranchName( $basket->{deliveryplace} ),
394                 basketbillingplace => C4::Branch::GetBranchName( $basket->{billingplace} ),
395             };
396             foreach(qw(
397                 basketname author title publishercode collectiontitle notes
398                 booksellername bookselleraddress booksellerpostal contractname
399                 basketgroupdeliveryplace basketgroupbillingplace
400                 basketdeliveryplace basketbillingplace
401             ) ) {
402                 # Double the quotes to not be interpreted as a field end
403                 $row->{$_} =~ s/"/""/g if $row->{$_};
404             }
405             push @rows, $row;
406          }
407      }
408     $template->param(rows => \@rows);
409
410     return $template->output;
411
412 }
413
414 =head3 CloseBasketgroup
415
416   &CloseBasketgroup($basketgroupno);
417
418 close a basketgroup
419
420 =cut
421
422 sub CloseBasketgroup {
423     my ($basketgroupno) = @_;
424     my $dbh        = C4::Context->dbh;
425     my $sth = $dbh->prepare("
426         UPDATE aqbasketgroups
427         SET    closed=1
428         WHERE  id=?
429     ");
430     $sth->execute($basketgroupno);
431 }
432
433 #------------------------------------------------------------#
434
435 =head3 ReOpenBaskergroup($basketgroupno)
436
437   &ReOpenBaskergroup($basketgroupno);
438
439 reopen a basketgroup
440
441 =cut
442
443 sub ReOpenBasketgroup {
444     my ($basketgroupno) = @_;
445     my $dbh        = C4::Context->dbh;
446     my $sth = $dbh->prepare("
447         UPDATE aqbasketgroups
448         SET    closed=0
449         WHERE  id=?
450     ");
451     $sth->execute($basketgroupno);
452 }
453
454 #------------------------------------------------------------#
455
456
457 =head3 DelBasket
458
459   &DelBasket($basketno);
460
461 Deletes the basket that has basketno field $basketno in the aqbasket table.
462
463 =over
464
465 =item C<$basketno> is the primary key of the basket in the aqbasket table.
466
467 =back
468
469 =cut
470
471 sub DelBasket {
472     my ( $basketno ) = @_;
473     my $query = "DELETE FROM aqbasket WHERE basketno=?";
474     my $dbh = C4::Context->dbh;
475     my $sth = $dbh->prepare($query);
476     $sth->execute($basketno);
477     $sth->finish;
478 }
479
480 #------------------------------------------------------------#
481
482 =head3 ModBasket
483
484   &ModBasket($basketinfo);
485
486 Modifies a basket, using a hashref $basketinfo for the relevant information, only $basketinfo->{'basketno'} is required.
487
488 =over
489
490 =item C<$basketno> is the primary key of the basket in the aqbasket table.
491
492 =back
493
494 =cut
495
496 sub ModBasket {
497     my $basketinfo = shift;
498     my $query = "UPDATE aqbasket SET ";
499     my @params;
500     foreach my $key (keys %$basketinfo){
501         if ($key ne 'basketno'){
502             $query .= "$key=?, ";
503             push(@params, $basketinfo->{$key} || undef );
504         }
505     }
506 # get rid of the "," at the end of $query
507     if (substr($query, length($query)-2) eq ', '){
508         chop($query);
509         chop($query);
510         $query .= ' ';
511     }
512     $query .= "WHERE basketno=?";
513     push(@params, $basketinfo->{'basketno'});
514     my $dbh = C4::Context->dbh;
515     my $sth = $dbh->prepare($query);
516     $sth->execute(@params);
517
518     $sth->finish;
519 }
520
521 #------------------------------------------------------------#
522
523 =head3 ModBasketHeader
524
525   &ModBasketHeader($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid);
526
527 Modifies a basket's header.
528
529 =over
530
531 =item C<$basketno> is the "basketno" field in the "aqbasket" table;
532
533 =item C<$basketname> is the "basketname" field in the "aqbasket" table;
534
535 =item C<$note> is the "note" field in the "aqbasket" table;
536
537 =item C<$booksellernote> is the "booksellernote" field in the "aqbasket" table;
538
539 =item C<$contractnumber> is the "contractnumber" (foreign) key in the "aqbasket" table.
540
541 =item C<$booksellerid> is the id (foreign) key in the "aqbooksellers" table for the vendor.
542
543 =item C<$deliveryplace> is the "deliveryplace" field in the aqbasket table.
544
545 =item C<$billingplace> is the "billingplace" field in the aqbasket table.
546
547 =back
548
549 =cut
550
551 sub ModBasketHeader {
552     my ($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid, $deliveryplace, $billingplace) = @_;
553     my $query = qq{
554         UPDATE aqbasket
555         SET basketname=?, note=?, booksellernote=?, booksellerid=?, deliveryplace=?, billingplace=?
556         WHERE basketno=?
557     };
558
559     my $dbh = C4::Context->dbh;
560     my $sth = $dbh->prepare($query);
561     $sth->execute($basketname, $note, $booksellernote, $booksellerid, $deliveryplace, $billingplace, $basketno);
562
563     if ( $contractnumber ) {
564         my $query2 ="UPDATE aqbasket SET contractnumber=? WHERE basketno=?";
565         my $sth2 = $dbh->prepare($query2);
566         $sth2->execute($contractnumber,$basketno);
567         $sth2->finish;
568     }
569     $sth->finish;
570 }
571
572 #------------------------------------------------------------#
573
574 =head3 GetBasketsByBookseller
575
576   @results = &GetBasketsByBookseller($booksellerid, $extra);
577
578 Returns a list of hashes of all the baskets that belong to bookseller 'booksellerid'.
579
580 =over
581
582 =item C<$booksellerid> is the 'id' field of the bookseller in the aqbooksellers table
583
584 =item C<$extra> is the extra sql parameters, can be
585
586  $extra->{groupby}: group baskets by column
587     ex. $extra->{groupby} = aqbasket.basketgroupid
588  $extra->{orderby}: order baskets by column
589  $extra->{limit}: limit number of results (can be helpful for pagination)
590
591 =back
592
593 =cut
594
595 sub GetBasketsByBookseller {
596     my ($booksellerid, $extra) = @_;
597     my $query = "SELECT * FROM aqbasket WHERE booksellerid=?";
598     if ($extra){
599         if ($extra->{groupby}) {
600             $query .= " GROUP by $extra->{groupby}";
601         }
602         if ($extra->{orderby}){
603             $query .= " ORDER by $extra->{orderby}";
604         }
605         if ($extra->{limit}){
606             $query .= " LIMIT $extra->{limit}";
607         }
608     }
609     my $dbh = C4::Context->dbh;
610     my $sth = $dbh->prepare($query);
611     $sth->execute($booksellerid);
612     my $results = $sth->fetchall_arrayref({});
613     $sth->finish;
614     return $results
615 }
616
617 =head3 GetBasketsInfosByBookseller
618
619     my $baskets = GetBasketsInfosByBookseller($supplierid, $allbaskets);
620
621 The optional second parameter allbaskets is a boolean allowing you to
622 select all baskets from the supplier; by default only active baskets (open or 
623 closed but still something to receive) are returned.
624
625 Returns in a arrayref of hashref all about booksellers baskets, plus:
626     total_biblios: Number of distinct biblios in basket
627     total_items: Number of items in basket
628     expected_items: Number of non-received items in basket
629
630 =cut
631
632 sub GetBasketsInfosByBookseller {
633     my ($supplierid, $allbaskets) = @_;
634
635     return unless $supplierid;
636
637     my $dbh = C4::Context->dbh;
638     my $query = qq{
639         SELECT aqbasket.*,
640           SUM(aqorders.quantity) AS total_items,
641           COUNT(DISTINCT aqorders.biblionumber) AS total_biblios,
642           SUM(
643             IF(aqorders.datereceived IS NULL
644               AND aqorders.datecancellationprinted IS NULL
645             , aqorders.quantity
646             , 0)
647           ) AS expected_items
648         FROM aqbasket
649           LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
650         WHERE booksellerid = ?};
651     if(!$allbaskets) {
652         $query.=" AND (closedate IS NULL OR (aqorders.quantity > aqorders.quantityreceived AND datecancellationprinted IS NULL))";
653     }
654     $query.=" GROUP BY aqbasket.basketno";
655
656     my $sth = $dbh->prepare($query);
657     $sth->execute($supplierid);
658     return $sth->fetchall_arrayref({});
659 }
660
661 =head3 GetBasketUsers
662
663     $basketusers_ids = &GetBasketUsers($basketno);
664
665 Returns a list of all borrowernumbers that are in basket users list
666
667 =cut
668
669 sub GetBasketUsers {
670     my $basketno = shift;
671
672     return unless $basketno;
673
674     my $query = qq{
675         SELECT borrowernumber
676         FROM aqbasketusers
677         WHERE basketno = ?
678     };
679     my $dbh = C4::Context->dbh;
680     my $sth = $dbh->prepare($query);
681     $sth->execute($basketno);
682     my $results = $sth->fetchall_arrayref( {} );
683     $sth->finish();
684
685     my @borrowernumbers;
686     foreach (@$results) {
687         push @borrowernumbers, $_->{'borrowernumber'};
688     }
689
690     return @borrowernumbers;
691 }
692
693 =head3 ModBasketUsers
694
695     my @basketusers_ids = (1, 2, 3);
696     &ModBasketUsers($basketno, @basketusers_ids);
697
698 Delete all users from basket users list, and add users in C<@basketusers_ids>
699 to this users list.
700
701 =cut
702
703 sub ModBasketUsers {
704     my ($basketno, @basketusers_ids) = @_;
705
706     return unless $basketno;
707
708     my $dbh = C4::Context->dbh;
709     my $query = qq{
710         DELETE FROM aqbasketusers
711         WHERE basketno = ?
712     };
713     my $sth = $dbh->prepare($query);
714     $sth->execute($basketno);
715     $sth->finish();
716
717     $query = qq{
718         INSERT INTO aqbasketusers (basketno, borrowernumber)
719         VALUES (?, ?)
720     };
721     $sth = $dbh->prepare($query);
722     foreach my $basketuser_id (@basketusers_ids) {
723         $sth->execute($basketno, $basketuser_id);
724     }
725 }
726
727 =head3 CanUserManageBasket
728
729     my $bool = CanUserManageBasket($borrower, $basket[, $userflags]);
730     my $bool = CanUserManageBasket($borrowernumber, $basketno[, $userflags]);
731
732 Check if a borrower can manage a basket, according to system preference
733 AcqViewBaskets, user permissions and basket properties (creator, users list,
734 branch).
735
736 First parameter can be either a borrowernumber or a hashref as returned by
737 C4::Members::GetMember.
738
739 Second parameter can be either a basketno or a hashref as returned by
740 C4::Acquisition::GetBasket.
741
742 The third parameter is optional. If given, it should be a hashref as returned
743 by C4::Auth::getuserflags. If not, getuserflags is called.
744
745 If user is authorised to manage basket, returns 1.
746 Otherwise returns 0.
747
748 =cut
749
750 sub CanUserManageBasket {
751     my ($borrower, $basket, $userflags) = @_;
752
753     if (!ref $borrower) {
754         $borrower = C4::Members::GetMember(borrowernumber => $borrower);
755     }
756     if (!ref $basket) {
757         $basket = GetBasket($basket);
758     }
759
760     return 0 unless ($basket and $borrower);
761
762     my $borrowernumber = $borrower->{borrowernumber};
763     my $basketno = $basket->{basketno};
764
765     my $AcqViewBaskets = C4::Context->preference('AcqViewBaskets');
766
767     if (!defined $userflags) {
768         my $dbh = C4::Context->dbh;
769         my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE borrowernumber = ?");
770         $sth->execute($borrowernumber);
771         my ($flags) = $sth->fetchrow_array;
772         $sth->finish;
773
774         $userflags = C4::Auth::getuserflags($flags, $borrower->{userid}, $dbh);
775     }
776
777     unless ($userflags->{superlibrarian}
778     || (ref $userflags->{acquisition} && $userflags->{acquisition}->{order_manage_all})
779     || (!ref $userflags->{acquisition} && $userflags->{acquisition}))
780     {
781         if (not exists $userflags->{acquisition}) {
782             return 0;
783         }
784
785         if ( (ref $userflags->{acquisition} && !$userflags->{acquisition}->{order_manage})
786         || (!ref $userflags->{acquisition} && !$userflags->{acquisition}) ) {
787             return 0;
788         }
789
790         if ($AcqViewBaskets eq 'user'
791         && $basket->{authorisedby} != $borrowernumber
792         && grep($borrowernumber, GetBasketUsers($basketno)) == 0) {
793             return 0;
794         }
795
796         if ($AcqViewBaskets eq 'branch' && defined $basket->{branch}
797         && $basket->{branch} ne $borrower->{branchcode}) {
798             return 0;
799         }
800     }
801
802     return 1;
803 }
804
805 #------------------------------------------------------------#
806
807 =head3 GetBasketsByBasketgroup
808
809   $baskets = &GetBasketsByBasketgroup($basketgroupid);
810
811 Returns a reference to all baskets that belong to basketgroup $basketgroupid.
812
813 =cut
814
815 sub GetBasketsByBasketgroup {
816     my $basketgroupid = shift;
817     my $query = qq{
818         SELECT *, aqbasket.booksellerid as booksellerid
819         FROM aqbasket
820         LEFT JOIN aqcontract USING(contractnumber) WHERE basketgroupid=?
821     };
822     my $dbh = C4::Context->dbh;
823     my $sth = $dbh->prepare($query);
824     $sth->execute($basketgroupid);
825     my $results = $sth->fetchall_arrayref({});
826     $sth->finish;
827     return $results
828 }
829
830 #------------------------------------------------------------#
831
832 =head3 NewBasketgroup
833
834   $basketgroupid = NewBasketgroup(\%hashref);
835
836 Adds a basketgroup to the aqbasketgroups table, and add the initial baskets to it.
837
838 $hashref->{'booksellerid'} is the 'id' field of the bookseller in the aqbooksellers table,
839
840 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
841
842 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
843
844 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
845
846 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
847
848 $hashref->{'freedeliveryplace'} is the 'freedeliveryplace' field of the basketgroup in the aqbasketgroups table,
849
850 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
851
852 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
853
854 =cut
855
856 sub NewBasketgroup {
857     my $basketgroupinfo = shift;
858     die "booksellerid is required to create a basketgroup" unless $basketgroupinfo->{'booksellerid'};
859     my $query = "INSERT INTO aqbasketgroups (";
860     my @params;
861     foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
862         if ( defined $basketgroupinfo->{$field} ) {
863             $query .= "$field, ";
864             push(@params, $basketgroupinfo->{$field});
865         }
866     }
867     $query .= "booksellerid) VALUES (";
868     foreach (@params) {
869         $query .= "?, ";
870     }
871     $query .= "?)";
872     push(@params, $basketgroupinfo->{'booksellerid'});
873     my $dbh = C4::Context->dbh;
874     my $sth = $dbh->prepare($query);
875     $sth->execute(@params);
876     my $basketgroupid = $dbh->{'mysql_insertid'};
877     if( $basketgroupinfo->{'basketlist'} ) {
878         foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
879             my $query2 = "UPDATE aqbasket SET basketgroupid=? WHERE basketno=?";
880             my $sth2 = $dbh->prepare($query2);
881             $sth2->execute($basketgroupid, $basketno);
882         }
883     }
884     return $basketgroupid;
885 }
886
887 #------------------------------------------------------------#
888
889 =head3 ModBasketgroup
890
891   ModBasketgroup(\%hashref);
892
893 Modifies a basketgroup in the aqbasketgroups table, and add the baskets to it.
894
895 $hashref->{'id'} is the 'id' field of the basketgroup in the aqbasketgroup table, this parameter is mandatory,
896
897 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
898
899 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
900
901 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
902
903 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
904
905 $hashref->{'freedeliveryplace'} is the 'freedeliveryplace' field of the basketgroup in the aqbasketgroups table,
906
907 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
908
909 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
910
911 =cut
912
913 sub ModBasketgroup {
914     my $basketgroupinfo = shift;
915     die "basketgroup id is required to edit a basketgroup" unless $basketgroupinfo->{'id'};
916     my $dbh = C4::Context->dbh;
917     my $query = "UPDATE aqbasketgroups SET ";
918     my @params;
919     foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
920         if ( defined $basketgroupinfo->{$field} ) {
921             $query .= "$field=?, ";
922             push(@params, $basketgroupinfo->{$field});
923         }
924     }
925     chop($query);
926     chop($query);
927     $query .= " WHERE id=?";
928     push(@params, $basketgroupinfo->{'id'});
929     my $sth = $dbh->prepare($query);
930     $sth->execute(@params);
931
932     $sth = $dbh->prepare('UPDATE aqbasket SET basketgroupid = NULL WHERE basketgroupid = ?');
933     $sth->execute($basketgroupinfo->{'id'});
934
935     if($basketgroupinfo->{'basketlist'} && @{$basketgroupinfo->{'basketlist'}}){
936         $sth = $dbh->prepare("UPDATE aqbasket SET basketgroupid=? WHERE basketno=?");
937         foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
938             $sth->execute($basketgroupinfo->{'id'}, $basketno);
939             $sth->finish;
940         }
941     }
942     $sth->finish;
943 }
944
945 #------------------------------------------------------------#
946
947 =head3 DelBasketgroup
948
949   DelBasketgroup($basketgroupid);
950
951 Deletes a basketgroup in the aqbasketgroups table, and removes the reference to it from the baskets,
952
953 =over
954
955 =item C<$basketgroupid> is the 'id' field of the basket in the aqbasketgroup table
956
957 =back
958
959 =cut
960
961 sub DelBasketgroup {
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);
968     $sth->finish;
969 }
970
971 #------------------------------------------------------------#
972
973
974 =head2 FUNCTIONS ABOUT ORDERS
975
976 =head3 GetBasketgroup
977
978   $basketgroup = &GetBasketgroup($basketgroupid);
979
980 Returns a reference to the hash containing all infermation about the basketgroup.
981
982 =cut
983
984 sub GetBasketgroup {
985     my $basketgroupid = shift;
986     die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
987     my $query = "SELECT * FROM aqbasketgroups WHERE id=?";
988     my $dbh = C4::Context->dbh;
989     my $sth = $dbh->prepare($query);
990     $sth->execute($basketgroupid);
991     my $result = $sth->fetchrow_hashref;
992     $sth->finish;
993     return $result
994 }
995
996 #------------------------------------------------------------#
997
998 =head3 GetBasketgroups
999
1000   $basketgroups = &GetBasketgroups($booksellerid);
1001
1002 Returns a reference to the array of all the basketgroups of bookseller $booksellerid.
1003
1004 =cut
1005
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({});
1014 }
1015
1016 #------------------------------------------------------------#
1017
1018 =head2 FUNCTIONS ABOUT ORDERS
1019
1020 =head3 GetOrders
1021
1022   @orders = &GetOrders($basketnumber, $orderby);
1023
1024 Looks up the pending (non-cancelled) orders with the given basket
1025 number. If C<$booksellerID> is non-empty, only orders from that seller
1026 are returned.
1027
1028 return :
1029 C<&basket> returns a two-element array. C<@orders> is an array of
1030 references-to-hash, whose keys are the fields from the aqorders,
1031 biblio, and biblioitems tables in the Koha database.
1032
1033 =cut
1034
1035 sub GetOrders {
1036     my ( $basketno, $orderby ) = @_;
1037     my $dbh   = C4::Context->dbh;
1038     my $query  ="
1039         SELECT biblio.*,biblioitems.*,
1040                 aqorders.*,
1041                 aqbudgets.*,
1042                 biblio.title,
1043                 aqorders_transfers.ordernumber_from AS transferred_from,
1044                 aqorders_transfers.timestamp AS transferred_from_timestamp
1045         FROM    aqorders
1046             LEFT JOIN aqbudgets        ON aqbudgets.budget_id = aqorders.budget_id
1047             LEFT JOIN biblio           ON biblio.biblionumber = aqorders.biblionumber
1048             LEFT JOIN biblioitems      ON biblioitems.biblionumber =biblio.biblionumber
1049             LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_to = aqorders.ordernumber
1050         WHERE   basketno=?
1051             AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
1052     ";
1053
1054     $orderby = "biblioitems.publishercode,biblio.title" unless $orderby;
1055     $query .= " ORDER BY $orderby";
1056     my $sth = $dbh->prepare($query);
1057     $sth->execute($basketno);
1058     my $results = $sth->fetchall_arrayref({});
1059     $sth->finish;
1060     return @$results;
1061 }
1062
1063 #------------------------------------------------------------#
1064 =head3 GetOrdersByBiblionumber
1065
1066   @orders = &GetOrdersByBiblionumber($biblionumber);
1067
1068 Looks up the orders with linked to a specific $biblionumber, including
1069 cancelled orders and received orders.
1070
1071 return :
1072 C<@orders> is an array of references-to-hash, whose keys are the
1073 fields from the aqorders, biblio, and biblioitems tables in the Koha database.
1074
1075 =cut
1076
1077 sub GetOrdersByBiblionumber {
1078     my $biblionumber = shift;
1079     return unless $biblionumber;
1080     my $dbh   = C4::Context->dbh;
1081     my $query  ="
1082         SELECT biblio.*,biblioitems.*,
1083                 aqorders.*,
1084                 aqbudgets.*
1085         FROM    aqorders
1086             LEFT JOIN aqbudgets        ON aqbudgets.budget_id = aqorders.budget_id
1087             LEFT JOIN biblio           ON biblio.biblionumber = aqorders.biblionumber
1088             LEFT JOIN biblioitems      ON biblioitems.biblionumber =biblio.biblionumber
1089         WHERE   aqorders.biblionumber=?
1090     ";
1091     my $sth = $dbh->prepare($query);
1092     $sth->execute($biblionumber);
1093     my $results = $sth->fetchall_arrayref({});
1094     $sth->finish;
1095     return @$results;
1096 }
1097
1098 #------------------------------------------------------------#
1099
1100 =head3 GetOrder
1101
1102   $order = &GetOrder($ordernumber);
1103
1104 Looks up an order by order number.
1105
1106 Returns a reference-to-hash describing the order. The keys of
1107 C<$order> are fields from the biblio, biblioitems, aqorders tables of the Koha database.
1108
1109 =cut
1110
1111 sub GetOrder {
1112     my ($ordernumber) = @_;
1113     my $dbh      = C4::Context->dbh;
1114     my $query = qq{SELECT
1115                 aqorders.*,
1116                 biblio.title,
1117                 biblio.author,
1118                 aqbasket.basketname,
1119                 borrowers.branchcode,
1120                 biblioitems.publicationyear,
1121                 biblio.copyrightdate,
1122                 biblioitems.editionstatement,
1123                 biblioitems.isbn,
1124                 biblioitems.ean,
1125                 biblio.seriestitle,
1126                 biblioitems.publishercode,
1127                 aqorders.rrp              AS unitpricesupplier,
1128                 aqorders.ecost            AS unitpricelib,
1129                 aqorders.claims_count     AS claims_count,
1130                 aqorders.claimed_date     AS claimed_date,
1131                 aqbudgets.budget_name     AS budget,
1132                 aqbooksellers.name        AS supplier,
1133                 aqbooksellers.id          AS supplierid,
1134                 biblioitems.publishercode AS publisher,
1135                 ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) AS estimateddeliverydate,
1136                 DATE(aqbasket.closedate)  AS orderdate,
1137                 aqorders.quantity - COALESCE(aqorders.quantityreceived,0)                 AS quantity_to_receive,
1138                 (aqorders.quantity - COALESCE(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
1139                 DATEDIFF(CURDATE( ),closedate) AS latesince
1140                 FROM aqorders LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1141                 LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
1142                 LEFT JOIN aqbudgets ON aqorders.budget_id = aqbudgets.budget_id,
1143                 aqbasket LEFT JOIN borrowers  ON aqbasket.authorisedby = borrowers.borrowernumber
1144                 LEFT JOIN aqbooksellers       ON aqbasket.booksellerid = aqbooksellers.id
1145                 WHERE aqorders.basketno = aqbasket.basketno
1146                     AND ordernumber=?};
1147     my $sth= $dbh->prepare($query);
1148     $sth->execute($ordernumber);
1149     my $data = $sth->fetchrow_hashref;
1150     $data->{orderdate} = format_date( $data->{orderdate} );
1151     $sth->finish;
1152     return $data;
1153 }
1154
1155 =head3 GetLastOrderNotReceivedFromSubscriptionid
1156
1157   $order = &GetLastOrderNotReceivedFromSubscriptionid($subscriptionid);
1158
1159 Returns a reference-to-hash describing the last order not received for a subscription.
1160
1161 =cut
1162
1163 sub GetLastOrderNotReceivedFromSubscriptionid {
1164     my ( $subscriptionid ) = @_;
1165     my $dbh                = C4::Context->dbh;
1166     my $query              = qq|
1167         SELECT * FROM aqorders
1168         LEFT JOIN subscription
1169             ON ( aqorders.subscriptionid = subscription.subscriptionid )
1170         WHERE aqorders.subscriptionid = ?
1171             AND aqorders.datereceived IS NULL
1172         LIMIT 1
1173     |;
1174     my $sth = $dbh->prepare( $query );
1175     $sth->execute( $subscriptionid );
1176     my $order = $sth->fetchrow_hashref;
1177     return $order;
1178 }
1179
1180 =head3 GetLastOrderReceivedFromSubscriptionid
1181
1182   $order = &GetLastOrderReceivedFromSubscriptionid($subscriptionid);
1183
1184 Returns a reference-to-hash describing the last order received for a subscription.
1185
1186 =cut
1187
1188 sub GetLastOrderReceivedFromSubscriptionid {
1189     my ( $subscriptionid ) = @_;
1190     my $dbh                = C4::Context->dbh;
1191     my $query              = qq|
1192         SELECT * FROM aqorders
1193         LEFT JOIN subscription
1194             ON ( aqorders.subscriptionid = subscription.subscriptionid )
1195         WHERE aqorders.subscriptionid = ?
1196             AND aqorders.datereceived =
1197                 (
1198                     SELECT MAX( aqorders.datereceived )
1199                     FROM aqorders
1200                     LEFT JOIN subscription
1201                         ON ( aqorders.subscriptionid = subscription.subscriptionid )
1202                         WHERE aqorders.subscriptionid = ?
1203                             AND aqorders.datereceived IS NOT NULL
1204                 )
1205         ORDER BY ordernumber DESC
1206         LIMIT 1
1207     |;
1208     my $sth = $dbh->prepare( $query );
1209     $sth->execute( $subscriptionid, $subscriptionid );
1210     my $order = $sth->fetchrow_hashref;
1211     return $order;
1212
1213 }
1214
1215
1216 #------------------------------------------------------------#
1217
1218 =head3 NewOrder
1219
1220   &NewOrder(\%hashref);
1221
1222 Adds a new order to the database. Any argument that isn't described
1223 below is the new value of the field with the same name in the aqorders
1224 table of the Koha database.
1225
1226 =over
1227
1228 =item $hashref->{'basketno'} is the basketno foreign key in aqorders, it is mandatory
1229
1230 =item $hashref->{'ordernumber'} is a "minimum order number."
1231
1232 =item $hashref->{'budgetdate'} is effectively ignored.
1233 If it's undef (anything false) or the string 'now', the current day is used.
1234 Else, the upcoming July 1st is used.
1235
1236 =item $hashref->{'subscription'} may be either "yes", or anything else for "no".
1237
1238 =item $hashref->{'uncertainprice'} may be 0 for "the price is known" or 1 for "the price is uncertain"
1239
1240 =item defaults entrydate to Now
1241
1242 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".
1243
1244 =back
1245
1246 =cut
1247
1248 sub NewOrder {
1249     my $orderinfo = shift;
1250
1251     my $dbh = C4::Context->dbh;
1252     my @params;
1253
1254
1255     # if these parameters are missing, we can't continue
1256     for my $key (qw/basketno quantity biblionumber budget_id/) {
1257         croak "Mandatory parameter $key missing" unless $orderinfo->{$key};
1258     }
1259
1260     if ( defined $orderinfo->{subscription} && $orderinfo->{'subscription'} eq 'yes' ) {
1261         $orderinfo->{'subscription'} = 1;
1262     } else {
1263         $orderinfo->{'subscription'} = 0;
1264     }
1265     $orderinfo->{'entrydate'} ||= C4::Dates->new()->output("iso");
1266     if (!$orderinfo->{quantityreceived}) {
1267         $orderinfo->{quantityreceived} = 0;
1268     }
1269
1270     my $ordernumber=InsertInTable("aqorders",$orderinfo);
1271     if (not $orderinfo->{parent_ordernumber}) {
1272         my $sth = $dbh->prepare("
1273             UPDATE aqorders
1274             SET parent_ordernumber = ordernumber
1275             WHERE ordernumber = ?
1276         ");
1277         $sth->execute($ordernumber);
1278     }
1279     return ( $orderinfo->{'basketno'}, $ordernumber );
1280 }
1281
1282
1283
1284 #------------------------------------------------------------#
1285
1286 =head3 NewOrderItem
1287
1288   &NewOrderItem();
1289
1290 =cut
1291
1292 sub NewOrderItem {
1293     my ($itemnumber, $ordernumber)  = @_;
1294     my $dbh = C4::Context->dbh;
1295     my $query = qq|
1296             INSERT INTO aqorders_items
1297                 (itemnumber, ordernumber)
1298             VALUES (?,?)    |;
1299
1300     my $sth = $dbh->prepare($query);
1301     $sth->execute( $itemnumber, $ordernumber);
1302 }
1303
1304 #------------------------------------------------------------#
1305
1306 =head3 ModOrder
1307
1308   &ModOrder(\%hashref);
1309
1310 Modifies an existing order. Updates the order with order number
1311 $hashref->{'ordernumber'} and biblionumber $hashref->{'biblionumber'}. All 
1312 other keys of the hash update the fields with the same name in the aqorders 
1313 table of the Koha database.
1314
1315 =cut
1316
1317 sub ModOrder {
1318     my $orderinfo = shift;
1319
1320     die "Ordernumber is required"     if $orderinfo->{'ordernumber'} eq  '' ;
1321     die "Biblionumber is required"  if  $orderinfo->{'biblionumber'} eq '';
1322
1323     my $dbh = C4::Context->dbh;
1324     my @params;
1325
1326     # update uncertainprice to an integer, just in case (under FF, checked boxes have the value "ON" by default)
1327     $orderinfo->{uncertainprice}=1 if $orderinfo->{uncertainprice};
1328
1329 #    delete($orderinfo->{'branchcode'});
1330     # the hash contains a lot of entries not in aqorders, so get the columns ...
1331     my $sth = $dbh->prepare("SELECT * FROM aqorders LIMIT 1;");
1332     $sth->execute;
1333     my $colnames = $sth->{NAME};
1334         #FIXME Be careful. If aqorders would have columns with diacritics,
1335         #you should need to decode what you get back from NAME.
1336         #See report 10110 and guided_reports.pl
1337     my $query = "UPDATE aqorders SET ";
1338
1339     foreach my $orderinfokey (grep(!/ordernumber/, keys %$orderinfo)){
1340         # ... and skip hash entries that are not in the aqorders table
1341         # FIXME : probably not the best way to do it (would be better to have a correct hash)
1342         next unless grep(/^$orderinfokey$/, @$colnames);
1343             $query .= "$orderinfokey=?, ";
1344             push(@params, $orderinfo->{$orderinfokey});
1345     }
1346
1347     $query .= "timestamp=NOW()  WHERE  ordernumber=?";
1348 #   push(@params, $specorderinfo{'ordernumber'});
1349     push(@params, $orderinfo->{'ordernumber'} );
1350     $sth = $dbh->prepare($query);
1351     $sth->execute(@params);
1352     $sth->finish;
1353 }
1354
1355 #------------------------------------------------------------#
1356
1357 =head3 ModItemOrder
1358
1359     ModItemOrder($itemnumber, $ordernumber);
1360
1361 Modifies the ordernumber of an item in aqorders_items.
1362
1363 =cut
1364
1365 sub ModItemOrder {
1366     my ($itemnumber, $ordernumber) = @_;
1367
1368     return unless ($itemnumber and $ordernumber);
1369
1370     my $dbh = C4::Context->dbh;
1371     my $query = qq{
1372         UPDATE aqorders_items
1373         SET ordernumber = ?
1374         WHERE itemnumber = ?
1375     };
1376     my $sth = $dbh->prepare($query);
1377     return $sth->execute($ordernumber, $itemnumber);
1378 }
1379
1380 #------------------------------------------------------------#
1381
1382 =head3 GetCancelledOrders
1383
1384   my @orders = GetCancelledOrders($basketno, $orderby);
1385
1386 Returns cancelled orders for a basket
1387
1388 =cut
1389
1390 sub GetCancelledOrders {
1391     my ( $basketno, $orderby ) = @_;
1392
1393     return () unless $basketno;
1394
1395     my $dbh   = C4::Context->dbh;
1396     my $query = "
1397         SELECT
1398             biblio.*,
1399             biblioitems.*,
1400             aqorders.*,
1401             aqbudgets.*,
1402             aqorders_transfers.ordernumber_to AS transferred_to,
1403             aqorders_transfers.timestamp AS transferred_to_timestamp
1404         FROM aqorders
1405           LEFT JOIN aqbudgets   ON aqbudgets.budget_id = aqorders.budget_id
1406           LEFT JOIN biblio      ON biblio.biblionumber = aqorders.biblionumber
1407           LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
1408           LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_from = aqorders.ordernumber
1409         WHERE basketno = ?
1410           AND (datecancellationprinted IS NOT NULL
1411                AND datecancellationprinted <> '0000-00-00')
1412     ";
1413
1414     $orderby = "aqorders.datecancellationprinted desc, aqorders.timestamp desc"
1415         unless $orderby;
1416     $query .= " ORDER BY $orderby";
1417     my $sth = $dbh->prepare($query);
1418     $sth->execute($basketno);
1419     my $results = $sth->fetchall_arrayref( {} );
1420
1421     return @$results;
1422 }
1423
1424
1425 #------------------------------------------------------------#
1426
1427 =head3 ModReceiveOrder
1428
1429   &ModReceiveOrder($biblionumber, $ordernumber, $quantityreceived, $user,
1430     $cost, $ecost, $invoiceid, rrp, budget_id, datereceived, \@received_itemnumbers);
1431
1432 Updates an order, to reflect the fact that it was received, at least
1433 in part. All arguments not mentioned below update the fields with the
1434 same name in the aqorders table of the Koha database.
1435
1436 If a partial order is received, splits the order into two.
1437
1438 Updates the order with bibilionumber C<$biblionumber> and ordernumber
1439 C<$ordernumber>.
1440
1441 =cut
1442
1443
1444 sub ModReceiveOrder {
1445     my (
1446         $biblionumber,    $ordernumber,  $quantrec, $user, $cost, $ecost,
1447         $invoiceid, $rrp, $budget_id, $datereceived, $received_items
1448     )
1449     = @_;
1450
1451     my $dbh = C4::Context->dbh;
1452     $datereceived = C4::Dates->output('iso') unless $datereceived;
1453     my $suggestionid = GetSuggestionFromBiblionumber( $biblionumber );
1454     if ($suggestionid) {
1455         ModSuggestion( {suggestionid=>$suggestionid,
1456                         STATUS=>'AVAILABLE',
1457                         biblionumber=> $biblionumber}
1458                         );
1459     }
1460
1461     my $sth=$dbh->prepare("
1462         SELECT * FROM   aqorders
1463         WHERE           biblionumber=? AND aqorders.ordernumber=?");
1464
1465     $sth->execute($biblionumber,$ordernumber);
1466     my $order = $sth->fetchrow_hashref();
1467     $sth->finish();
1468
1469     my $new_ordernumber = $ordernumber;
1470     if ( $order->{quantity} > $quantrec ) {
1471         # Split order line in two parts: the first is the original order line
1472         # without received items (the quantity is decreased),
1473         # the second part is a new order line with quantity=quantityrec
1474         # (entirely received)
1475         $sth=$dbh->prepare("
1476             UPDATE aqorders
1477             SET quantity = ?,
1478                 orderstatus = 'partial'
1479             WHERE ordernumber = ?
1480         ");
1481
1482         $sth->execute($order->{quantity} - $quantrec, $ordernumber);
1483
1484         $sth->finish;
1485
1486         delete $order->{'ordernumber'};
1487         $order->{'budget_id'} = ( $budget_id || $order->{'budget_id'} );
1488         $order->{'quantity'} = $quantrec;
1489         $order->{'quantityreceived'} = $quantrec;
1490         $order->{'datereceived'} = $datereceived;
1491         $order->{'invoiceid'} = $invoiceid;
1492         $order->{'unitprice'} = $cost;
1493         $order->{'rrp'} = $rrp;
1494         $order->{ecost} = $ecost;
1495         $order->{'orderstatus'} = 'complete';
1496         my $basketno;
1497         ( $basketno, $new_ordernumber ) = NewOrder($order);
1498
1499         if ($received_items) {
1500             foreach my $itemnumber (@$received_items) {
1501                 ModItemOrder($itemnumber, $new_ordernumber);
1502             }
1503         }
1504     } else {
1505         $sth=$dbh->prepare("update aqorders
1506                             set quantityreceived=?,datereceived=?,invoiceid=?,
1507                                 unitprice=?,rrp=?,ecost=?,budget_id=?,orderstatus='complete'
1508                             where biblionumber=? and ordernumber=?");
1509         $sth->execute($quantrec,$datereceived,$invoiceid,$cost,$rrp,$ecost,$budget_id,$biblionumber,$ordernumber);
1510         $sth->finish;
1511     }
1512     return ($datereceived, $new_ordernumber);
1513 }
1514
1515 =head3 CancelReceipt
1516
1517     my $parent_ordernumber = CancelReceipt($ordernumber);
1518
1519     Cancel an order line receipt and update the parent order line, as if no
1520     receipt was made.
1521     If items are created at receipt (AcqCreateItem = receiving) then delete
1522     these items.
1523
1524 =cut
1525
1526 sub CancelReceipt {
1527     my $ordernumber = shift;
1528
1529     return unless $ordernumber;
1530
1531     my $dbh = C4::Context->dbh;
1532     my $query = qq{
1533         SELECT datereceived, parent_ordernumber, quantity
1534         FROM aqorders
1535         WHERE ordernumber = ?
1536     };
1537     my $sth = $dbh->prepare($query);
1538     $sth->execute($ordernumber);
1539     my $order = $sth->fetchrow_hashref;
1540     unless($order) {
1541         warn "CancelReceipt: order $ordernumber does not exist";
1542         return;
1543     }
1544     unless($order->{'datereceived'}) {
1545         warn "CancelReceipt: order $ordernumber is not received";
1546         return;
1547     }
1548
1549     my $parent_ordernumber = $order->{'parent_ordernumber'};
1550
1551     if($parent_ordernumber == $ordernumber || not $parent_ordernumber) {
1552         # The order line has no parent, just mark it as not received
1553         $query = qq{
1554             UPDATE aqorders
1555             SET quantityreceived = ?,
1556                 datereceived = ?,
1557                 invoiceid = ?,
1558                 orderstatus = 'ordered'
1559             WHERE ordernumber = ?
1560         };
1561         $sth = $dbh->prepare($query);
1562         $sth->execute(0, undef, undef, $ordernumber);
1563     } else {
1564         # The order line has a parent, increase parent quantity and delete
1565         # the order line.
1566         $query = qq{
1567             SELECT quantity, datereceived
1568             FROM aqorders
1569             WHERE ordernumber = ?
1570         };
1571         $sth = $dbh->prepare($query);
1572         $sth->execute($parent_ordernumber);
1573         my $parent_order = $sth->fetchrow_hashref;
1574         unless($parent_order) {
1575             warn "Parent order $parent_ordernumber does not exist.";
1576             return;
1577         }
1578         if($parent_order->{'datereceived'}) {
1579             warn "CancelReceipt: parent order is received.".
1580                 " Can't cancel receipt.";
1581             return;
1582         }
1583         $query = qq{
1584             UPDATE aqorders
1585             SET quantity = ?,
1586                 orderstatus = 'ordered'
1587             WHERE ordernumber = ?
1588         };
1589         $sth = $dbh->prepare($query);
1590         my $rv = $sth->execute(
1591             $order->{'quantity'} + $parent_order->{'quantity'},
1592             $parent_ordernumber
1593         );
1594         unless($rv) {
1595             warn "Cannot update parent order line, so do not cancel".
1596                 " receipt";
1597             return;
1598         }
1599         if(C4::Context->preference('AcqCreateItem') eq 'receiving') {
1600             # Remove items that were created at receipt
1601             $query = qq{
1602                 DELETE FROM items, aqorders_items
1603                 USING items, aqorders_items
1604                 WHERE items.itemnumber = ? AND aqorders_items.itemnumber = ?
1605             };
1606             $sth = $dbh->prepare($query);
1607             my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
1608             foreach my $itemnumber (@itemnumbers) {
1609                 $sth->execute($itemnumber, $itemnumber);
1610             }
1611         } else {
1612             # Update items
1613             my @itemnumbers = GetItemnumbersFromOrder($ordernumber);
1614             foreach my $itemnumber (@itemnumbers) {
1615                 ModItemOrder($itemnumber, $parent_ordernumber);
1616             }
1617         }
1618         # Delete order line
1619         $query = qq{
1620             DELETE FROM aqorders
1621             WHERE ordernumber = ?
1622         };
1623         $sth = $dbh->prepare($query);
1624         $sth->execute($ordernumber);
1625
1626     }
1627
1628     return $parent_ordernumber;
1629 }
1630
1631 #------------------------------------------------------------#
1632
1633 =head3 SearchOrders
1634
1635 @results = &SearchOrders({
1636     ordernumber => $ordernumber,
1637     search => $search,
1638     biblionumber => $biblionumber,
1639     ean => $ean,
1640     booksellerid => $booksellerid,
1641     basketno => $basketno,
1642     owner => $owner,
1643     pending => $pending
1644 });
1645
1646 Searches for orders.
1647
1648 C<$owner> Finds order for the logged in user.
1649 C<$pending> Finds pending orders. Ignores completed and cancelled orders.
1650
1651
1652 C<@results> is an array of references-to-hash with the keys are fields
1653 from aqorders, biblio, biblioitems and aqbasket tables.
1654
1655 =cut
1656
1657 sub SearchOrders {
1658     my ( $params ) = @_;
1659     my $ordernumber = $params->{ordernumber};
1660     my $search = $params->{search};
1661     my $ean = $params->{ean};
1662     my $booksellerid = $params->{booksellerid};
1663     my $basketno = $params->{basketno};
1664     my $basketname = $params->{basketname};
1665     my $basketgroupname = $params->{basketgroupname};
1666     my $owner = $params->{owner};
1667     my $pending = $params->{pending};
1668
1669     my $dbh = C4::Context->dbh;
1670     my @args = ();
1671     my $query = q{
1672         SELECT aqbasket.basketno,
1673                borrowers.surname,
1674                borrowers.firstname,
1675                biblio.*,
1676                biblioitems.isbn,
1677                biblioitems.biblioitemnumber,
1678                aqbasket.closedate,
1679                aqbasket.creationdate,
1680                aqbasket.basketname,
1681                aqorders.*
1682         FROM aqorders
1683             LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
1684             LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid = aqbasketgroups.id
1685             LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
1686             LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1687             LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
1688         WHERE (datecancellationprinted is NULL)
1689     };
1690
1691     $query .= q{
1692         AND (quantity > quantityreceived OR quantityreceived is NULL)
1693     } if $pending;
1694
1695     my $userenv = C4::Context->userenv;
1696     if ( C4::Context->preference("IndependentBranches") ) {
1697         if ( ( $userenv ) and ( $userenv->{flags} != 1 ) ) {
1698             $query .= q{
1699                 AND (
1700                     borrowers.branchcode = ?
1701                     OR borrowers.branchcode  = ''
1702                 )
1703             };
1704             push @args, $userenv->{branch};
1705         }
1706     }
1707
1708     if ( $ordernumber ) {
1709         $query .= ' AND (aqorders.ordernumber=?)';
1710         push @args, $ordernumber;
1711     }
1712     if( $search ) {
1713         $query .= ' AND (biblio.title LIKE ? OR biblio.author LIKE ? OR biblioitems.isbn LIKE ?)';
1714         push @args, ("%$search%","%$search%","%$search%");
1715     }
1716     if ( $ean ) {
1717         $query .= ' AND biblioitems.ean = ?';
1718         push @args, $ean;
1719     }
1720     if ( $booksellerid ) {
1721         $query .= 'AND aqbasket.booksellerid = ?';
1722         push @args, $booksellerid;
1723     }
1724     if( $basketno ) {
1725         $query .= 'AND aqbasket.basketno = ?';
1726         push @args, $basketno;
1727     }
1728     if( $basketname ) {
1729         $query .= 'AND aqbasket.basketname LIKE ?';
1730         push @args, "%$basketname%";
1731     }
1732     if( $basketgroupname ) {
1733         $query .= ' AND aqbasketgroups.name LIKE ?';
1734         push @args, "%$basketgroupname%";
1735     }
1736
1737     if ( $owner ) {
1738         $query .= ' AND aqbasket.authorisedby=? ';
1739         push @args, $userenv->{'number'};
1740     }
1741
1742     $query .= ' ORDER BY aqbasket.basketno';
1743
1744     my $sth = $dbh->prepare($query);
1745     $sth->execute(@args);
1746     return $sth->fetchall_arrayref({});
1747 }
1748
1749 #------------------------------------------------------------#
1750
1751 =head3 DelOrder
1752
1753   &DelOrder($biblionumber, $ordernumber);
1754
1755 Cancel the order with the given order and biblio numbers. It does not
1756 delete any entries in the aqorders table, it merely marks them as
1757 cancelled.
1758
1759 =cut
1760
1761 sub DelOrder {
1762     my ( $bibnum, $ordernumber ) = @_;
1763     my $dbh = C4::Context->dbh;
1764     my $query = "
1765         UPDATE aqorders
1766         SET    datecancellationprinted=now(), orderstatus='cancelled'
1767         WHERE  biblionumber=? AND ordernumber=?
1768     ";
1769     my $sth = $dbh->prepare($query);
1770     $sth->execute( $bibnum, $ordernumber );
1771     $sth->finish;
1772     my @itemnumbers = GetItemnumbersFromOrder( $ordernumber );
1773     foreach my $itemnumber (@itemnumbers){
1774         C4::Items::DelItem( $dbh, $bibnum, $itemnumber );
1775     }
1776     
1777 }
1778
1779 =head3 TransferOrder
1780
1781     my $newordernumber = TransferOrder($ordernumber, $basketno);
1782
1783 Transfer an order line to a basket.
1784 Mark $ordernumber as cancelled with an internal note 'Cancelled and transfered
1785 to BOOKSELLER on DATE' and create new order with internal note
1786 'Transfered from BOOKSELLER on DATE'.
1787 Move all attached items to the new order.
1788 Received orders cannot be transfered.
1789 Return the ordernumber of created order.
1790
1791 =cut
1792
1793 sub TransferOrder {
1794     my ($ordernumber, $basketno) = @_;
1795
1796     return unless ($ordernumber and $basketno);
1797
1798     my $order = GetOrder( $ordernumber );
1799     return if $order->{datereceived};
1800     my $basket = GetBasket($basketno);
1801     return unless $basket;
1802
1803     my $dbh = C4::Context->dbh;
1804     my ($query, $sth, $rv);
1805
1806     $query = qq{
1807         UPDATE aqorders
1808         SET datecancellationprinted = CAST(NOW() AS date)
1809         WHERE ordernumber = ?
1810     };
1811     $sth = $dbh->prepare($query);
1812     $rv = $sth->execute($ordernumber);
1813
1814     delete $order->{'ordernumber'};
1815     $order->{'basketno'} = $basketno;
1816     my $newordernumber;
1817     (undef, $newordernumber) = NewOrder($order);
1818
1819     $query = qq{
1820         UPDATE aqorders_items
1821         SET ordernumber = ?
1822         WHERE ordernumber = ?
1823     };
1824     $sth = $dbh->prepare($query);
1825     $sth->execute($newordernumber, $ordernumber);
1826
1827     $query = q{
1828         INSERT INTO aqorders_transfers (ordernumber_from, ordernumber_to)
1829         VALUES (?, ?)
1830     };
1831     $sth = $dbh->prepare($query);
1832     $sth->execute($ordernumber, $newordernumber);
1833
1834     return $newordernumber;
1835 }
1836
1837 =head2 FUNCTIONS ABOUT PARCELS
1838
1839 =cut
1840
1841 #------------------------------------------------------------#
1842
1843 =head3 GetParcel
1844
1845   @results = &GetParcel($booksellerid, $code, $date);
1846
1847 Looks up all of the received items from the supplier with the given
1848 bookseller ID at the given date, for the given code (bookseller Invoice number). Ignores cancelled and completed orders.
1849
1850 C<@results> is an array of references-to-hash. The keys of each element are fields from
1851 the aqorders, biblio, and biblioitems tables of the Koha database.
1852
1853 C<@results> is sorted alphabetically by book title.
1854
1855 =cut
1856
1857 sub GetParcel {
1858     #gets all orders from a certain supplier, orders them alphabetically
1859     my ( $supplierid, $code, $datereceived ) = @_;
1860     my $dbh     = C4::Context->dbh;
1861     my @results = ();
1862     $code .= '%'
1863     if $code;  # add % if we search on a given code (otherwise, let him empty)
1864     my $strsth ="
1865         SELECT  authorisedby,
1866                 creationdate,
1867                 aqbasket.basketno,
1868                 closedate,surname,
1869                 firstname,
1870                 aqorders.biblionumber,
1871                 aqorders.ordernumber,
1872                 aqorders.parent_ordernumber,
1873                 aqorders.quantity,
1874                 aqorders.quantityreceived,
1875                 aqorders.unitprice,
1876                 aqorders.listprice,
1877                 aqorders.rrp,
1878                 aqorders.ecost,
1879                 aqorders.gstrate,
1880                 biblio.title
1881         FROM aqorders
1882         LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
1883         LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
1884         LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1885         LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
1886         WHERE
1887             aqbasket.booksellerid = ?
1888             AND aqinvoices.invoicenumber LIKE ?
1889             AND aqorders.datereceived = ? ";
1890
1891     my @query_params = ( $supplierid, $code, $datereceived );
1892     if ( C4::Context->preference("IndependentBranches") ) {
1893         my $userenv = C4::Context->userenv;
1894         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1895             $strsth .= " and (borrowers.branchcode = ?
1896                         or borrowers.branchcode  = '')";
1897             push @query_params, $userenv->{branch};
1898         }
1899     }
1900     $strsth .= " ORDER BY aqbasket.basketno";
1901     # ## parcelinformation : $strsth
1902     my $sth = $dbh->prepare($strsth);
1903     $sth->execute( @query_params );
1904     while ( my $data = $sth->fetchrow_hashref ) {
1905         push( @results, $data );
1906     }
1907     # ## countparcelbiblio: scalar(@results)
1908     $sth->finish;
1909
1910     return @results;
1911 }
1912
1913 #------------------------------------------------------------#
1914
1915 =head3 GetParcels
1916
1917   $results = &GetParcels($bookseller, $order, $code, $datefrom, $dateto);
1918
1919 get a lists of parcels.
1920
1921 * Input arg :
1922
1923 =over
1924
1925 =item $bookseller
1926 is the bookseller this function has to get parcels.
1927
1928 =item $order
1929 To know on what criteria the results list has to be ordered.
1930
1931 =item $code
1932 is the booksellerinvoicenumber.
1933
1934 =item $datefrom & $dateto
1935 to know on what date this function has to filter its search.
1936
1937 =back
1938
1939 * return:
1940 a pointer on a hash list containing parcel informations as such :
1941
1942 =over
1943
1944 =item Creation date
1945
1946 =item Last operation
1947
1948 =item Number of biblio
1949
1950 =item Number of items
1951
1952 =back
1953
1954 =cut
1955
1956 sub GetParcels {
1957     my ($bookseller,$order, $code, $datefrom, $dateto) = @_;
1958     my $dbh    = C4::Context->dbh;
1959     my @query_params = ();
1960     my $strsth ="
1961         SELECT  aqinvoices.invoicenumber,
1962                 datereceived,purchaseordernumber,
1963                 count(DISTINCT biblionumber) AS biblio,
1964                 sum(quantity) AS itemsexpected,
1965                 sum(quantityreceived) AS itemsreceived
1966         FROM   aqorders LEFT JOIN aqbasket ON aqbasket.basketno = aqorders.basketno
1967         LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
1968         WHERE aqbasket.booksellerid = ? and datereceived IS NOT NULL
1969     ";
1970     push @query_params, $bookseller;
1971
1972     if ( defined $code ) {
1973         $strsth .= ' and aqinvoices.invoicenumber like ? ';
1974         # add a % to the end of the code to allow stemming.
1975         push @query_params, "$code%";
1976     }
1977
1978     if ( defined $datefrom ) {
1979         $strsth .= ' and datereceived >= ? ';
1980         push @query_params, $datefrom;
1981     }
1982
1983     if ( defined $dateto ) {
1984         $strsth .=  'and datereceived <= ? ';
1985         push @query_params, $dateto;
1986     }
1987
1988     $strsth .= "group by aqinvoices.invoicenumber,datereceived ";
1989
1990     # can't use a placeholder to place this column name.
1991     # but, we could probably be checking to make sure it is a column that will be fetched.
1992     $strsth .= "order by $order " if ($order);
1993
1994     my $sth = $dbh->prepare($strsth);
1995
1996     $sth->execute( @query_params );
1997     my $results = $sth->fetchall_arrayref({});
1998     $sth->finish;
1999     return @$results;
2000 }
2001
2002 #------------------------------------------------------------#
2003
2004 =head3 GetLateOrders
2005
2006   @results = &GetLateOrders;
2007
2008 Searches for bookseller with late orders.
2009
2010 return:
2011 the table of supplier with late issues. This table is full of hashref.
2012
2013 =cut
2014
2015 sub GetLateOrders {
2016     my $delay      = shift;
2017     my $supplierid = shift;
2018     my $branch     = shift;
2019     my $estimateddeliverydatefrom = shift;
2020     my $estimateddeliverydateto = shift;
2021
2022     my $dbh = C4::Context->dbh;
2023
2024     #BEWARE, order of parenthesis and LEFT JOIN is important for speed
2025     my $dbdriver = C4::Context->config("db_scheme") || "mysql";
2026
2027     my @query_params = ();
2028     my $select = "
2029     SELECT aqbasket.basketno,
2030         aqorders.ordernumber,
2031         DATE(aqbasket.closedate)  AS orderdate,
2032         aqorders.rrp              AS unitpricesupplier,
2033         aqorders.ecost            AS unitpricelib,
2034         aqorders.claims_count     AS claims_count,
2035         aqorders.claimed_date     AS claimed_date,
2036         aqbudgets.budget_name     AS budget,
2037         borrowers.branchcode      AS branch,
2038         aqbooksellers.name        AS supplier,
2039         aqbooksellers.id          AS supplierid,
2040         biblio.author, biblio.title,
2041         biblioitems.publishercode AS publisher,
2042         biblioitems.publicationyear,
2043         ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) AS estimateddeliverydate,
2044     ";
2045     my $from = "
2046     FROM
2047         aqorders LEFT JOIN biblio     ON biblio.biblionumber         = aqorders.biblionumber
2048         LEFT JOIN biblioitems         ON biblioitems.biblionumber    = biblio.biblionumber
2049         LEFT JOIN aqbudgets           ON aqorders.budget_id          = aqbudgets.budget_id,
2050         aqbasket LEFT JOIN borrowers  ON aqbasket.authorisedby       = borrowers.borrowernumber
2051         LEFT JOIN aqbooksellers       ON aqbasket.booksellerid       = aqbooksellers.id
2052         WHERE aqorders.basketno = aqbasket.basketno
2053         AND ( datereceived = ''
2054             OR datereceived IS NULL
2055             OR aqorders.quantityreceived < aqorders.quantity
2056         )
2057         AND aqbasket.closedate IS NOT NULL
2058         AND (aqorders.datecancellationprinted IS NULL OR aqorders.datecancellationprinted='0000-00-00')
2059     ";
2060     my $having = "";
2061     if ($dbdriver eq "mysql") {
2062         $select .= "
2063         aqorders.quantity - COALESCE(aqorders.quantityreceived,0)                 AS quantity,
2064         (aqorders.quantity - COALESCE(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
2065         DATEDIFF(CAST(now() AS date),closedate) AS latesince
2066         ";
2067         if ( defined $delay ) {
2068             $from .= " AND (closedate <= DATE_SUB(CAST(now() AS date),INTERVAL ? DAY)) " ;
2069             push @query_params, $delay;
2070         }
2071         $having = "
2072         HAVING quantity          <> 0
2073             AND unitpricesupplier <> 0
2074             AND unitpricelib      <> 0
2075         ";
2076     } else {
2077         # FIXME: account for IFNULL as above
2078         $select .= "
2079                 aqorders.quantity                AS quantity,
2080                 aqorders.quantity * aqorders.rrp AS subtotal,
2081                 (CAST(now() AS date) - closedate)            AS latesince
2082         ";
2083         if ( defined $delay ) {
2084             $from .= " AND (closedate <= (CAST(now() AS date) -(INTERVAL ? DAY)) ";
2085             push @query_params, $delay;
2086         }
2087     }
2088     if (defined $supplierid) {
2089         $from .= ' AND aqbasket.booksellerid = ? ';
2090         push @query_params, $supplierid;
2091     }
2092     if (defined $branch) {
2093         $from .= ' AND borrowers.branchcode LIKE ? ';
2094         push @query_params, $branch;
2095     }
2096
2097     if ( defined $estimateddeliverydatefrom or defined $estimateddeliverydateto ) {
2098         $from .= ' AND aqbooksellers.deliverytime IS NOT NULL ';
2099     }
2100     if ( defined $estimateddeliverydatefrom ) {
2101         $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) >= ?';
2102         push @query_params, $estimateddeliverydatefrom;
2103     }
2104     if ( defined $estimateddeliverydateto ) {
2105         $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= ?';
2106         push @query_params, $estimateddeliverydateto;
2107     }
2108     if ( defined $estimateddeliverydatefrom and not defined $estimateddeliverydateto ) {
2109         $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= CAST(now() AS date)';
2110     }
2111     if (C4::Context->preference("IndependentBranches")
2112             && C4::Context->userenv
2113             && C4::Context->userenv->{flags} != 1 ) {
2114         $from .= ' AND borrowers.branchcode LIKE ? ';
2115         push @query_params, C4::Context->userenv->{branch};
2116     }
2117     $from .= " AND orderstatus <> 'cancelled' ";
2118     my $query = "$select $from $having\nORDER BY latesince, basketno, borrowers.branchcode, supplier";
2119     $debug and print STDERR "GetLateOrders query: $query\nGetLateOrders args: " . join(" ",@query_params);
2120     my $sth = $dbh->prepare($query);
2121     $sth->execute(@query_params);
2122     my @results;
2123     while (my $data = $sth->fetchrow_hashref) {
2124         $data->{orderdate} = format_date($data->{orderdate});
2125         $data->{claimed_date} = format_date($data->{claimed_date});
2126         push @results, $data;
2127     }
2128     return @results;
2129 }
2130
2131 #------------------------------------------------------------#
2132
2133 =head3 GetHistory
2134
2135   (\@order_loop, $total_qty, $total_price, $total_qtyreceived) = GetHistory( %params );
2136
2137 Retreives some acquisition history information
2138
2139 params:  
2140   title
2141   author
2142   name
2143   from_placed_on
2144   to_placed_on
2145   basket                  - search both basket name and number
2146   booksellerinvoicenumber 
2147
2148 returns:
2149     $order_loop is a list of hashrefs that each look like this:
2150             {
2151                 'author'           => 'Twain, Mark',
2152                 'basketno'         => '1',
2153                 'biblionumber'     => '215',
2154                 'count'            => 1,
2155                 'creationdate'     => 'MM/DD/YYYY',
2156                 'datereceived'     => undef,
2157                 'ecost'            => '1.00',
2158                 'id'               => '1',
2159                 'invoicenumber'    => undef,
2160                 'name'             => '',
2161                 'ordernumber'      => '1',
2162                 'quantity'         => 1,
2163                 'quantityreceived' => undef,
2164                 'title'            => 'The Adventures of Huckleberry Finn'
2165             }
2166     $total_qty is the sum of all of the quantities in $order_loop
2167     $total_price is the cost of each in $order_loop times the quantity
2168     $total_qtyreceived is the sum of all of the quantityreceived entries in $order_loop
2169
2170 =cut
2171
2172 sub GetHistory {
2173 # don't run the query if there are no parameters (list would be too long for sure !)
2174     croak "No search params" unless @_;
2175     my %params = @_;
2176     my $title = $params{title};
2177     my $author = $params{author};
2178     my $isbn   = $params{isbn};
2179     my $ean    = $params{ean};
2180     my $name = $params{name};
2181     my $from_placed_on = $params{from_placed_on};
2182     my $to_placed_on = $params{to_placed_on};
2183     my $basket = $params{basket};
2184     my $booksellerinvoicenumber = $params{booksellerinvoicenumber};
2185     my $basketgroupname = $params{basketgroupname};
2186     my $budget = $params{budget};
2187     my $orderstatus = $params{orderstatus};
2188
2189     my @order_loop;
2190     my $total_qty         = 0;
2191     my $total_qtyreceived = 0;
2192     my $total_price       = 0;
2193
2194     my $dbh   = C4::Context->dbh;
2195     my $query ="
2196         SELECT
2197             COALESCE(biblio.title,     deletedbiblio.title)     AS title,
2198             COALESCE(biblio.author,    deletedbiblio.author)    AS author,
2199             COALESCE(biblioitems.isbn, deletedbiblioitems.isbn) AS isbn,
2200             COALESCE(biblioitems.ean,  deletedbiblioitems.ean)  AS ean,
2201             aqorders.basketno,
2202             aqbasket.basketname,
2203             aqbasket.basketgroupid,
2204             aqbasketgroups.name as groupname,
2205             aqbooksellers.name,
2206             aqbasket.creationdate,
2207             aqorders.datereceived,
2208             aqorders.quantity,
2209             aqorders.quantityreceived,
2210             aqorders.ecost,
2211             aqorders.ordernumber,
2212             aqorders.invoiceid,
2213             aqinvoices.invoicenumber,
2214             aqbooksellers.id as id,
2215             aqorders.biblionumber,
2216             aqorders.orderstatus,
2217             aqorders.parent_ordernumber,
2218             aqbudgets.budget_name
2219             ";
2220     $query .= ", aqbudgets.budget_id AS budget" if defined $budget;
2221     $query .= "
2222         FROM aqorders
2223         LEFT JOIN aqbasket ON aqorders.basketno=aqbasket.basketno
2224         LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid=aqbasketgroups.id
2225         LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
2226         LEFT JOIN biblioitems ON biblioitems.biblionumber=aqorders.biblionumber
2227         LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
2228         LEFT JOIN aqbudgets ON aqorders.budget_id=aqbudgets.budget_id
2229         LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
2230         LEFT JOIN deletedbiblio ON deletedbiblio.biblionumber=aqorders.biblionumber
2231         LEFT JOIN deletedbiblioitems ON deletedbiblioitems.biblionumber=aqorders.biblionumber
2232         ";
2233
2234     if ( C4::Context->preference("IndependentBranches") ) {
2235         $query .= " LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber";
2236     }
2237
2238     $query .= " WHERE 1 ";
2239
2240     $query .= " AND (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') " if $orderstatus ne 'cancelled';
2241
2242     my @query_params  = ();
2243
2244     if ( $title ) {
2245         $query .= " AND biblio.title LIKE ? ";
2246         $title =~ s/\s+/%/g;
2247         push @query_params, "%$title%";
2248     }
2249
2250     if ( $author ) {
2251         $query .= " AND biblio.author LIKE ? ";
2252         push @query_params, "%$author%";
2253     }
2254
2255     if ( $isbn ) {
2256         $query .= " AND biblioitems.isbn LIKE ? ";
2257         push @query_params, "%$isbn%";
2258     }
2259     if ( $ean ) {
2260         $query .= " AND biblioitems.ean = ? ";
2261         push @query_params, "$ean";
2262     }
2263     if ( $name ) {
2264         $query .= " AND aqbooksellers.name LIKE ? ";
2265         push @query_params, "%$name%";
2266     }
2267
2268     if ( $budget ) {
2269         $query .= " AND aqbudgets.budget_id = ? ";
2270         push @query_params, "$budget";
2271     }
2272
2273     if ( $from_placed_on ) {
2274         $query .= " AND creationdate >= ? ";
2275         push @query_params, $from_placed_on;
2276     }
2277
2278     if ( $to_placed_on ) {
2279         $query .= " AND creationdate <= ? ";
2280         push @query_params, $to_placed_on;
2281     }
2282
2283     if ( defined $orderstatus and $orderstatus ne '') {
2284         $query .= " AND aqorders.orderstatus = ? ";
2285         push @query_params, "$orderstatus";
2286     }
2287
2288     if ($basket) {
2289         if ($basket =~ m/^\d+$/) {
2290             $query .= " AND aqorders.basketno = ? ";
2291             push @query_params, $basket;
2292         } else {
2293             $query .= " AND aqbasket.basketname LIKE ? ";
2294             push @query_params, "%$basket%";
2295         }
2296     }
2297
2298     if ($booksellerinvoicenumber) {
2299         $query .= " AND aqinvoices.invoicenumber LIKE ? ";
2300         push @query_params, "%$booksellerinvoicenumber%";
2301     }
2302
2303     if ($basketgroupname) {
2304         $query .= " AND aqbasketgroups.name LIKE ? ";
2305         push @query_params, "%$basketgroupname%";
2306     }
2307
2308     if ( C4::Context->preference("IndependentBranches") ) {
2309         my $userenv = C4::Context->userenv;
2310         if ( $userenv && ($userenv->{flags} || 0) != 1 ) {
2311             $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
2312             push @query_params, $userenv->{branch};
2313         }
2314     }
2315     $query .= " ORDER BY id";
2316     my $sth = $dbh->prepare($query);
2317     $sth->execute( @query_params );
2318     my $cnt = 1;
2319     while ( my $line = $sth->fetchrow_hashref ) {
2320         $line->{count} = $cnt++;
2321         $line->{toggle} = 1 if $cnt % 2;
2322         push @order_loop, $line;
2323         $total_qty         += ( $line->{quantity} ) ? $line->{quantity} : 0;
2324         $total_qtyreceived += ( $line->{quantityreceived} ) ? $line->{quantityreceived} : 0;
2325         $total_price       += ( $line->{quantity} and $line->{ecost} ) ? $line->{quantity} * $line->{ecost} : 0;
2326     }
2327     return \@order_loop, $total_qty, $total_price, $total_qtyreceived;
2328 }
2329
2330 =head2 GetRecentAcqui
2331
2332   $results = GetRecentAcqui($days);
2333
2334 C<$results> is a ref to a table which containts hashref
2335
2336 =cut
2337
2338 sub GetRecentAcqui {
2339     my $limit  = shift;
2340     my $dbh    = C4::Context->dbh;
2341     my $query = "
2342         SELECT *
2343         FROM   biblio
2344         ORDER BY timestamp DESC
2345         LIMIT  0,".$limit;
2346
2347     my $sth = $dbh->prepare($query);
2348     $sth->execute;
2349     my $results = $sth->fetchall_arrayref({});
2350     return $results;
2351 }
2352
2353 =head3 GetContracts
2354
2355   $contractlist = &GetContracts($booksellerid, $activeonly);
2356
2357 Looks up the contracts that belong to a bookseller
2358
2359 Returns a list of contracts
2360
2361 =over
2362
2363 =item C<$booksellerid> is the "id" field in the "aqbooksellers" table.
2364
2365 =item C<$activeonly> if exists get only contracts that are still active.
2366
2367 =back
2368
2369 =cut
2370
2371 sub GetContracts {
2372     my ( $booksellerid, $activeonly ) = @_;
2373     my $dbh = C4::Context->dbh;
2374     my $query;
2375     if (! $activeonly) {
2376         $query = "
2377             SELECT *
2378             FROM   aqcontract
2379             WHERE  booksellerid=?
2380         ";
2381     } else {
2382         $query = "SELECT *
2383             FROM aqcontract
2384             WHERE booksellerid=?
2385                 AND contractenddate >= CURDATE( )";
2386     }
2387     my $sth = $dbh->prepare($query);
2388     $sth->execute( $booksellerid );
2389     my @results;
2390     while (my $data = $sth->fetchrow_hashref ) {
2391         push(@results, $data);
2392     }
2393     $sth->finish;
2394     return @results;
2395 }
2396
2397 #------------------------------------------------------------#
2398
2399 =head3 GetContract
2400
2401   $contract = &GetContract($contractID);
2402
2403 Looks up the contract that has PRIMKEY (contractnumber) value $contractID
2404
2405 Returns a contract
2406
2407 =cut
2408
2409 sub GetContract {
2410     my ( $contractno ) = @_;
2411     my $dbh = C4::Context->dbh;
2412     my $query = "
2413         SELECT *
2414         FROM   aqcontract
2415         WHERE  contractnumber=?
2416         ";
2417
2418     my $sth = $dbh->prepare($query);
2419     $sth->execute( $contractno );
2420     my $result = $sth->fetchrow_hashref;
2421     return $result;
2422 }
2423
2424 =head3 AddClaim
2425
2426 =over
2427
2428 &AddClaim($ordernumber);
2429
2430 Add a claim for an order
2431
2432 =back
2433
2434 =cut
2435
2436 sub AddClaim {
2437     my ($ordernumber) = @_;
2438     my $dbh          = C4::Context->dbh;
2439     my $query        = "
2440         UPDATE aqorders SET
2441             claims_count = claims_count + 1,
2442             claimed_date = CURDATE()
2443         WHERE ordernumber = ?
2444         ";
2445     my $sth = $dbh->prepare($query);
2446     $sth->execute($ordernumber);
2447 }
2448
2449 =head3 GetInvoices
2450
2451     my @invoices = GetInvoices(
2452         invoicenumber => $invoicenumber,
2453         suppliername => $suppliername,
2454         shipmentdatefrom => $shipmentdatefrom, # ISO format
2455         shipmentdateto => $shipmentdateto, # ISO format
2456         billingdatefrom => $billingdatefrom, # ISO format
2457         billingdateto => $billingdateto, # ISO format
2458         isbneanissn => $isbn_or_ean_or_issn,
2459         title => $title,
2460         author => $author,
2461         publisher => $publisher,
2462         publicationyear => $publicationyear,
2463         branchcode => $branchcode,
2464         order_by => $order_by
2465     );
2466
2467 Return a list of invoices that match all given criteria.
2468
2469 $order_by is "column_name (asc|desc)", where column_name is any of
2470 'invoicenumber', 'booksellerid', 'shipmentdate', 'billingdate', 'closedate',
2471 'shipmentcost', 'shipmentcost_budgetid'.
2472
2473 asc is the default if omitted
2474
2475 =cut
2476
2477 sub GetInvoices {
2478     my %args = @_;
2479
2480     my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2481         closedate shipmentcost shipmentcost_budgetid);
2482
2483     my $dbh = C4::Context->dbh;
2484     my $query = qq{
2485         SELECT aqinvoices.*, aqbooksellers.name AS suppliername,
2486           COUNT(
2487             DISTINCT IF(
2488               aqorders.datereceived IS NOT NULL,
2489               aqorders.biblionumber,
2490               NULL
2491             )
2492           ) AS receivedbiblios,
2493           SUM(aqorders.quantityreceived) AS receiveditems
2494         FROM aqinvoices
2495           LEFT JOIN aqbooksellers ON aqbooksellers.id = aqinvoices.booksellerid
2496           LEFT JOIN aqorders ON aqorders.invoiceid = aqinvoices.invoiceid
2497           LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
2498           LEFT JOIN biblioitems ON biblio.biblionumber = biblioitems.biblionumber
2499           LEFT JOIN subscription ON biblio.biblionumber = subscription.biblionumber
2500     };
2501
2502     my @bind_args;
2503     my @bind_strs;
2504     if($args{supplierid}) {
2505         push @bind_strs, " aqinvoices.booksellerid = ? ";
2506         push @bind_args, $args{supplierid};
2507     }
2508     if($args{invoicenumber}) {
2509         push @bind_strs, " aqinvoices.invoicenumber LIKE ? ";
2510         push @bind_args, "%$args{invoicenumber}%";
2511     }
2512     if($args{suppliername}) {
2513         push @bind_strs, " aqbooksellers.name LIKE ? ";
2514         push @bind_args, "%$args{suppliername}%";
2515     }
2516     if($args{shipmentdatefrom}) {
2517         push @bind_strs, " aqinvoices.shipementdate >= ? ";
2518         push @bind_args, $args{shipmentdatefrom};
2519     }
2520     if($args{shipmentdateto}) {
2521         push @bind_strs, " aqinvoices.shipementdate <= ? ";
2522         push @bind_args, $args{shipmentdateto};
2523     }
2524     if($args{billingdatefrom}) {
2525         push @bind_strs, " aqinvoices.billingdate >= ? ";
2526         push @bind_args, $args{billingdatefrom};
2527     }
2528     if($args{billingdateto}) {
2529         push @bind_strs, " aqinvoices.billingdate <= ? ";
2530         push @bind_args, $args{billingdateto};
2531     }
2532     if($args{isbneanissn}) {
2533         push @bind_strs, " (biblioitems.isbn LIKE ? OR biblioitems.ean LIKE ? OR biblioitems.issn LIKE ? ) ";
2534         push @bind_args, $args{isbneanissn}, $args{isbneanissn}, $args{isbneanissn};
2535     }
2536     if($args{title}) {
2537         push @bind_strs, " biblio.title LIKE ? ";
2538         push @bind_args, $args{title};
2539     }
2540     if($args{author}) {
2541         push @bind_strs, " biblio.author LIKE ? ";
2542         push @bind_args, $args{author};
2543     }
2544     if($args{publisher}) {
2545         push @bind_strs, " biblioitems.publishercode LIKE ? ";
2546         push @bind_args, $args{publisher};
2547     }
2548     if($args{publicationyear}) {
2549         push @bind_strs, " biblioitems.publicationyear = ? ";
2550         push @bind_args, $args{publicationyear};
2551     }
2552     if($args{branchcode}) {
2553         push @bind_strs, " aqorders.branchcode = ? ";
2554         push @bind_args, $args{branchcode};
2555     }
2556
2557     $query .= " WHERE " . join(" AND ", @bind_strs) if @bind_strs;
2558     $query .= " GROUP BY aqinvoices.invoiceid ";
2559
2560     if($args{order_by}) {
2561         my ($column, $direction) = split / /, $args{order_by};
2562         if(grep /^$column$/, @columns) {
2563             $direction ||= 'ASC';
2564             $query .= " ORDER BY $column $direction";
2565         }
2566     }
2567
2568     my $sth = $dbh->prepare($query);
2569     $sth->execute(@bind_args);
2570
2571     my $results = $sth->fetchall_arrayref({});
2572     return @$results;
2573 }
2574
2575 =head3 GetInvoice
2576
2577     my $invoice = GetInvoice($invoiceid);
2578
2579 Get informations about invoice with given $invoiceid
2580
2581 Return a hash filled with aqinvoices.* fields
2582
2583 =cut
2584
2585 sub GetInvoice {
2586     my ($invoiceid) = @_;
2587     my $invoice;
2588
2589     return unless $invoiceid;
2590
2591     my $dbh = C4::Context->dbh;
2592     my $query = qq{
2593         SELECT *
2594         FROM aqinvoices
2595         WHERE invoiceid = ?
2596     };
2597     my $sth = $dbh->prepare($query);
2598     $sth->execute($invoiceid);
2599
2600     $invoice = $sth->fetchrow_hashref;
2601     return $invoice;
2602 }
2603
2604 =head3 GetInvoiceDetails
2605
2606     my $invoice = GetInvoiceDetails($invoiceid)
2607
2608 Return informations about an invoice + the list of related order lines
2609
2610 Orders informations are in $invoice->{orders} (array ref)
2611
2612 =cut
2613
2614 sub GetInvoiceDetails {
2615     my ($invoiceid) = @_;
2616
2617     if ( !defined $invoiceid ) {
2618         carp 'GetInvoiceDetails called without an invoiceid';
2619         return;
2620     }
2621
2622     my $dbh = C4::Context->dbh;
2623     my $query = q{
2624         SELECT aqinvoices.*, aqbooksellers.name AS suppliername
2625         FROM aqinvoices
2626           LEFT JOIN aqbooksellers ON aqinvoices.booksellerid = aqbooksellers.id
2627         WHERE invoiceid = ?
2628     };
2629     my $sth = $dbh->prepare($query);
2630     $sth->execute($invoiceid);
2631
2632     my $invoice = $sth->fetchrow_hashref;
2633
2634     $query = q{
2635         SELECT aqorders.*, biblio.*, aqbasket.basketname
2636         FROM aqorders
2637           LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
2638           LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
2639         WHERE invoiceid = ?
2640     };
2641     $sth = $dbh->prepare($query);
2642     $sth->execute($invoiceid);
2643     $invoice->{orders} = $sth->fetchall_arrayref({});
2644     $invoice->{orders} ||= []; # force an empty arrayref if fetchall_arrayref fails
2645
2646     return $invoice;
2647 }
2648
2649 =head3 AddInvoice
2650
2651     my $invoiceid = AddInvoice(
2652         invoicenumber => $invoicenumber,
2653         booksellerid => $booksellerid,
2654         shipmentdate => $shipmentdate,
2655         billingdate => $billingdate,
2656         closedate => $closedate,
2657         shipmentcost => $shipmentcost,
2658         shipmentcost_budgetid => $shipmentcost_budgetid
2659     );
2660
2661 Create a new invoice and return its id or undef if it fails.
2662
2663 =cut
2664
2665 sub AddInvoice {
2666     my %invoice = @_;
2667
2668     return unless(%invoice and $invoice{invoicenumber});
2669
2670     my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2671         closedate shipmentcost shipmentcost_budgetid);
2672
2673     my @set_strs;
2674     my @set_args;
2675     foreach my $key (keys %invoice) {
2676         if(0 < grep(/^$key$/, @columns)) {
2677             push @set_strs, "$key = ?";
2678             push @set_args, ($invoice{$key} || undef);
2679         }
2680     }
2681
2682     my $rv;
2683     if(@set_args > 0) {
2684         my $dbh = C4::Context->dbh;
2685         my $query = "INSERT INTO aqinvoices SET ";
2686         $query .= join (",", @set_strs);
2687         my $sth = $dbh->prepare($query);
2688         $rv = $sth->execute(@set_args);
2689         if($rv) {
2690             $rv = $dbh->last_insert_id(undef, undef, 'aqinvoices', undef);
2691         }
2692     }
2693     return $rv;
2694 }
2695
2696 =head3 ModInvoice
2697
2698     ModInvoice(
2699         invoiceid => $invoiceid,    # Mandatory
2700         invoicenumber => $invoicenumber,
2701         booksellerid => $booksellerid,
2702         shipmentdate => $shipmentdate,
2703         billingdate => $billingdate,
2704         closedate => $closedate,
2705         shipmentcost => $shipmentcost,
2706         shipmentcost_budgetid => $shipmentcost_budgetid
2707     );
2708
2709 Modify an invoice, invoiceid is mandatory.
2710
2711 Return undef if it fails.
2712
2713 =cut
2714
2715 sub ModInvoice {
2716     my %invoice = @_;
2717
2718     return unless(%invoice and $invoice{invoiceid});
2719
2720     my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2721         closedate shipmentcost shipmentcost_budgetid);
2722
2723     my @set_strs;
2724     my @set_args;
2725     foreach my $key (keys %invoice) {
2726         if(0 < grep(/^$key$/, @columns)) {
2727             push @set_strs, "$key = ?";
2728             push @set_args, ($invoice{$key} || undef);
2729         }
2730     }
2731
2732     my $dbh = C4::Context->dbh;
2733     my $query = "UPDATE aqinvoices SET ";
2734     $query .= join(",", @set_strs);
2735     $query .= " WHERE invoiceid = ?";
2736
2737     my $sth = $dbh->prepare($query);
2738     $sth->execute(@set_args, $invoice{invoiceid});
2739 }
2740
2741 =head3 CloseInvoice
2742
2743     CloseInvoice($invoiceid);
2744
2745 Close an invoice.
2746
2747 Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => undef);
2748
2749 =cut
2750
2751 sub CloseInvoice {
2752     my ($invoiceid) = @_;
2753
2754     return unless $invoiceid;
2755
2756     my $dbh = C4::Context->dbh;
2757     my $query = qq{
2758         UPDATE aqinvoices
2759         SET closedate = CAST(NOW() AS DATE)
2760         WHERE invoiceid = ?
2761     };
2762     my $sth = $dbh->prepare($query);
2763     $sth->execute($invoiceid);
2764 }
2765
2766 =head3 ReopenInvoice
2767
2768     ReopenInvoice($invoiceid);
2769
2770 Reopen an invoice
2771
2772 Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => C4::Dates->new()->output('iso'))
2773
2774 =cut
2775
2776 sub ReopenInvoice {
2777     my ($invoiceid) = @_;
2778
2779     return unless $invoiceid;
2780
2781     my $dbh = C4::Context->dbh;
2782     my $query = qq{
2783         UPDATE aqinvoices
2784         SET closedate = NULL
2785         WHERE invoiceid = ?
2786     };
2787     my $sth = $dbh->prepare($query);
2788     $sth->execute($invoiceid);
2789 }
2790
2791 =head3 DelInvoice
2792
2793     DelInvoice($invoiceid);
2794
2795 Delete an invoice if there are no items attached to it.
2796
2797 =cut
2798
2799 sub DelInvoice {
2800     my ($invoiceid) = @_;
2801
2802     return unless $invoiceid;
2803
2804     my $dbh   = C4::Context->dbh;
2805     my $query = qq{
2806         SELECT COUNT(*)
2807         FROM aqorders
2808         WHERE invoiceid = ?
2809     };
2810     my $sth = $dbh->prepare($query);
2811     $sth->execute($invoiceid);
2812     my $res = $sth->fetchrow_arrayref;
2813     if ( $res && $res->[0] == 0 ) {
2814         $query = qq{
2815             DELETE FROM aqinvoices
2816             WHERE invoiceid = ?
2817         };
2818         my $sth = $dbh->prepare($query);
2819         return ( $sth->execute($invoiceid) > 0 );
2820     }
2821     return;
2822 }
2823
2824 =head3 MergeInvoices
2825
2826     MergeInvoices($invoiceid, \@sourceids);
2827
2828 Merge the invoices identified by the IDs in \@sourceids into
2829 the invoice identified by $invoiceid.
2830
2831 =cut
2832
2833 sub MergeInvoices {
2834     my ($invoiceid, $sourceids) = @_;
2835
2836     return unless $invoiceid;
2837     foreach my $sourceid (@$sourceids) {
2838         next if $sourceid == $invoiceid;
2839         my $source = GetInvoiceDetails($sourceid);
2840         foreach my $order (@{$source->{'orders'}}) {
2841             $order->{'invoiceid'} = $invoiceid;
2842             ModOrder($order);
2843         }
2844         DelInvoice($source->{'invoiceid'});
2845     }
2846     return;
2847 }
2848
2849 =head3 GetBiblioCountByBasketno
2850
2851 $biblio_count = &GetBiblioCountByBasketno($basketno);
2852
2853 Looks up the biblio's count that has basketno value $basketno
2854
2855 Returns a quantity
2856
2857 =cut
2858
2859 sub GetBiblioCountByBasketno {
2860     my ($basketno) = @_;
2861     my $dbh          = C4::Context->dbh;
2862     my $query        = "
2863         SELECT COUNT( DISTINCT( biblionumber ) )
2864         FROM   aqorders
2865         WHERE  basketno = ?
2866             AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
2867         ";
2868
2869     my $sth = $dbh->prepare($query);
2870     $sth->execute($basketno);
2871     return $sth->fetchrow;
2872 }
2873
2874 1;
2875 __END__
2876
2877 =head1 AUTHOR
2878
2879 Koha Development Team <http://koha-community.org/>
2880
2881 =cut