Bug 5347: Adds columns claims_count and claimed_date in aqorders
[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
33 use Time::localtime;
34 use HTML::Entities;
35
36 use vars qw($VERSION @ISA @EXPORT);
37
38 BEGIN {
39     # set the version for version checking
40     $VERSION = 3.01;
41     require Exporter;
42     @ISA    = qw(Exporter);
43     @EXPORT = qw(
44         &GetBasket &NewBasket &CloseBasket &DelBasket &ModBasket
45         &GetBasketAsCSV
46         &GetBasketsByBookseller &GetBasketsByBasketgroup
47
48         &ModBasketHeader
49
50         &ModBasketgroup &NewBasketgroup &DelBasketgroup &GetBasketgroup &CloseBasketgroup
51         &GetBasketgroups &ReOpenBasketgroup
52
53         &NewOrder &DelOrder &ModOrder &GetPendingOrders &GetOrder &GetOrders
54         &GetOrderNumber &GetLateOrders &GetOrderFromItemnumber
55         &SearchOrder &GetHistory &GetRecentAcqui
56         &ModReceiveOrder &ModOrderBiblioitemNumber
57         &GetCancelledOrders
58
59         &NewOrderItem &ModOrderItem
60
61         &GetParcels &GetParcel
62         &GetContracts &GetContract
63
64         &GetItemnumbersFromOrder
65
66         &AddClaim
67     );
68 }
69
70
71
72
73
74 sub GetOrderFromItemnumber {
75     my ($itemnumber) = @_;
76     my $dbh          = C4::Context->dbh;
77     my $query        = qq|
78
79     SELECT  * from aqorders    LEFT JOIN aqorders_items
80     ON (     aqorders.ordernumber = aqorders_items.ordernumber   )
81     WHERE itemnumber = ?  |;
82
83     my $sth = $dbh->prepare($query);
84
85 #    $sth->trace(3);
86
87     $sth->execute($itemnumber);
88
89     my $order = $sth->fetchrow_hashref;
90     return ( $order  );
91
92 }
93
94 # Returns the itemnumber(s) associated with the ordernumber given in parameter
95 sub GetItemnumbersFromOrder {
96     my ($ordernumber) = @_;
97     my $dbh          = C4::Context->dbh;
98     my $query        = "SELECT itemnumber FROM aqorders_items WHERE ordernumber=?";
99     my $sth = $dbh->prepare($query);
100     $sth->execute($ordernumber);
101     my @tab;
102
103     while (my $order = $sth->fetchrow_hashref) {
104     push @tab, $order->{'itemnumber'};
105     }
106
107     return @tab;
108
109 }
110
111
112
113
114
115
116 =head1 NAME
117
118 C4::Acquisition - Koha functions for dealing with orders and acquisitions
119
120 =head1 SYNOPSIS
121
122 use C4::Acquisition;
123
124 =head1 DESCRIPTION
125
126 The functions in this module deal with acquisitions, managing book
127 orders, basket and parcels.
128
129 =head1 FUNCTIONS
130
131 =head2 FUNCTIONS ABOUT BASKETS
132
133 =head3 GetBasket
134
135   $aqbasket = &GetBasket($basketnumber);
136
137 get all basket informations in aqbasket for a given basket
138
139 B<returns:> informations for a given basket returned as a hashref.
140
141 =cut
142
143 sub GetBasket {
144     my ($basketno) = @_;
145     my $dbh        = C4::Context->dbh;
146     my $query = "
147         SELECT  aqbasket.*,
148                 concat( b.firstname,' ',b.surname) AS authorisedbyname,
149                 b.branchcode AS branch
150         FROM    aqbasket
151         LEFT JOIN borrowers b ON aqbasket.authorisedby=b.borrowernumber
152         WHERE basketno=?
153     ";
154     my $sth=$dbh->prepare($query);
155     $sth->execute($basketno);
156     my $basket = $sth->fetchrow_hashref;
157     return ( $basket );
158 }
159
160 #------------------------------------------------------------#
161
162 =head3 NewBasket
163
164   $basket = &NewBasket( $booksellerid, $authorizedby, $basketname, 
165       $basketnote, $basketbooksellernote, $basketcontractnumber );
166
167 Create a new basket in aqbasket table
168
169 =over
170
171 =item C<$booksellerid> is a foreign key in the aqbasket table
172
173 =item C<$authorizedby> is the username of who created the basket
174
175 =back
176
177 The other parameters are optional, see ModBasketHeader for more info on them.
178
179 =cut
180
181 # FIXME : this function seems to be unused.
182
183 sub NewBasket {
184     my ( $booksellerid, $authorisedby, $basketname, $basketnote, $basketbooksellernote, $basketcontractnumber ) = @_;
185     my $dbh = C4::Context->dbh;
186     my $query = "
187         INSERT INTO aqbasket
188                 (creationdate,booksellerid,authorisedby)
189         VALUES  (now(),'$booksellerid','$authorisedby')
190     ";
191     my $sth =
192     $dbh->do($query);
193 #find & return basketno MYSQL dependant, but $dbh->last_insert_id always returns null :-(
194     my $basket = $dbh->{'mysql_insertid'};
195     ModBasketHeader($basket, $basketname || '', $basketnote || '', $basketbooksellernote || '', $basketcontractnumber || undef);
196     return $basket;
197 }
198
199 #------------------------------------------------------------#
200
201 =head3 CloseBasket
202
203   &CloseBasket($basketno);
204
205 close a basket (becomes unmodifiable,except for recieves)
206
207 =cut
208
209 sub CloseBasket {
210     my ($basketno) = @_;
211     my $dbh        = C4::Context->dbh;
212     my $query = "
213         UPDATE aqbasket
214         SET    closedate=now()
215         WHERE  basketno=?
216     ";
217     my $sth = $dbh->prepare($query);
218     $sth->execute($basketno);
219 }
220
221 #------------------------------------------------------------#
222
223 =head3 GetBasketAsCSV
224
225   &GetBasketAsCSV($basketno);
226
227 Export a basket as CSV
228
229 =cut
230
231 sub GetBasketAsCSV {
232     my ($basketno) = @_;
233     my $basket = GetBasket($basketno);
234     my @orders = GetOrders($basketno);
235     my $contract = GetContract($basket->{'contractnumber'});
236     my $csv = Text::CSV->new();
237     my $output; 
238
239     # TODO: Translate headers
240     my @headers = qw(contractname ordernumber entrydate isbn author title publishercode collectiontitle notes quantity rrp);
241
242     $csv->combine(@headers);                                                                                                        
243     $output = $csv->string() . "\n";    
244
245     my @rows;
246     foreach my $order (@orders) {
247         my @cols;
248         # newlines are not valid characters for Text::CSV combine()
249         $order->{'notes'} =~ s/[\r\n]+//g;
250         push(@cols,
251                 $contract->{'contractname'},
252                 $order->{'ordernumber'},
253                 $order->{'entrydate'}, 
254                 $order->{'isbn'},
255                 $order->{'author'},
256                 $order->{'title'},
257                 $order->{'publishercode'},
258                 $order->{'collectiontitle'},
259                 $order->{'notes'},
260                 $order->{'quantity'},
261                 $order->{'rrp'},
262             );
263         push (@rows, \@cols);
264     }
265
266     foreach my $row (@rows) {
267         $csv->combine(@$row);                                                                                                                    
268         $output .= $csv->string() . "\n";    
269
270     }
271                                                                                                                                                       
272     return $output;             
273
274 }
275
276
277 =head3 CloseBasketgroup
278
279   &CloseBasketgroup($basketgroupno);
280
281 close a basketgroup
282
283 =cut
284
285 sub CloseBasketgroup {
286     my ($basketgroupno) = @_;
287     my $dbh        = C4::Context->dbh;
288     my $sth = $dbh->prepare("
289         UPDATE aqbasketgroups
290         SET    closed=1
291         WHERE  id=?
292     ");
293     $sth->execute($basketgroupno);
294 }
295
296 #------------------------------------------------------------#
297
298 =head3 ReOpenBaskergroup($basketgroupno)
299
300   &ReOpenBaskergroup($basketgroupno);
301
302 reopen a basketgroup
303
304 =cut
305
306 sub ReOpenBasketgroup {
307     my ($basketgroupno) = @_;
308     my $dbh        = C4::Context->dbh;
309     my $sth = $dbh->prepare("
310         UPDATE aqbasketgroups
311         SET    closed=0
312         WHERE  id=?
313     ");
314     $sth->execute($basketgroupno);
315 }
316
317 #------------------------------------------------------------#
318
319
320 =head3 DelBasket
321
322   &DelBasket($basketno);
323
324 Deletes the basket that has basketno field $basketno in the aqbasket table.
325
326 =over
327
328 =item C<$basketno> is the primary key of the basket in the aqbasket table.
329
330 =back
331
332 =cut
333
334 sub DelBasket {
335     my ( $basketno ) = @_;
336     my $query = "DELETE FROM aqbasket WHERE basketno=?";
337     my $dbh = C4::Context->dbh;
338     my $sth = $dbh->prepare($query);
339     $sth->execute($basketno);
340     $sth->finish;
341 }
342
343 #------------------------------------------------------------#
344
345 =head3 ModBasket
346
347   &ModBasket($basketinfo);
348
349 Modifies a basket, using a hashref $basketinfo for the relevant information, only $basketinfo->{'basketno'} is required.
350
351 =over
352
353 =item C<$basketno> is the primary key of the basket in the aqbasket table.
354
355 =back
356
357 =cut
358
359 sub ModBasket {
360     my $basketinfo = shift;
361     my $query = "UPDATE aqbasket SET ";
362     my @params;
363     foreach my $key (keys %$basketinfo){
364         if ($key ne 'basketno'){
365             $query .= "$key=?, ";
366             push(@params, $basketinfo->{$key} || undef );
367         }
368     }
369 # get rid of the "," at the end of $query
370     if (substr($query, length($query)-2) eq ', '){
371         chop($query);
372         chop($query);
373         $query .= ' ';
374     }
375     $query .= "WHERE basketno=?";
376     push(@params, $basketinfo->{'basketno'});
377     my $dbh = C4::Context->dbh;
378     my $sth = $dbh->prepare($query);
379     $sth->execute(@params);
380     $sth->finish;
381 }
382
383 #------------------------------------------------------------#
384
385 =head3 ModBasketHeader
386
387   &ModBasketHeader($basketno, $basketname, $note, $booksellernote, $contractnumber);
388
389 Modifies a basket's header.
390
391 =over
392
393 =item C<$basketno> is the "basketno" field in the "aqbasket" table;
394
395 =item C<$basketname> is the "basketname" field in the "aqbasket" table;
396
397 =item C<$note> is the "note" field in the "aqbasket" table;
398
399 =item C<$booksellernote> is the "booksellernote" field in the "aqbasket" table;
400
401 =item C<$contractnumber> is the "contractnumber" (foreign) key in the "aqbasket" table.
402
403 =back
404
405 =cut
406
407 sub ModBasketHeader {
408     my ($basketno, $basketname, $note, $booksellernote, $contractnumber) = @_;
409     my $query = "UPDATE aqbasket SET basketname=?, note=?, booksellernote=? WHERE basketno=?";
410     my $dbh = C4::Context->dbh;
411     my $sth = $dbh->prepare($query);
412     $sth->execute($basketname,$note,$booksellernote,$basketno);
413     if ( $contractnumber ) {
414         my $query2 ="UPDATE aqbasket SET contractnumber=? WHERE basketno=?";
415         my $sth2 = $dbh->prepare($query2);
416         $sth2->execute($contractnumber,$basketno);
417         $sth2->finish;
418     }
419     $sth->finish;
420 }
421
422 #------------------------------------------------------------#
423
424 =head3 GetBasketsByBookseller
425
426   @results = &GetBasketsByBookseller($booksellerid, $extra);
427
428 Returns a list of hashes of all the baskets that belong to bookseller 'booksellerid'.
429
430 =over
431
432 =item C<$booksellerid> is the 'id' field of the bookseller in the aqbooksellers table
433
434 =item C<$extra> is the extra sql parameters, can be
435
436  $extra->{groupby}: group baskets by column
437     ex. $extra->{groupby} = aqbasket.basketgroupid
438  $extra->{orderby}: order baskets by column
439  $extra->{limit}: limit number of results (can be helpful for pagination)
440
441 =back
442
443 =cut
444
445 sub GetBasketsByBookseller {
446     my ($booksellerid, $extra) = @_;
447     my $query = "SELECT * FROM aqbasket WHERE booksellerid=?";
448     if ($extra){
449         if ($extra->{groupby}) {
450             $query .= " GROUP by $extra->{groupby}";
451         }
452         if ($extra->{orderby}){
453             $query .= " ORDER by $extra->{orderby}";
454         }
455         if ($extra->{limit}){
456             $query .= " LIMIT $extra->{limit}";
457         }
458     }
459     my $dbh = C4::Context->dbh;
460     my $sth = $dbh->prepare($query);
461     $sth->execute($booksellerid);
462     my $results = $sth->fetchall_arrayref({});
463     $sth->finish;
464     return $results
465 }
466
467 #------------------------------------------------------------#
468
469 =head3 GetBasketsByBasketgroup
470
471   $baskets = &GetBasketsByBasketgroup($basketgroupid);
472
473 Returns a reference to all baskets that belong to basketgroup $basketgroupid.
474
475 =cut
476
477 sub GetBasketsByBasketgroup {
478     my $basketgroupid = shift;
479     my $query = "SELECT * FROM aqbasket
480                 LEFT JOIN aqcontract USING(contractnumber) WHERE basketgroupid=?";
481     my $dbh = C4::Context->dbh;
482     my $sth = $dbh->prepare($query);
483     $sth->execute($basketgroupid);
484     my $results = $sth->fetchall_arrayref({});
485     $sth->finish;
486     return $results
487 }
488
489 #------------------------------------------------------------#
490
491 =head3 NewBasketgroup
492
493   $basketgroupid = NewBasketgroup(\%hashref);
494
495 Adds a basketgroup to the aqbasketgroups table, and add the initial baskets to it.
496
497 $hashref->{'booksellerid'} is the 'id' field of the bookseller in the aqbooksellers table,
498
499 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
500
501 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
502
503 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
504
505 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
506
507 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
508
509 =cut
510
511 sub NewBasketgroup {
512     my $basketgroupinfo = shift;
513     die "booksellerid is required to create a basketgroup" unless $basketgroupinfo->{'booksellerid'};
514     my $query = "INSERT INTO aqbasketgroups (";
515     my @params;
516     foreach my $field ('name', 'deliveryplace', 'deliverycomment', 'closed') {
517         if ( $basketgroupinfo->{$field} ) {
518             $query .= "$field, ";
519             push(@params, $basketgroupinfo->{$field});
520         }
521     }
522     $query .= "booksellerid) VALUES (";
523     foreach (@params) {
524         $query .= "?, ";
525     }
526     $query .= "?)";
527     push(@params, $basketgroupinfo->{'booksellerid'});
528     my $dbh = C4::Context->dbh;
529     my $sth = $dbh->prepare($query);
530     $sth->execute(@params);
531     my $basketgroupid = $dbh->{'mysql_insertid'};
532     if( $basketgroupinfo->{'basketlist'} ) {
533         foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
534             my $query2 = "UPDATE aqbasket SET basketgroupid=? WHERE basketno=?";
535             my $sth2 = $dbh->prepare($query2);
536             $sth2->execute($basketgroupid, $basketno);
537         }
538     }
539     return $basketgroupid;
540 }
541
542 #------------------------------------------------------------#
543
544 =head3 ModBasketgroup
545
546   ModBasketgroup(\%hashref);
547
548 Modifies a basketgroup in the aqbasketgroups table, and add the baskets to it.
549
550 $hashref->{'id'} is the 'id' field of the basketgroup in the aqbasketgroup table, this parameter is mandatory,
551
552 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
553
554 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
555
556 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
557
558 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
559
560 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
561
562 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
563
564 =cut
565
566 sub ModBasketgroup {
567     my $basketgroupinfo = shift;
568     die "basketgroup id is required to edit a basketgroup" unless $basketgroupinfo->{'id'};
569     my $dbh = C4::Context->dbh;
570     my $query = "UPDATE aqbasketgroups SET ";
571     my @params;
572     foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
573         if ( defined $basketgroupinfo->{$field} ) {
574             $query .= "$field=?, ";
575             push(@params, $basketgroupinfo->{$field});
576         }
577     }
578     chop($query);
579     chop($query);
580     $query .= " WHERE id=?";
581     push(@params, $basketgroupinfo->{'id'});
582     my $sth = $dbh->prepare($query);
583     $sth->execute(@params);
584
585     $sth = $dbh->prepare('UPDATE aqbasket SET basketgroupid = NULL WHERE basketgroupid = ?');
586     $sth->execute($basketgroupinfo->{'id'});
587
588     if($basketgroupinfo->{'basketlist'} && @{$basketgroupinfo->{'basketlist'}}){
589         $sth = $dbh->prepare("UPDATE aqbasket SET basketgroupid=? WHERE basketno=?");
590         foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
591             $sth->execute($basketgroupinfo->{'id'}, $basketno);
592             $sth->finish;
593         }
594     }
595     $sth->finish;
596 }
597
598 #------------------------------------------------------------#
599
600 =head3 DelBasketgroup
601
602   DelBasketgroup($basketgroupid);
603
604 Deletes a basketgroup in the aqbasketgroups table, and removes the reference to it from the baskets,
605
606 =over
607
608 =item C<$basketgroupid> is the 'id' field of the basket in the aqbasketgroup table
609
610 =back
611
612 =cut
613
614 sub DelBasketgroup {
615     my $basketgroupid = shift;
616     die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
617     my $query = "DELETE FROM aqbasketgroups WHERE id=?";
618     my $dbh = C4::Context->dbh;
619     my $sth = $dbh->prepare($query);
620     $sth->execute($basketgroupid);
621     $sth->finish;
622 }
623
624 #------------------------------------------------------------#
625
626
627 =head2 FUNCTIONS ABOUT ORDERS
628
629 =head3 GetBasketgroup
630
631   $basketgroup = &GetBasketgroup($basketgroupid);
632
633 Returns a reference to the hash containing all infermation about the basketgroup.
634
635 =cut
636
637 sub GetBasketgroup {
638     my $basketgroupid = shift;
639     die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
640     my $query = "SELECT * FROM aqbasketgroups WHERE id=?";
641     my $dbh = C4::Context->dbh;
642     my $sth = $dbh->prepare($query);
643     $sth->execute($basketgroupid);
644     my $result = $sth->fetchrow_hashref;
645     $sth->finish;
646     return $result
647 }
648
649 #------------------------------------------------------------#
650
651 =head3 GetBasketgroups
652
653   $basketgroups = &GetBasketgroups($booksellerid);
654
655 Returns a reference to the array of all the basketgroups of bookseller $booksellerid.
656
657 =cut
658
659 sub GetBasketgroups {
660     my $booksellerid = shift;
661     die "bookseller id is required to edit a basketgroup" unless $booksellerid;
662     my $query = "SELECT * FROM aqbasketgroups WHERE booksellerid=? ORDER BY `id` DESC";
663     my $dbh = C4::Context->dbh;
664     my $sth = $dbh->prepare($query);
665     $sth->execute($booksellerid);
666     my $results = $sth->fetchall_arrayref({});
667     $sth->finish;
668     return $results
669 }
670
671 #------------------------------------------------------------#
672
673 =head2 FUNCTIONS ABOUT ORDERS
674
675 =cut
676
677 #------------------------------------------------------------#
678
679 =head3 GetPendingOrders
680
681   $orders = &GetPendingOrders($booksellerid, $grouped, $owner);
682
683 Finds pending orders from the bookseller with the given ID. Ignores
684 completed and cancelled orders.
685
686 C<$booksellerid> contains the bookseller identifier
687 C<$grouped> contains 0 or 1. 0 means returns the list, 1 means return the total
688 C<$owner> contains 0 or 1. 0 means any owner. 1 means only the list of orders entered by the user itself.
689
690 C<$orders> is a reference-to-array; each element is a
691 reference-to-hash with the following fields:
692 C<$grouped> is a boolean that, if set to 1 will group all order lines of the same basket
693 in a single result line
694
695 =over
696
697 =item C<authorizedby>
698
699 =item C<entrydate>
700
701 =item C<basketno>
702
703 =back
704
705 These give the value of the corresponding field in the aqorders table
706 of the Koha database.
707
708 Results are ordered from most to least recent.
709
710 =cut
711
712 sub GetPendingOrders {
713     my ($supplierid,$grouped,$owner,$basketno) = @_;
714     my $dbh = C4::Context->dbh;
715     my $strsth = "
716         SELECT    ".($grouped?"count(*),":"")."aqbasket.basketno,
717                     surname,firstname,aqorders.*,biblio.*,biblioitems.isbn,
718                     aqbasket.closedate, aqbasket.creationdate, aqbasket.basketname
719         FROM      aqorders
720         LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
721         LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
722         LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
723         LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
724         WHERE booksellerid=?
725             AND (quantity > quantityreceived OR quantityreceived is NULL)
726             AND datecancellationprinted IS NULL";
727     my @query_params = ( $supplierid );
728     my $userenv = C4::Context->userenv;
729     if ( C4::Context->preference("IndependantBranches") ) {
730         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
731             $strsth .= " and (borrowers.branchcode = ?
732                         or borrowers.branchcode  = '')";
733             push @query_params, $userenv->{branch};
734         }
735     }
736     if ($owner) {
737         $strsth .= " AND aqbasket.authorisedby=? ";
738         push @query_params, $userenv->{'number'};
739     }
740     if ($basketno) {
741         $strsth .= " AND aqbasket.basketno=? ";
742         push @query_params, $basketno;
743     }
744     $strsth .= " group by aqbasket.basketno" if $grouped;
745     $strsth .= " order by aqbasket.basketno";
746
747     my $sth = $dbh->prepare($strsth);
748     $sth->execute( @query_params );
749     my $results = $sth->fetchall_arrayref({});
750     $sth->finish;
751     return $results;
752 }
753
754 #------------------------------------------------------------#
755
756 =head3 GetOrders
757
758   @orders = &GetOrders($basketnumber, $orderby);
759
760 Looks up the pending (non-cancelled) orders with the given basket
761 number. If C<$booksellerID> is non-empty, only orders from that seller
762 are returned.
763
764 return :
765 C<&basket> returns a two-element array. C<@orders> is an array of
766 references-to-hash, whose keys are the fields from the aqorders,
767 biblio, and biblioitems tables in the Koha database.
768
769 =cut
770
771 sub GetOrders {
772     my ( $basketno, $orderby ) = @_;
773     my $dbh   = C4::Context->dbh;
774     my $query  ="
775         SELECT biblio.*,biblioitems.*,
776                 aqorders.*,
777                 aqbudgets.*,
778                 biblio.title
779         FROM    aqorders
780             LEFT JOIN aqbudgets        ON aqbudgets.budget_id = aqorders.budget_id
781             LEFT JOIN biblio           ON biblio.biblionumber = aqorders.biblionumber
782             LEFT JOIN biblioitems      ON biblioitems.biblionumber =biblio.biblionumber
783         WHERE   basketno=?
784             AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
785     ";
786
787     $orderby = "biblioitems.publishercode,biblio.title" unless $orderby;
788     $query .= " ORDER BY $orderby";
789     my $sth = $dbh->prepare($query);
790     $sth->execute($basketno);
791     my $results = $sth->fetchall_arrayref({});
792     $sth->finish;
793     return @$results;
794 }
795
796 #------------------------------------------------------------#
797
798 =head3 GetOrderNumber
799
800   $ordernumber = &GetOrderNumber($biblioitemnumber, $biblionumber);
801
802 Looks up the ordernumber with the given biblionumber and biblioitemnumber.
803
804 Returns the number of this order.
805
806 =over
807
808 =item C<$ordernumber> is the order number.
809
810 =back
811
812 =cut
813
814 sub GetOrderNumber {
815     my ( $biblionumber,$biblioitemnumber ) = @_;
816     my $dbh = C4::Context->dbh;
817     my $query = "
818         SELECT ordernumber
819         FROM   aqorders
820         WHERE  biblionumber=?
821         AND    biblioitemnumber=?
822     ";
823     my $sth = $dbh->prepare($query);
824     $sth->execute( $biblionumber, $biblioitemnumber );
825
826     return $sth->fetchrow;
827 }
828
829 #------------------------------------------------------------#
830
831 =head3 GetOrder
832
833   $order = &GetOrder($ordernumber);
834
835 Looks up an order by order number.
836
837 Returns a reference-to-hash describing the order. The keys of
838 C<$order> are fields from the biblio, biblioitems, aqorders tables of the Koha database.
839
840 =cut
841
842 sub GetOrder {
843     my ($ordernumber) = @_;
844     my $dbh      = C4::Context->dbh;
845     my $query = "
846         SELECT biblioitems.*, biblio.*, aqorders.*
847         FROM   aqorders
848         LEFT JOIN biblio on           biblio.biblionumber=aqorders.biblionumber
849         LEFT JOIN biblioitems on       biblioitems.biblionumber=aqorders.biblionumber
850         WHERE aqorders.ordernumber=?
851
852     ";
853     my $sth= $dbh->prepare($query);
854     $sth->execute($ordernumber);
855     my $data = $sth->fetchrow_hashref;
856     $sth->finish;
857     return $data;
858 }
859
860 #------------------------------------------------------------#
861
862 =head3 NewOrder
863
864   &NewOrder(\%hashref);
865
866 Adds a new order to the database. Any argument that isn't described
867 below is the new value of the field with the same name in the aqorders
868 table of the Koha database.
869
870 =over
871
872 =item $hashref->{'basketno'} is the basketno foreign key in aqorders, it is mandatory
873
874 =item $hashref->{'ordernumber'} is a "minimum order number."
875
876 =item $hashref->{'budgetdate'} is effectively ignored.
877 If it's undef (anything false) or the string 'now', the current day is used.
878 Else, the upcoming July 1st is used.
879
880 =item $hashref->{'subscription'} may be either "yes", or anything else for "no".
881
882 =item $hashref->{'uncertainprice'} may be 0 for "the price is known" or 1 for "the price is uncertain"
883
884 =item defaults entrydate to Now
885
886 The following keys are used: "biblionumber", "title", "basketno", "quantity", "notes", "biblioitemnumber", "rrp", "ecost", "gst", "unitprice", "subscription", "sort1", "sort2", "booksellerinvoicenumber", "listprice", "budgetdate", "purchaseordernumber", "branchcode", "booksellerinvoicenumber", "bookfundid".
887
888 =back
889
890 =cut
891
892 sub NewOrder {
893     my $orderinfo = shift;
894 #### ------------------------------
895     my $dbh = C4::Context->dbh;
896     my @params;
897
898
899     # if these parameters are missing, we can't continue
900     for my $key (qw/basketno quantity biblionumber budget_id/) {
901         croak "Mandatory parameter $key missing" unless $orderinfo->{$key};
902     }
903
904     if ( defined $orderinfo->{subscription} && $orderinfo->{'subscription'} eq 'yes' ) {
905         $orderinfo->{'subscription'} = 1;
906     } else {
907         $orderinfo->{'subscription'} = 0;
908     }
909     $orderinfo->{'entrydate'} ||= C4::Dates->new()->output("iso");
910     if (!$orderinfo->{quantityreceived}) {
911         $orderinfo->{quantityreceived} = 0;
912     }
913
914     my $ordernumber=InsertInTable("aqorders",$orderinfo);
915     return ( $orderinfo->{'basketno'}, $ordernumber );
916 }
917
918
919
920 #------------------------------------------------------------#
921
922 =head3 NewOrderItem
923
924   &NewOrderItem();
925
926 =cut
927
928 sub NewOrderItem {
929     #my ($biblioitemnumber,$ordernumber, $biblionumber) = @_;
930     my ($itemnumber, $ordernumber)  = @_;
931     my $dbh = C4::Context->dbh;
932     my $query = qq|
933             INSERT INTO aqorders_items
934                 (itemnumber, ordernumber)
935             VALUES (?,?)    |;
936
937     my $sth = $dbh->prepare($query);
938     $sth->execute( $itemnumber, $ordernumber);
939 }
940
941 #------------------------------------------------------------#
942
943 =head3 ModOrder
944
945   &ModOrder(\%hashref);
946
947 Modifies an existing order. Updates the order with order number
948 $hashref->{'ordernumber'} and biblionumber $hashref->{'biblionumber'}. All 
949 other keys of the hash update the fields with the same name in the aqorders 
950 table of the Koha database.
951
952 =cut
953
954 sub ModOrder {
955     my $orderinfo = shift;
956
957     die "Ordernumber is required"     if $orderinfo->{'ordernumber'} eq  '' ;
958     die "Biblionumber is required"  if  $orderinfo->{'biblionumber'} eq '';
959
960     my $dbh = C4::Context->dbh;
961     my @params;
962
963     # update uncertainprice to an integer, just in case (under FF, checked boxes have the value "ON" by default)
964     $orderinfo->{uncertainprice}=1 if $orderinfo->{uncertainprice};
965
966 #    delete($orderinfo->{'branchcode'});
967     # the hash contains a lot of entries not in aqorders, so get the columns ...
968     my $sth = $dbh->prepare("SELECT * FROM aqorders LIMIT 1;");
969     $sth->execute;
970     my $colnames = $sth->{NAME};
971     my $query = "UPDATE aqorders SET ";
972
973     foreach my $orderinfokey (grep(!/ordernumber/, keys %$orderinfo)){
974         # ... and skip hash entries that are not in the aqorders table
975         # FIXME : probably not the best way to do it (would be better to have a correct hash)
976         next unless grep(/^$orderinfokey$/, @$colnames);
977             $query .= "$orderinfokey=?, ";
978             push(@params, $orderinfo->{$orderinfokey});
979     }
980
981     $query .= "timestamp=NOW()  WHERE  ordernumber=?";
982 #   push(@params, $specorderinfo{'ordernumber'});
983     push(@params, $orderinfo->{'ordernumber'} );
984     $sth = $dbh->prepare($query);
985     $sth->execute(@params);
986     $sth->finish;
987 }
988
989 #------------------------------------------------------------#
990
991 =head3 ModOrderItem
992
993   &ModOrderItem(\%hashref);
994
995 Modifies the itemnumber in the aqorders_items table. The input hash needs three entities:
996
997 =over
998
999 =item - itemnumber: the old itemnumber
1000 =item - ordernumber: the order this item is attached to
1001 =item - newitemnumber: the new itemnumber we want to attach the line to
1002
1003 =back
1004
1005 =cut
1006
1007 sub ModOrderItem {
1008     my $orderiteminfo = shift;
1009     if (! $orderiteminfo->{'ordernumber'} || ! $orderiteminfo->{'itemnumber'} || ! $orderiteminfo->{'newitemnumber'}){
1010         die "Ordernumber, itemnumber and newitemnumber is required";
1011     }
1012
1013     my $dbh = C4::Context->dbh;
1014
1015     my $query = "UPDATE aqorders_items set itemnumber=? where itemnumber=? and ordernumber=?";
1016     my @params = ($orderiteminfo->{'newitemnumber'}, $orderiteminfo->{'itemnumber'}, $orderiteminfo->{'ordernumber'});
1017     my $sth = $dbh->prepare($query);
1018     $sth->execute(@params);
1019     return 0;
1020 }
1021
1022 #------------------------------------------------------------#
1023
1024
1025 =head3 ModOrderBibliotemNumber
1026
1027   &ModOrderBiblioitemNumber($biblioitemnumber,$ordernumber, $biblionumber);
1028
1029 Modifies the biblioitemnumber for an existing order.
1030 Updates the order with order number C<$ordernum> and biblionumber C<$biblionumber>.
1031
1032 =cut
1033
1034 #FIXME: is this used at all?
1035 sub ModOrderBiblioitemNumber {
1036     my ($biblioitemnumber,$ordernumber, $biblionumber) = @_;
1037     my $dbh = C4::Context->dbh;
1038     my $query = "
1039     UPDATE aqorders
1040     SET    biblioitemnumber = ?
1041     WHERE  ordernumber = ?
1042     AND biblionumber =  ?";
1043     my $sth = $dbh->prepare($query);
1044     $sth->execute( $biblioitemnumber, $ordernumber, $biblionumber );
1045 }
1046
1047 =head3 GetCancelledOrders
1048
1049   my @orders = GetCancelledOrders($basketno, $orderby);
1050
1051 Returns cancelled orders for a basket
1052
1053 =cut
1054
1055 sub GetCancelledOrders {
1056     my ( $basketno, $orderby ) = @_;
1057
1058     return () unless $basketno;
1059
1060     my $dbh   = C4::Context->dbh;
1061     my $query = "
1062         SELECT biblio.*, biblioitems.*, aqorders.*, aqbudgets.*
1063         FROM aqorders
1064           LEFT JOIN aqbudgets   ON aqbudgets.budget_id = aqorders.budget_id
1065           LEFT JOIN biblio      ON biblio.biblionumber = aqorders.biblionumber
1066           LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
1067         WHERE basketno = ?
1068           AND (datecancellationprinted IS NOT NULL
1069                AND datecancellationprinted <> '0000-00-00')
1070     ";
1071
1072     $orderby = "aqorders.datecancellationprinted desc, aqorders.timestamp desc"
1073         unless $orderby;
1074     $query .= " ORDER BY $orderby";
1075     my $sth = $dbh->prepare($query);
1076     $sth->execute($basketno);
1077     my $results = $sth->fetchall_arrayref( {} );
1078
1079     return @$results;
1080 }
1081
1082
1083 #------------------------------------------------------------#
1084
1085 =head3 ModReceiveOrder
1086
1087   &ModReceiveOrder($biblionumber, $ordernumber, $quantityreceived, $user,
1088     $unitprice, $booksellerinvoicenumber, $biblioitemnumber,
1089     $freight, $bookfund, $rrp);
1090
1091 Updates an order, to reflect the fact that it was received, at least
1092 in part. All arguments not mentioned below update the fields with the
1093 same name in the aqorders table of the Koha database.
1094
1095 If a partial order is received, splits the order into two.  The received
1096 portion must have a booksellerinvoicenumber.
1097
1098 Updates the order with bibilionumber C<$biblionumber> and ordernumber
1099 C<$ordernumber>.
1100
1101 =cut
1102
1103
1104 sub ModReceiveOrder {
1105     my (
1106         $biblionumber,    $ordernumber,  $quantrec, $user, $cost,
1107         $invoiceno, $freight, $rrp, $budget_id, $datereceived
1108     )
1109     = @_;
1110     my $dbh = C4::Context->dbh;
1111 #     warn "DATE BEFORE : $daterecieved";
1112 #    $daterecieved=POSIX::strftime("%Y-%m-%d",CORE::localtime) unless $daterecieved;
1113 #     warn "DATE REC : $daterecieved";
1114     $datereceived = C4::Dates->output('iso') unless $datereceived;
1115     my $suggestionid = GetSuggestionFromBiblionumber( $dbh, $biblionumber );
1116     if ($suggestionid) {
1117         ModSuggestion( {suggestionid=>$suggestionid,
1118                                                 STATUS=>'AVAILABLE',
1119                                                 biblionumber=> $biblionumber}
1120                                                 );
1121     }
1122
1123     my $sth=$dbh->prepare("
1124         SELECT * FROM   aqorders
1125         WHERE           biblionumber=? AND aqorders.ordernumber=?");
1126
1127     $sth->execute($biblionumber,$ordernumber);
1128     my $order = $sth->fetchrow_hashref();
1129     $sth->finish();
1130
1131     if ( $order->{quantity} > $quantrec ) {
1132         $sth=$dbh->prepare("
1133             UPDATE aqorders
1134             SET quantityreceived=?
1135                 , datereceived=?
1136                 , booksellerinvoicenumber=?
1137                 , unitprice=?
1138                 , freight=?
1139                 , rrp=?
1140                 , quantity=?
1141             WHERE biblionumber=? AND ordernumber=?");
1142
1143         $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$quantrec,$biblionumber,$ordernumber);
1144         $sth->finish;
1145
1146         # create a new order for the remaining items, and set its bookfund.
1147         foreach my $orderkey ( "linenumber", "allocation" ) {
1148             delete($order->{'$orderkey'});
1149         }
1150         $order->{'quantity'} -= $quantrec;
1151         $order->{'quantityreceived'} = 0;
1152         my $newOrder = NewOrder($order);
1153 } else {
1154         $sth=$dbh->prepare("update aqorders
1155                             set quantityreceived=?,datereceived=?,booksellerinvoicenumber=?,
1156                                 unitprice=?,freight=?,rrp=?
1157                             where biblionumber=? and ordernumber=?");
1158         $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$biblionumber,$ordernumber);
1159         $sth->finish;
1160     }
1161     return $datereceived;
1162 }
1163 #------------------------------------------------------------#
1164
1165 =head3 SearchOrder
1166
1167 @results = &SearchOrder($search, $biblionumber, $complete);
1168
1169 Searches for orders.
1170
1171 C<$search> may take one of several forms: if it is an ISBN,
1172 C<&ordersearch> returns orders with that ISBN. If C<$search> is an
1173 order number, C<&ordersearch> returns orders with that order number
1174 and biblionumber C<$biblionumber>. Otherwise, C<$search> is considered
1175 to be a space-separated list of search terms; in this case, all of the
1176 terms must appear in the title (matching the beginning of title
1177 words).
1178
1179 If C<$complete> is C<yes>, the results will include only completed
1180 orders. In any case, C<&ordersearch> ignores cancelled orders.
1181
1182 C<&ordersearch> returns an array.
1183 C<@results> is an array of references-to-hash with the following keys:
1184
1185 =over 4
1186
1187 =item C<author>
1188
1189 =item C<seriestitle>
1190
1191 =item C<branchcode>
1192
1193 =item C<bookfundid>
1194
1195 =back
1196
1197 =cut
1198
1199 sub SearchOrder {
1200 #### -------- SearchOrder-------------------------------
1201     my ($ordernumber, $search, $supplierid, $basket) = @_;
1202
1203     my $dbh = C4::Context->dbh;
1204     my @args = ();
1205     my $query =
1206             "SELECT *
1207             FROM aqorders
1208             LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1209             LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
1210             LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
1211                 WHERE  (datecancellationprinted is NULL)";
1212
1213     if($ordernumber){
1214         $query .= " AND (aqorders.ordernumber=?)";
1215         push @args, $ordernumber;
1216     }
1217     if($search){
1218         $query .= " AND (biblio.title like ? OR biblio.author LIKE ? OR biblioitems.isbn like ?)";
1219         push @args, ("%$search%","%$search%","%$search%");
1220     }
1221     if($supplierid){
1222         $query .= "AND aqbasket.booksellerid = ?";
1223         push @args, $supplierid;
1224     }
1225     if($basket){
1226         $query .= "AND aqorders.basketno = ?";
1227         push @args, $basket;
1228     }
1229
1230     my $sth = $dbh->prepare($query);
1231     $sth->execute(@args);
1232     my $results = $sth->fetchall_arrayref({});
1233     $sth->finish;
1234     return $results;
1235 }
1236
1237 #------------------------------------------------------------#
1238
1239 =head3 DelOrder
1240
1241   &DelOrder($biblionumber, $ordernumber);
1242
1243 Cancel the order with the given order and biblio numbers. It does not
1244 delete any entries in the aqorders table, it merely marks them as
1245 cancelled.
1246
1247 =cut
1248
1249 sub DelOrder {
1250     my ( $bibnum, $ordernumber ) = @_;
1251     my $dbh = C4::Context->dbh;
1252     my $query = "
1253         UPDATE aqorders
1254         SET    datecancellationprinted=now()
1255         WHERE  biblionumber=? AND ordernumber=?
1256     ";
1257     my $sth = $dbh->prepare($query);
1258     $sth->execute( $bibnum, $ordernumber );
1259     $sth->finish;
1260     my @itemnumbers = GetItemnumbersFromOrder( $ordernumber );
1261     foreach my $itemnumber (@itemnumbers){
1262         C4::Items::DelItem( $dbh, $bibnum, $itemnumber );
1263     }
1264     
1265 }
1266
1267 =head2 FUNCTIONS ABOUT PARCELS
1268
1269 =cut
1270
1271 #------------------------------------------------------------#
1272
1273 =head3 GetParcel
1274
1275   @results = &GetParcel($booksellerid, $code, $date);
1276
1277 Looks up all of the received items from the supplier with the given
1278 bookseller ID at the given date, for the given code (bookseller Invoice number). Ignores cancelled and completed orders.
1279
1280 C<@results> is an array of references-to-hash. The keys of each element are fields from
1281 the aqorders, biblio, and biblioitems tables of the Koha database.
1282
1283 C<@results> is sorted alphabetically by book title.
1284
1285 =cut
1286
1287 sub GetParcel {
1288     #gets all orders from a certain supplier, orders them alphabetically
1289     my ( $supplierid, $code, $datereceived ) = @_;
1290     my $dbh     = C4::Context->dbh;
1291     my @results = ();
1292     $code .= '%'
1293     if $code;  # add % if we search on a given code (otherwise, let him empty)
1294     my $strsth ="
1295         SELECT  authorisedby,
1296                 creationdate,
1297                 aqbasket.basketno,
1298                 closedate,surname,
1299                 firstname,
1300                 aqorders.biblionumber,
1301                 aqorders.ordernumber,
1302                 aqorders.quantity,
1303                 aqorders.quantityreceived,
1304                 aqorders.unitprice,
1305                 aqorders.listprice,
1306                 aqorders.rrp,
1307                 aqorders.ecost,
1308                 biblio.title
1309         FROM aqorders
1310         LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
1311         LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
1312         LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1313         WHERE
1314             aqbasket.booksellerid = ?
1315             AND aqorders.booksellerinvoicenumber LIKE ?
1316             AND aqorders.datereceived = ? ";
1317
1318     my @query_params = ( $supplierid, $code, $datereceived );
1319     if ( C4::Context->preference("IndependantBranches") ) {
1320         my $userenv = C4::Context->userenv;
1321         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1322             $strsth .= " and (borrowers.branchcode = ?
1323                         or borrowers.branchcode  = '')";
1324             push @query_params, $userenv->{branch};
1325         }
1326     }
1327     $strsth .= " ORDER BY aqbasket.basketno";
1328     # ## parcelinformation : $strsth
1329     my $sth = $dbh->prepare($strsth);
1330     $sth->execute( @query_params );
1331     while ( my $data = $sth->fetchrow_hashref ) {
1332         push( @results, $data );
1333     }
1334     # ## countparcelbiblio: scalar(@results)
1335     $sth->finish;
1336
1337     return @results;
1338 }
1339
1340 #------------------------------------------------------------#
1341
1342 =head3 GetParcels
1343
1344   $results = &GetParcels($bookseller, $order, $code, $datefrom, $dateto);
1345
1346 get a lists of parcels.
1347
1348 * Input arg :
1349
1350 =over
1351
1352 =item $bookseller
1353 is the bookseller this function has to get parcels.
1354
1355 =item $order
1356 To know on what criteria the results list has to be ordered.
1357
1358 =item $code
1359 is the booksellerinvoicenumber.
1360
1361 =item $datefrom & $dateto
1362 to know on what date this function has to filter its search.
1363
1364 =back
1365
1366 * return:
1367 a pointer on a hash list containing parcel informations as such :
1368
1369 =over
1370
1371 =item Creation date
1372
1373 =item Last operation
1374
1375 =item Number of biblio
1376
1377 =item Number of items
1378
1379 =back
1380
1381 =cut
1382
1383 sub GetParcels {
1384     my ($bookseller,$order, $code, $datefrom, $dateto) = @_;
1385     my $dbh    = C4::Context->dbh;
1386     my @query_params = ();
1387     my $strsth ="
1388         SELECT  aqorders.booksellerinvoicenumber,
1389                 datereceived,purchaseordernumber,
1390                 count(DISTINCT biblionumber) AS biblio,
1391                 sum(quantity) AS itemsexpected,
1392                 sum(quantityreceived) AS itemsreceived
1393         FROM   aqorders LEFT JOIN aqbasket ON aqbasket.basketno = aqorders.basketno
1394         WHERE aqbasket.booksellerid = ? and datereceived IS NOT NULL
1395     ";
1396     push @query_params, $bookseller;
1397
1398     if ( defined $code ) {
1399         $strsth .= ' and aqorders.booksellerinvoicenumber like ? ';
1400         # add a % to the end of the code to allow stemming.
1401         push @query_params, "$code%";
1402     }
1403
1404     if ( defined $datefrom ) {
1405         $strsth .= ' and datereceived >= ? ';
1406         push @query_params, $datefrom;
1407     }
1408
1409     if ( defined $dateto ) {
1410         $strsth .=  'and datereceived <= ? ';
1411         push @query_params, $dateto;
1412     }
1413
1414     $strsth .= "group by aqorders.booksellerinvoicenumber,datereceived ";
1415
1416     # can't use a placeholder to place this column name.
1417     # but, we could probably be checking to make sure it is a column that will be fetched.
1418     $strsth .= "order by $order " if ($order);
1419
1420     my $sth = $dbh->prepare($strsth);
1421
1422     $sth->execute( @query_params );
1423     my $results = $sth->fetchall_arrayref({});
1424     $sth->finish;
1425     return @$results;
1426 }
1427
1428 #------------------------------------------------------------#
1429
1430 =head3 GetLateOrders
1431
1432   @results = &GetLateOrders;
1433
1434 Searches for bookseller with late orders.
1435
1436 return:
1437 the table of supplier with late issues. This table is full of hashref.
1438
1439 =cut
1440
1441 sub GetLateOrders {
1442     my $delay      = shift;
1443     my $supplierid = shift;
1444     my $branch     = shift;
1445
1446     my $dbh = C4::Context->dbh;
1447
1448     #BEWARE, order of parenthesis and LEFT JOIN is important for speed
1449     my $dbdriver = C4::Context->config("db_scheme") || "mysql";
1450
1451     my @query_params = ($delay);        # delay is the first argument regardless
1452     my $select = "
1453     SELECT aqbasket.basketno,
1454         aqorders.ordernumber,
1455         DATE(aqbasket.closedate)  AS orderdate,
1456         aqorders.rrp              AS unitpricesupplier,
1457         aqorders.ecost            AS unitpricelib,
1458         aqorders.claims_count     AS claims_count,
1459         aqorders.claimed_date     AS claimed_date,
1460         aqbudgets.budget_name     AS budget,
1461         borrowers.branchcode      AS branch,
1462         aqbooksellers.name        AS supplier,
1463         aqbooksellers.id          AS supplierid,
1464         biblio.author, biblio.title,
1465         biblioitems.publishercode AS publisher,
1466         biblioitems.publicationyear,
1467     ";
1468     my $from = "
1469     FROM
1470         aqorders LEFT JOIN biblio     ON biblio.biblionumber         = aqorders.biblionumber
1471         LEFT JOIN biblioitems         ON biblioitems.biblionumber    = biblio.biblionumber
1472         LEFT JOIN aqbudgets           ON aqorders.budget_id          = aqbudgets.budget_id,
1473         aqbasket LEFT JOIN borrowers  ON aqbasket.authorisedby       = borrowers.borrowernumber
1474         LEFT JOIN aqbooksellers       ON aqbasket.booksellerid       = aqbooksellers.id
1475         WHERE aqorders.basketno = aqbasket.basketno
1476         AND ( datereceived = ''
1477             OR datereceived IS NULL
1478             OR aqorders.quantityreceived < aqorders.quantity
1479         )
1480         AND (aqorders.datecancellationprinted IS NULL OR aqorders.datecancellationprinted='0000-00-00')
1481     ";
1482     my $having = "";
1483     if ($dbdriver eq "mysql") {
1484         $select .= "
1485         aqorders.quantity - IFNULL(aqorders.quantityreceived,0)                 AS quantity,
1486         (aqorders.quantity - IFNULL(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
1487         DATEDIFF(CURDATE( ),closedate) AS latesince
1488         ";
1489         $from .= " AND (closedate <= DATE_SUB(CURDATE( ),INTERVAL ? DAY)) ";
1490         $having = "
1491         HAVING quantity          <> 0
1492             AND unitpricesupplier <> 0
1493             AND unitpricelib      <> 0
1494         ";
1495     } else {
1496         # FIXME: account for IFNULL as above
1497         $select .= "
1498                 aqorders.quantity                AS quantity,
1499                 aqorders.quantity * aqorders.rrp AS subtotal,
1500                 (CURDATE - closedate)            AS latesince
1501         ";
1502         $from .= " AND (closedate <= (CURDATE -(INTERVAL ? DAY)) ";
1503     }
1504     if (defined $supplierid) {
1505         $from .= ' AND aqbasket.booksellerid = ? ';
1506         push @query_params, $supplierid;
1507     }
1508     if (defined $branch) {
1509         $from .= ' AND borrowers.branchcode LIKE ? ';
1510         push @query_params, $branch;
1511     }
1512     if (C4::Context->preference("IndependantBranches")
1513             && C4::Context->userenv
1514             && C4::Context->userenv->{flags} != 1 ) {
1515         $from .= ' AND borrowers.branchcode LIKE ? ';
1516         push @query_params, C4::Context->userenv->{branch};
1517     }
1518     my $query = "$select $from $having\nORDER BY latesince, basketno, borrowers.branchcode, supplier";
1519     $debug and print STDERR "GetLateOrders query: $query\nGetLateOrders args: " . join(" ",@query_params);
1520     my $sth = $dbh->prepare($query);
1521     $sth->execute(@query_params);
1522     my @results;
1523     while (my $data = $sth->fetchrow_hashref) {
1524         $data->{orderdate} = format_date($data->{orderdate});
1525         $data->{claimed_date} = format_date($data->{claimed_date});
1526         push @results, $data;
1527     }
1528     return @results;
1529 }
1530
1531 #------------------------------------------------------------#
1532
1533 =head3 GetHistory
1534
1535   (\@order_loop, $total_qty, $total_price, $total_qtyreceived) = GetHistory( %params );
1536
1537 Retreives some acquisition history information
1538
1539 params:  
1540   title
1541   author
1542   name
1543   from_placed_on
1544   to_placed_on
1545   basket                  - search both basket name and number
1546   booksellerinvoicenumber 
1547
1548 returns:
1549     $order_loop is a list of hashrefs that each look like this:
1550             {
1551                 'author'           => 'Twain, Mark',
1552                 'basketno'         => '1',
1553                 'biblionumber'     => '215',
1554                 'count'            => 1,
1555                 'creationdate'     => 'MM/DD/YYYY',
1556                 'datereceived'     => undef,
1557                 'ecost'            => '1.00',
1558                 'id'               => '1',
1559                 'invoicenumber'    => undef,
1560                 'name'             => '',
1561                 'ordernumber'      => '1',
1562                 'quantity'         => 1,
1563                 'quantityreceived' => undef,
1564                 'title'            => 'The Adventures of Huckleberry Finn'
1565             }
1566     $total_qty is the sum of all of the quantities in $order_loop
1567     $total_price is the cost of each in $order_loop times the quantity
1568     $total_qtyreceived is the sum of all of the quantityreceived entries in $order_loop
1569
1570 =cut
1571
1572 sub GetHistory {
1573 # don't run the query if there are no parameters (list would be too long for sure !)
1574     croak "No search params" unless @_;
1575     my %params = @_;
1576     my $title = $params{title};
1577     my $author = $params{author};
1578     my $isbn   = $params{isbn};
1579     my $name = $params{name};
1580     my $from_placed_on = $params{from_placed_on};
1581     my $to_placed_on = $params{to_placed_on};
1582     my $basket = $params{basket};
1583     my $booksellerinvoicenumber = $params{booksellerinvoicenumber};
1584
1585     my @order_loop;
1586     my $total_qty         = 0;
1587     my $total_qtyreceived = 0;
1588     my $total_price       = 0;
1589
1590     my $dbh   = C4::Context->dbh;
1591     my $query ="
1592         SELECT
1593             biblio.title,
1594             biblio.author,
1595             biblioitems.isbn,
1596             aqorders.basketno,
1597     aqbasket.basketname,
1598     aqbasket.basketgroupid,
1599     aqbasketgroups.name as groupname,
1600             aqbooksellers.name,
1601     aqbasket.creationdate,
1602             aqorders.datereceived,
1603             aqorders.quantity,
1604             aqorders.quantityreceived,
1605             aqorders.ecost,
1606             aqorders.ordernumber,
1607             aqorders.booksellerinvoicenumber as invoicenumber,
1608             aqbooksellers.id as id,
1609             aqorders.biblionumber
1610         FROM aqorders
1611         LEFT JOIN aqbasket ON aqorders.basketno=aqbasket.basketno
1612     LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid=aqbasketgroups.id
1613         LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
1614         LEFT JOIN biblioitems ON biblioitems.biblionumber=aqorders.biblionumber
1615         LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber";
1616
1617     $query .= " LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber"
1618     if ( C4::Context->preference("IndependantBranches") );
1619
1620     $query .= " WHERE (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') ";
1621
1622     my @query_params  = ();
1623
1624     if ( $title ) {
1625         $query .= " AND biblio.title LIKE ? ";
1626         $title =~ s/\s+/%/g;
1627         push @query_params, "%$title%";
1628     }
1629
1630     if ( $author ) {
1631         $query .= " AND biblio.author LIKE ? ";
1632         push @query_params, "%$author%";
1633     }
1634
1635     if ( $isbn ) {
1636         $query .= " AND biblioitems.isbn LIKE ? ";
1637         push @query_params, "%$isbn%";
1638     }
1639
1640     if ( $name ) {
1641         $query .= " AND aqbooksellers.name LIKE ? ";
1642         push @query_params, "%$name%";
1643     }
1644
1645     if ( $from_placed_on ) {
1646         $query .= " AND creationdate >= ? ";
1647         push @query_params, $from_placed_on;
1648     }
1649
1650     if ( $to_placed_on ) {
1651         $query .= " AND creationdate <= ? ";
1652         push @query_params, $to_placed_on;
1653     }
1654
1655     if ($basket) {
1656         if ($basket =~ m/^\d+$/) {
1657             $query .= " AND aqorders.basketno = ? ";
1658             push @query_params, $basket;
1659         } else {
1660             $query .= " AND aqbasket.basketname LIKE ? ";
1661             push @query_params, "%$basket%";
1662         }
1663     }
1664
1665     if ($booksellerinvoicenumber) {
1666         $query .= " AND (aqorders.booksellerinvoicenumber LIKE ? OR aqbasket.booksellerinvoicenumber LIKE ?)";
1667         push @query_params, "%$booksellerinvoicenumber%", "%$booksellerinvoicenumber%";
1668     }
1669
1670     if ( C4::Context->preference("IndependantBranches") ) {
1671         my $userenv = C4::Context->userenv;
1672         if ( $userenv && ($userenv->{flags} || 0) != 1 ) {
1673             $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
1674             push @query_params, $userenv->{branch};
1675         }
1676     }
1677     $query .= " ORDER BY id";
1678     my $sth = $dbh->prepare($query);
1679     $sth->execute( @query_params );
1680     my $cnt = 1;
1681     while ( my $line = $sth->fetchrow_hashref ) {
1682         $line->{count} = $cnt++;
1683         $line->{toggle} = 1 if $cnt % 2;
1684         push @order_loop, $line;
1685         $line->{creationdate} = format_date( $line->{creationdate} );
1686         $line->{datereceived} = format_date( $line->{datereceived} );
1687         $total_qty         += $line->{'quantity'};
1688         $total_qtyreceived += $line->{'quantityreceived'};
1689         $total_price       += $line->{'quantity'} * $line->{'ecost'};
1690     }
1691     return \@order_loop, $total_qty, $total_price, $total_qtyreceived;
1692 }
1693
1694 =head2 GetRecentAcqui
1695
1696   $results = GetRecentAcqui($days);
1697
1698 C<$results> is a ref to a table which containts hashref
1699
1700 =cut
1701
1702 sub GetRecentAcqui {
1703     my $limit  = shift;
1704     my $dbh    = C4::Context->dbh;
1705     my $query = "
1706         SELECT *
1707         FROM   biblio
1708         ORDER BY timestamp DESC
1709         LIMIT  0,".$limit;
1710
1711     my $sth = $dbh->prepare($query);
1712     $sth->execute;
1713     my $results = $sth->fetchall_arrayref({});
1714     return $results;
1715 }
1716
1717 =head3 GetContracts
1718
1719   $contractlist = &GetContracts($booksellerid, $activeonly);
1720
1721 Looks up the contracts that belong to a bookseller
1722
1723 Returns a list of contracts
1724
1725 =over
1726
1727 =item C<$booksellerid> is the "id" field in the "aqbooksellers" table.
1728
1729 =item C<$activeonly> if exists get only contracts that are still active.
1730
1731 =back
1732
1733 =cut
1734
1735 sub GetContracts {
1736     my ( $booksellerid, $activeonly ) = @_;
1737     my $dbh = C4::Context->dbh;
1738     my $query;
1739     if (! $activeonly) {
1740         $query = "
1741             SELECT *
1742             FROM   aqcontract
1743             WHERE  booksellerid=?
1744         ";
1745     } else {
1746         $query = "SELECT *
1747             FROM aqcontract
1748             WHERE booksellerid=?
1749                 AND contractenddate >= CURDATE( )";
1750     }
1751     my $sth = $dbh->prepare($query);
1752     $sth->execute( $booksellerid );
1753     my @results;
1754     while (my $data = $sth->fetchrow_hashref ) {
1755         push(@results, $data);
1756     }
1757     $sth->finish;
1758     return @results;
1759 }
1760
1761 #------------------------------------------------------------#
1762
1763 =head3 GetContract
1764
1765   $contract = &GetContract($contractID);
1766
1767 Looks up the contract that has PRIMKEY (contractnumber) value $contractID
1768
1769 Returns a contract
1770
1771 =cut
1772
1773 sub GetContract {
1774     my ( $contractno ) = @_;
1775     my $dbh = C4::Context->dbh;
1776     my $query = "
1777         SELECT *
1778         FROM   aqcontract
1779         WHERE  contractnumber=?
1780         ";
1781
1782     my $sth = $dbh->prepare($query);
1783     $sth->execute( $contractno );
1784     my $result = $sth->fetchrow_hashref;
1785     return $result;
1786 }
1787
1788 =head3 AddClaim
1789
1790 =over 4
1791
1792 &AddClaim($ordernumber);
1793
1794 Add a claim for an order
1795
1796 =back
1797
1798 =cut
1799 sub AddClaim {
1800     my ($ordernumber) = @_;
1801     my $dbh          = C4::Context->dbh;
1802     my $query        = "
1803         UPDATE aqorders SET
1804             claims_count = claims_count + 1,
1805             claimed_date = CURDATE()
1806         WHERE ordernumber = ?
1807         ";
1808     my $sth = $dbh->prepare($query);
1809     $sth->execute($ordernumber);
1810
1811 }
1812
1813 1;
1814 __END__
1815
1816 =head1 AUTHOR
1817
1818 Koha Development Team <http://koha-community.org/>
1819
1820 =cut