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