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