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