removed more redundant 'my' causing variable masking warnings
[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 with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20
21 use strict;
22 require Exporter;
23 use C4::Context;
24 use C4::Dates qw(format_date);
25 use MARC::Record;
26 use C4::Suggestions;
27 use Time::localtime;
28
29 use vars qw($VERSION @ISA @EXPORT);
30
31 # set the version for version checking
32 $VERSION = 3.01;
33
34 # used in receiveorder subroutine
35 # to provide library specific handling
36 my $library_name = C4::Context->preference("LibraryName");
37
38 =head1 NAME
39
40 C4::Acquisition - Koha functions for dealing with orders and acquisitions
41
42 =head1 SYNOPSIS
43
44 use C4::Acquisition;
45
46 =head1 DESCRIPTION
47
48 The functions in this module deal with acquisitions, managing book
49 orders, basket and parcels.
50
51 =head1 FUNCTIONS
52
53 =over 2
54
55 =cut
56
57 @ISA    = qw(Exporter);
58 @EXPORT = qw(
59   &GetBasket &NewBasket &CloseBasket
60   &GetPendingOrders &GetOrder &GetOrders
61   &GetOrderNumber &GetLateOrders &NewOrder &DelOrder
62   &SearchOrder &GetHistory &GetRecentAcqui
63   &ModOrder &ModReceiveOrder &ModOrderBiblioNumber
64   &GetParcels &GetParcel
65 );
66
67 =head2 FUNCTIONS ABOUT BASKETS
68
69 =over 2
70
71 =cut
72
73 #------------------------------------------------------------#
74
75 =head3 GetBasket
76
77 =over 4
78
79 $aqbasket = &GetBasket($basketnumber);
80
81 get all basket informations in aqbasket for a given basket
82
83 return :
84 informations for a given basket returned as a hashref.
85
86 =back
87
88 =back
89
90 =cut
91
92 sub GetBasket {
93     my ($basketno) = @_;
94     my $dbh        = C4::Context->dbh;
95     my $query = "
96         SELECT  aqbasket.*,
97                 concat( b.firstname,' ',b.surname) AS authorisedbyname,
98                 b.branchcode AS branch
99         FROM    aqbasket
100         LEFT JOIN borrowers b ON aqbasket.authorisedby=b.borrowernumber
101         WHERE basketno=?
102     ";
103     my $sth=$dbh->prepare($query);
104     $sth->execute($basketno);
105     my $basket = $sth->fetchrow_hashref;
106         return ( $basket );
107 }
108
109 #------------------------------------------------------------#
110
111 =head3 NewBasket
112
113 =over 4
114
115 $basket = &NewBasket();
116
117 Create a new basket in aqbasket table
118
119 =back
120
121 =cut
122
123 # FIXME : this function seems to be unused.
124
125 sub NewBasket {
126     my ( $booksellerid, $authorisedby ) = @_;
127     my $dbh = C4::Context->dbh;
128     my $query = "
129         INSERT INTO aqbasket
130                 (creationdate,booksellerid,authorisedby)
131         VALUES  (now(),'$booksellerid','$authorisedby')
132     ";
133     my $sth =
134       $dbh->do($query);
135
136 #find & return basketno MYSQL dependant, but $dbh->last_insert_id always returns null :-(
137     my $basket = $dbh->{'mysql_insertid'};
138     return $basket;
139 }
140
141 #------------------------------------------------------------#
142
143 =head3 CloseBasket
144
145 =over 4
146
147 &CloseBasket($basketno);
148
149 close a basket (becomes unmodifiable,except for recieves)
150
151 =back
152
153 =cut
154
155 sub CloseBasket {
156     my ($basketno) = @_;
157     my $dbh        = C4::Context->dbh;
158     my $query = "
159         UPDATE aqbasket
160         SET    closedate=now()
161         WHERE  basketno=?
162     ";
163     my $sth = $dbh->prepare($query);
164     $sth->execute($basketno);
165 }
166
167 #------------------------------------------------------------#
168
169 =back
170
171 =head2 FUNCTIONS ABOUT ORDERS
172
173 =over 2
174
175 =cut
176
177 #------------------------------------------------------------#
178
179 =head3 GetPendingOrders
180
181 =over 4
182
183 $orders = &GetPendingOrders($booksellerid, $grouped);
184
185 Finds pending orders from the bookseller with the given ID. Ignores
186 completed and cancelled orders.
187
188 C<$orders> is a reference-to-array; each element is a
189 reference-to-hash with the following fields:
190 C<$grouped> is a boolean that, if set to 1 will group all order lines of the same basket
191 in a single result line 
192
193 =over 2
194
195 =item C<authorizedby>
196
197 =item C<entrydate>
198
199 =item C<basketno>
200
201 These give the value of the corresponding field in the aqorders table
202 of the Koha database.
203
204 =back
205
206 =back
207
208 Results are ordered from most to least recent.
209
210 =cut
211
212 sub GetPendingOrders {
213     my ($supplierid,$grouped) = @_;
214     my $dbh = C4::Context->dbh;
215     my $strsth = "
216         SELECT    ".($grouped?"count(*),":"")."aqbasket.basketno,
217                     surname,firstname,aqorders.*,
218                     aqbasket.closedate, aqbasket.creationdate
219         FROM      aqorders
220         LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
221         LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
222         WHERE booksellerid=?
223             AND (quantity > quantityreceived OR quantityreceived is NULL)
224             AND datecancellationprinted IS NULL
225             AND (to_days(now())-to_days(closedate) < 180 OR closedate IS NULL)
226     ";
227     ## FIXME  Why 180 days ???
228     if ( C4::Context->preference("IndependantBranches") ) {
229         my $userenv = C4::Context->userenv;
230         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
231             $strsth .=
232                 " and (borrowers.branchcode = '"
233               . $userenv->{branch}
234               . "' or borrowers.branchcode ='')";
235         }
236     }
237     $strsth .= " group by aqbasket.basketno" if $grouped;
238     $strsth .= " order by aqbasket.basketno";
239
240     my $sth = $dbh->prepare($strsth);
241     $sth->execute($supplierid);
242     my $results = $sth->fetchall_arrayref({});
243     $sth->finish;
244     return $results;
245 }
246
247 #------------------------------------------------------------#
248
249 =head3 GetOrders
250
251 =over 4
252
253 @orders = &GetOrders($basketnumber, $orderby);
254
255 Looks up the pending (non-cancelled) orders with the given basket
256 number. If C<$booksellerID> is non-empty, only orders from that seller
257 are returned.
258
259 return :
260 C<&basket> returns a two-element array. C<@orders> is an array of
261 references-to-hash, whose keys are the fields from the aqorders,
262 biblio, and biblioitems tables in the Koha database.
263
264 =back
265
266 =cut
267
268 sub GetOrders {
269     my ( $basketno, $orderby ) = @_;
270     my $dbh   = C4::Context->dbh;
271     my $query  ="
272          SELECT  aqorderbreakdown.*,
273                 biblio.*,biblioitems.publishercode,
274                 aqorders.*,
275                 aqbookfund.bookfundname,
276                 biblio.title
277         FROM    aqorders
278             LEFT JOIN aqorderbreakdown ON aqorders.ordernumber=aqorderbreakdown.ordernumber
279             LEFT JOIN aqbookfund       ON aqbookfund.bookfundid=aqorderbreakdown.bookfundid
280             LEFT JOIN biblio           ON biblio.biblionumber=aqorders.biblionumber
281             LEFT JOIN biblioitems      ON biblioitems.biblionumber=biblio.biblionumber
282         WHERE   basketno=?
283             AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
284     ";
285
286     $orderby = "biblioitems.publishercode,biblio.title" unless $orderby;
287     $query .= " ORDER BY $orderby";
288     my $sth = $dbh->prepare($query);
289     $sth->execute($basketno);
290     my @results;
291
292     while ( my $data = $sth->fetchrow_hashref ) {
293         push @results, $data;
294     }
295     $sth->finish;
296     return @results;
297 }
298
299 #------------------------------------------------------------#
300
301 =head3 GetOrderNumber
302
303 =over 4
304
305 $ordernumber = &GetOrderNumber($biblioitemnumber, $biblionumber);
306
307 Looks up the ordernumber with the given biblionumber and biblioitemnumber.
308
309 Returns the number of this order.
310
311 =item C<$ordernumber> is the order number.
312
313 =back
314
315 =cut
316 sub GetOrderNumber {
317     my ( $biblionumber,$biblioitemnumber ) = @_;
318     my $dbh = C4::Context->dbh;
319     my $query = "
320         SELECT ordernumber
321         FROM   aqorders
322         WHERE  biblionumber=?
323         AND    biblioitemnumber=?
324     ";
325     my $sth = $dbh->prepare($query);
326     $sth->execute( $biblionumber, $biblioitemnumber );
327
328     return $sth->fetchrow;
329 }
330
331 #------------------------------------------------------------#
332
333 =head3 GetOrder
334
335 =over 4
336
337 $order = &GetOrder($ordernumber);
338
339 Looks up an order by order number.
340
341 Returns a reference-to-hash describing the order. The keys of
342 C<$order> are fields from the biblio, biblioitems, aqorders, and
343 aqorderbreakdown tables of the Koha database.
344
345 =back
346
347 =cut
348
349 sub GetOrder {
350     my ($ordnum) = @_;
351     my $dbh      = C4::Context->dbh;
352     my $query = "
353         SELECT *
354         FROM   aqorders
355         LEFT JOIN aqorderbreakdown ON aqorders.ordernumber=aqorderbreakdown.ordernumber
356         LEFT JOIN biblio on           biblio.biblionumber=aqorders.biblionumber
357         LEFT JOIN biblioitems on       biblioitems.biblionumber=aqorders.biblionumber
358         WHERE aqorders.ordernumber=?
359
360     ";
361     my $sth= $dbh->prepare($query);
362     $sth->execute($ordnum);
363     my $data = $sth->fetchrow_hashref;
364     $sth->finish;
365     return $data;
366 }
367
368 #------------------------------------------------------------#
369
370 =head3 NewOrder
371
372 =over 4
373
374   &NewOrder($basket, $biblionumber, $title, $quantity, $listprice,
375     $booksellerid, $who, $notes, $bookfund, $biblioitemnumber, $rrp,
376     $ecost, $gst, $budget, $unitprice, $subscription,
377     $booksellerinvoicenumber, $purchaseorder);
378
379 Adds a new order to the database. Any argument that isn't described
380 below is the new value of the field with the same name in the aqorders
381 table of the Koha database.
382
383 C<$ordnum> is a "minimum order number." After adding the new entry to
384 the aqorders table, C<&neworder> finds the first entry in aqorders
385 with order number greater than or equal to C<$ordnum>, and adds an
386 entry to the aqorderbreakdown table, with the order number just found,
387 and the book fund ID of the newly-added order.
388
389 C<$budget> is effectively ignored.
390
391 C<$subscription> may be either "yes", or anything else for "no".
392
393 =back
394
395 =cut
396
397 sub NewOrder {
398    my (
399         $basketno,  $bibnum,       $title,        $quantity,
400         $listprice, $booksellerid, $authorisedby, $notes,
401         $bookfund,  $bibitemnum,   $rrp,          $ecost,
402         $gst,       $budget,       $cost,         $sub,
403         $invoice,   $sort1,        $sort2,        $purchaseorder
404       )
405       = @_;
406
407     my $year  = localtime->year() + 1900;
408     my $month = localtime->mon() + 1;       # months starts at 0, add 1
409
410     if ( !$budget || $budget eq 'now' ) {
411         $budget = "now()";
412     }
413
414     # if month is july or more, budget start is 1 jul, next year.
415     elsif ( $month >= '7' ) {
416         ++$year;                            # add 1 to year , coz its next year
417         $budget = "'$year-07-01'";
418     }
419     else {
420
421         # START OF NEW BUDGET, 1ST OF JULY, THIS YEAR
422         $budget = "'$year-07-01'";
423     }
424
425     if ( $sub eq 'yes' ) {
426         $sub = 1;
427     }
428     else {
429         $sub = 0;
430     }
431
432     # if $basket empty, it's also a new basket, create it
433     unless ($basketno) {
434         $basketno = NewBasket( $booksellerid, $authorisedby );
435     }
436
437     my $dbh = C4::Context->dbh;
438     my $query = "
439         INSERT INTO aqorders
440            ( biblionumber,title,basketno,quantity,listprice,notes,
441            biblioitemnumber,rrp,ecost,gst,unitprice,subscription,sort1,sort2,budgetdate,entrydate,purchaseordernumber)
442         VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,$budget,now(),? )
443     ";
444     my $sth = $dbh->prepare($query);
445
446     $sth->execute(
447         $bibnum, $title,      $basketno, $quantity, $listprice,
448         $notes,  $bibitemnum, $rrp,      $ecost,    $gst,
449         $cost,   $sub,        $sort1,    $sort2,        $purchaseorder
450     );
451     $sth->finish;
452
453     #get ordnum MYSQL dependant, but $dbh->last_insert_id returns null
454     my $ordnum = $dbh->{'mysql_insertid'};
455     $query = "
456         INSERT INTO aqorderbreakdown (ordernumber,bookfundid)
457         VALUES (?,?)
458     ";
459     $sth = $dbh->prepare($query);
460     $sth->execute( $ordnum, $bookfund );
461     $sth->finish;
462     return ( $basketno, $ordnum );
463 }
464
465 #------------------------------------------------------------#
466
467 =head3 ModOrder
468
469 =over 4
470
471 &ModOrder($title, $ordernumber, $quantity, $listprice,
472     $biblionumber, $basketno, $supplier, $who, $notes,
473     $bookfundid, $bibitemnum, $rrp, $ecost, $gst, $budget,
474     $unitprice, $booksellerinvoicenumber);
475
476 Modifies an existing order. Updates the order with order number
477 C<$ordernumber> and biblionumber C<$biblionumber>. All other arguments
478 update the fields with the same name in the aqorders table of the Koha
479 database.
480
481 Entries with order number C<$ordernumber> in the aqorderbreakdown
482 table are also updated to the new book fund ID.
483
484 =back
485
486 =cut
487
488 sub ModOrder {
489     my (
490         $title,      $ordnum,   $quantity, $listprice, $bibnum,
491         $basketno,   $supplier, $who,      $notes,     $bookfund,
492         $bibitemnum, $rrp,      $ecost,    $gst,       $budget,
493         $cost,       $invoice,  $sort1,    $sort2,     $purchaseorder
494       )
495       = @_;
496     my $dbh = C4::Context->dbh;
497     my $query = "
498         UPDATE aqorders
499         SET    title=?,
500                quantity=?,listprice=?,basketno=?,
501                rrp=?,ecost=?,unitprice=?,booksellerinvoicenumber=?,
502                notes=?,sort1=?, sort2=?, purchaseordernumber=?
503         WHERE  ordernumber=? AND biblionumber=?
504     ";
505     my $sth = $dbh->prepare($query);
506     $sth->execute(
507         $title, $quantity, $listprice, $basketno, $rrp,
508         $ecost, $cost,     $invoice,   $notes,    $sort1,
509         $sort2, $purchaseorder,
510                 $ordnum,   $bibnum
511     );
512     $sth->finish;
513     $query = "
514         UPDATE aqorderbreakdown
515         SET    bookfundid=?
516         WHERE  ordernumber=?
517     ";
518     $sth = $dbh->prepare($query);
519
520     unless ( $sth->execute( $bookfund, $ordnum ) )
521     {    # zero rows affected [Bug 734]
522         my $query ="
523             INSERT INTO aqorderbreakdown
524                      (ordernumber,bookfundid)
525             VALUES   (?,?)
526         ";
527         $sth = $dbh->prepare($query);
528         $sth->execute( $ordnum, $bookfund );
529     }
530     $sth->finish;
531 }
532
533 #------------------------------------------------------------#
534
535 =head3 ModOrderBiblioNumber
536
537 =over 4
538
539 &ModOrderBiblioNumber($biblioitemnumber,$ordnum, $biblionumber);
540
541 Modifies the biblioitemnumber for an existing order.
542 Updates the order with order number C<$ordernum> and biblionumber C<$biblionumber>.
543
544 =back
545
546 =cut
547
548 sub ModOrderBiblioNumber {
549     my ($biblioitemnumber,$ordnum, $biblionumber) = @_;
550     my $dbh = C4::Context->dbh;
551     my $query = "
552       UPDATE aqorders
553       SET    biblioitemnumber = ?
554       WHERE  ordernumber = ?
555       AND biblionumber =  ?";
556     my $sth = $dbh->prepare($query);
557     $sth->execute( $biblioitemnumber, $ordnum, $biblionumber );
558 }
559
560 #------------------------------------------------------------#
561
562 =head3 ModReceiveOrder
563
564 =over 4
565
566 &ModReceiveOrder($biblionumber, $ordernumber, $quantityreceived, $user,
567     $unitprice, $booksellerinvoicenumber, $biblioitemnumber,
568     $freight, $bookfund, $rrp);
569
570 Updates an order, to reflect the fact that it was received, at least
571 in part. All arguments not mentioned below update the fields with the
572 same name in the aqorders table of the Koha database.
573
574 If a partial order is received, splits the order into two.  The received
575 portion must have a booksellerinvoicenumber.  
576
577 Updates the order with bibilionumber C<$biblionumber> and ordernumber
578 C<$ordernumber>.
579
580 Also updates the book fund ID in the aqorderbreakdown table.
581
582 =back
583
584 =cut
585
586
587 sub ModReceiveOrder {
588     my (
589         $biblionumber,    $ordnum,  $quantrec, $user, $cost,
590         $invoiceno, $freight, $rrp, $bookfund, $datereceived
591       )
592       = @_;
593     my $dbh = C4::Context->dbh;
594 #     warn "DATE BEFORE : $daterecieved";
595 #    $daterecieved=POSIX::strftime("%Y-%m-%d",CORE::localtime) unless $daterecieved;
596 #     warn "DATE REC : $daterecieved";
597         $datereceived = C4::Dates->output('iso') unless $datereceived;
598     my $suggestionid = GetSuggestionFromBiblionumber( $dbh, $biblionumber );
599     if ($suggestionid) {
600         ModStatus( $suggestionid, 'AVAILABLE', '', $biblionumber );
601     }
602     # Allows libraries to change their bookfund during receiving orders
603     # allows them to adjust budgets
604     if ( C4::Context->preference("LooseBudgets") && $bookfund ) {
605         my $query = "
606             UPDATE aqorderbreakdown
607             SET    bookfundid=?
608             WHERE  ordernumber=?
609         ";
610         my $sth = $dbh->prepare($query);
611         $sth->execute( $bookfund, $ordnum );
612         $sth->finish;
613     }
614    
615         my $sth=$dbh->prepare("SELECT * FROM aqorders  LEFT JOIN aqorderbreakdown ON aqorders.ordernumber=aqorderbreakdown.ordernumber
616                                                         WHERE biblionumber=? AND aqorders.ordernumber=?");
617     $sth->execute($biblionumber,$ordnum);
618     my $order = $sth->fetchrow_hashref();
619     $sth->finish();
620         
621         if ( $order->{quantity} > $quantrec ) {
622         $sth=$dbh->prepare("update aqorders 
623                                                         set quantityreceived=?,datereceived=?,booksellerinvoicenumber=?, 
624                                                                 unitprice=?,freight=?,rrp=?,quantity=?
625                             where biblionumber=? and ordernumber=?");
626         $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$quantrec,$biblionumber,$ordnum);
627         $sth->finish;
628         # create a new order for the remaining items, and set its bookfund.
629         my $newOrder = NewOrder($order->{'basketno'},$order->{'biblionumber'},$order->{'title'}, $order->{'quantity'} - $quantrec,    
630                     $order->{'listprice'},$order->{'booksellerid'},$order->{'authorisedby'},$order->{'notes'},   
631                     $order->{'bookfundid'},$order->{'biblioitemnumber'},$order->{'rrp'},$order->{'ecost'},$order->{'gst'},
632                     $order->{'budget'},$order->{'unitcost'},$order->{'sub'},'',$order->{'sort1'},$order->{'sort2'},$order->{'purchaseordernumber'});
633     
634         $sth=$dbh->prepare(" insert into aqorderbreakdown (ordernumber, branchcode, bookfundid) values (?,?,?)"); 
635         $sth->execute($newOrder,$order->{branch},$order->{bookfundid});
636     } else {
637         $sth=$dbh->prepare("update aqorders 
638                                                         set quantityreceived=?,datereceived=?,booksellerinvoicenumber=?, 
639                                                                 unitprice=?,freight=?,rrp=?
640                             where biblionumber=? and ordernumber=?");
641         $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$biblionumber,$ordnum);
642         $sth->finish;
643     }
644     return $datereceived;
645 }
646 #------------------------------------------------------------#
647
648 =head3 SearchOrder
649
650 @results = &SearchOrder($search, $biblionumber, $complete);
651
652 Searches for orders.
653
654 C<$search> may take one of several forms: if it is an ISBN,
655 C<&ordersearch> returns orders with that ISBN. If C<$search> is an
656 order number, C<&ordersearch> returns orders with that order number
657 and biblionumber C<$biblionumber>. Otherwise, C<$search> is considered
658 to be a space-separated list of search terms; in this case, all of the
659 terms must appear in the title (matching the beginning of title
660 words).
661
662 If C<$complete> is C<yes>, the results will include only completed
663 orders. In any case, C<&ordersearch> ignores cancelled orders.
664
665 C<&ordersearch> returns an array.
666 C<@results> is an array of references-to-hash with the following keys:
667
668 =over 4
669
670 =item C<author>
671
672 =item C<seriestitle>
673
674 =item C<branchcode>
675
676 =item C<bookfundid>
677
678 =back
679
680 =cut
681
682 sub SearchOrder {
683     my ( $search, $id, $biblionumber, $catview ) = @_;
684     my $dbh = C4::Context->dbh;
685     my @data = split( ' ', $search );
686     my @searchterms;
687     if ($id) {
688         @searchterms = ($id);
689     }
690     map { push( @searchterms, "$_%", "%$_%" ) } @data;
691     push( @searchterms, $search, $search, $biblionumber );
692     my $query;
693   ### FIXME  THIS CAN raise a problem if more THAN ONE biblioitem is linked to one biblio  
694     if ($id) {  
695         $query =
696           "SELECT *,biblio.title 
697            FROM aqorders 
698            LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber 
699            LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber 
700            LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
701             WHERE aqbasket.booksellerid = ?
702             AND ((datecancellationprinted is NULL)
703             OR (datecancellationprinted = '0000-00-00'))
704             AND (("
705           . (
706             join( " AND ",
707                 map { "(biblio.title like ? or biblio.title like ?)" } @data )
708           )
709           . ") OR biblioitems.isbn=? OR (aqorders.ordernumber=? AND aqorders.biblionumber=?)) ";
710
711     }
712     else {
713         $query =
714           " SELECT *,biblio.title
715             FROM   aqorders
716             LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
717             LEFT JOIN aqbasket on aqorders.basketno=aqbasket.basketno
718             LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber      
719             WHERE  ((datecancellationprinted is NULL)
720             OR     (datecancellationprinted = '0000-00-00'))
721             AND    (aqorders.quantityreceived < aqorders.quantity OR aqorders.quantityreceived is NULL)
722             AND (("
723           . (
724             join( " AND ",
725                 map { "(biblio.title like ? OR biblio.title like ?)" } @data )
726           )
727           . ") or biblioitems.isbn=? OR (aqorders.ordernumber=? AND aqorders.biblionumber=?)) ";
728     }
729     $query .= " GROUP BY aqorders.ordernumber";
730     ### $query
731     my $sth = $dbh->prepare($query);
732     $sth->execute(@searchterms);
733     my @results = ();
734     my $query2 = "
735         SELECT *
736         FROM   biblio
737         WHERE  biblionumber=?
738     ";
739     my $sth2 = $dbh->prepare($query2);
740     my $query3 = "
741         SELECT *
742         FROM   aqorderbreakdown
743         WHERE  ordernumber=?
744     ";
745     my $sth3 = $dbh->prepare($query3);
746
747     while ( my $data = $sth->fetchrow_hashref ) {
748         $sth2->execute( $data->{'biblionumber'} );
749         my $data2 = $sth2->fetchrow_hashref;
750         $data->{'author'}      = $data2->{'author'};
751         $data->{'seriestitle'} = $data2->{'seriestitle'};
752         $sth3->execute( $data->{'ordernumber'} );
753         my $data3 = $sth3->fetchrow_hashref;
754         $data->{'branchcode'} = $data3->{'branchcode'};
755         $data->{'bookfundid'} = $data3->{'bookfundid'};
756         push( @results, $data );
757     }
758     ### @results
759     $sth->finish;
760     $sth2->finish;
761     $sth3->finish;
762     return @results;
763 }
764
765 #------------------------------------------------------------#
766
767 =head3 DelOrder
768
769 =over 4
770
771 &DelOrder($biblionumber, $ordernumber);
772
773 Cancel the order with the given order and biblio numbers. It does not
774 delete any entries in the aqorders table, it merely marks them as
775 cancelled.
776
777 =back
778
779 =cut
780
781 sub DelOrder {
782     my ( $bibnum, $ordnum ) = @_;
783     my $dbh = C4::Context->dbh;
784     my $query = "
785         UPDATE aqorders
786         SET    datecancellationprinted=now()
787         WHERE  biblionumber=? AND ordernumber=?
788     ";
789     my $sth = $dbh->prepare($query);
790     $sth->execute( $bibnum, $ordnum );
791     $sth->finish;
792 }
793
794
795 =back
796
797 =head2 FUNCTIONS ABOUT PARCELS
798
799 =over 2
800
801 =cut
802
803 #------------------------------------------------------------#
804
805 =head3 GetParcel
806
807 =over 4
808
809 @results = &GetParcel($booksellerid, $code, $date);
810
811 Looks up all of the received items from the supplier with the given
812 bookseller ID at the given date, for the given code (bookseller Invoice number). Ignores cancelled and completed orders.
813
814 C<@results> is an array of references-to-hash. The keys of each element are fields from
815 the aqorders, biblio, and biblioitems tables of the Koha database.
816
817 C<@results> is sorted alphabetically by book title.
818
819 =back
820
821 =cut
822
823 sub GetParcel {
824     #gets all orders from a certain supplier, orders them alphabetically
825     my ( $supplierid, $code, $datereceived ) = @_;
826     my $dbh     = C4::Context->dbh;
827     my @results = ();
828     $code .= '%'
829       if $code;  # add % if we search on a given code (otherwise, let him empty)
830     my $strsth ="
831         SELECT  authorisedby,
832                 creationdate,
833                 aqbasket.basketno,
834                 closedate,surname,
835                 firstname,
836                 aqorders.biblionumber,
837                 aqorders.title,
838                 aqorders.ordernumber,
839                 aqorders.quantity,
840                 aqorders.quantityreceived,
841                 aqorders.unitprice,
842                 aqorders.listprice,
843                 aqorders.rrp,
844                 aqorders.ecost
845         FROM aqorders 
846         LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
847         LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
848         WHERE 
849             aqbasket.booksellerid=?
850             AND aqorders.booksellerinvoicenumber LIKE  \"$code\"
851             AND aqorders.datereceived= \'$datereceived\'";
852
853     if ( C4::Context->preference("IndependantBranches") ) {
854         my $userenv = C4::Context->userenv;
855         if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
856             $strsth .=
857                 " AND (borrowers.branchcode = '"
858               . $userenv->{branch}
859               . "' OR borrowers.branchcode ='')";
860         }
861     }
862     $strsth .= " ORDER BY aqbasket.basketno";
863     ### parcelinformation : $strsth
864  #   warn "STH : $strsth";
865     my $sth = $dbh->prepare($strsth);
866     $sth->execute($supplierid);
867     while ( my $data = $sth->fetchrow_hashref ) {
868         push( @results, $data );
869     }
870     ### countparcelbiblio: scalar(@results)
871     $sth->finish;
872
873     return @results;
874 }
875
876 #------------------------------------------------------------#
877
878 =head3 GetParcels
879
880 =over 4
881
882 $results = &GetParcels($bookseller, $order, $code, $datefrom, $dateto);
883 get a lists of parcels.
884
885 * Input arg :
886
887 =item $bookseller
888 is the bookseller this function has to get parcels.
889
890 =item $order
891 To know on what criteria the results list has to be ordered.
892
893 =item $code
894 is the booksellerinvoicenumber.
895
896 =item $datefrom & $dateto
897 to know on what date this function has to filter its search.
898
899 * return:
900 a pointer on a hash list containing parcel informations as such :
901
902 =item Creation date
903
904 =item Last operation
905
906 =item Number of biblio
907
908 =item Number of items
909
910 =back
911
912 =cut
913
914 sub GetParcels {
915     my ($bookseller,$order, $code, $datefrom, $dateto) = @_;
916     my $dbh    = C4::Context->dbh;
917     my $strsth ="
918         SELECT  aqorders.booksellerinvoicenumber,
919                 datereceived,purchaseordernumber,
920                 count(DISTINCT biblionumber) AS biblio,
921                 sum(quantity) AS itemsexpected,
922                 sum(quantityreceived) AS itemsreceived
923         FROM   aqorders LEFT JOIN aqbasket ON aqbasket.basketno = aqorders.basketno
924         WHERE aqbasket.booksellerid = $bookseller and datereceived IS NOT NULL
925     ";
926
927     $strsth .= "and aqorders.booksellerinvoicenumber like \"$code%\" " if ($code);
928
929     $strsth .= "and datereceived >=" . $dbh->quote($datefrom) . " " if ($datefrom);
930
931     $strsth .= "and datereceived <=" . $dbh->quote($dateto) . " " if ($dateto);
932
933     $strsth .= "group by aqorders.booksellerinvoicenumber,datereceived ";
934     $strsth .= "order by $order " if ($order);
935 ### $strsth
936     my $sth = $dbh->prepare($strsth);
937
938     $sth->execute;
939     my $results = $sth->fetchall_arrayref({});
940     $sth->finish;
941     return @$results;
942 }
943
944 #------------------------------------------------------------#
945
946 =head3 GetLateOrders
947
948 =over 4
949
950 @results = &GetLateOrders;
951
952 Searches for bookseller with late orders.
953
954 return:
955 the table of supplier with late issues. This table is full of hashref.
956
957 =back
958
959 =cut
960
961 sub GetLateOrders {
962     my $delay      = shift;
963     my $supplierid = shift;
964     my $branch     = shift;
965
966     my $dbh = C4::Context->dbh;
967
968     #BEWARE, order of parenthesis and LEFT JOIN is important for speed
969     my $strsth;
970     my $dbdriver = C4::Context->config("db_scheme") || "mysql";
971
972     #    warn " $dbdriver";
973     if ( $dbdriver eq "mysql" ) {
974         $strsth = "
975             SELECT aqbasket.basketno,aqorders.ordernumber,
976                 DATE(aqbasket.closedate) AS orderdate,
977                 aqorders.quantity - IFNULL(aqorders.quantityreceived,0) AS quantity,
978                 aqorders.rrp AS unitpricesupplier,
979                 aqorders.ecost AS unitpricelib,
980                 (aqorders.quantity - IFNULL(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
981                 aqbookfund.bookfundname AS budget,
982                 borrowers.branchcode AS branch,
983                 aqbooksellers.name AS supplier,
984                 aqorders.title,
985                 biblio.author,
986                 biblioitems.publishercode AS publisher,
987                 biblioitems.publicationyear,
988                 DATEDIFF(CURDATE( ),closedate) AS latesince
989             FROM  (((
990                 (aqorders LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber)
991             LEFT JOIN biblioitems ON  biblioitems.biblionumber=biblio.biblionumber)
992             LEFT JOIN aqorderbreakdown ON aqorders.ordernumber = aqorderbreakdown.ordernumber)
993             LEFT JOIN aqbookfund ON aqorderbreakdown.bookfundid = aqbookfund.bookfundid),
994             (aqbasket LEFT JOIN borrowers ON aqbasket.authorisedby = borrowers.borrowernumber)
995             LEFT JOIN aqbooksellers ON aqbasket.booksellerid = aqbooksellers.id
996             WHERE aqorders.basketno = aqbasket.basketno
997             AND (closedate < DATE_SUB(CURDATE( ),INTERVAL $delay DAY))
998             AND ((datereceived = '' OR datereceived is null)
999             OR (aqorders.quantityreceived < aqorders.quantity) )
1000         ";
1001         $strsth .= " AND aqbasket.booksellerid = $supplierid " if ($supplierid);
1002         $strsth .= " AND borrowers.branchcode like \'" . $branch . "\'"
1003           if ($branch);
1004         $strsth .=
1005           " AND borrowers.branchcode like \'"
1006           . C4::Context->userenv->{branch} . "\'"
1007           if ( C4::Context->preference("IndependantBranches")
1008             && C4::Context->userenv
1009             && C4::Context->userenv->{flags} != 1 );
1010         $strsth .=" HAVING quantity<>0
1011                     AND unitpricesupplier<>0
1012                     AND unitpricelib<>0
1013                     ORDER BY latesince,basketno,borrowers.branchcode, supplier
1014         ";
1015     }
1016     else {
1017         $strsth = "
1018             SELECT aqbasket.basketno,
1019                    DATE(aqbasket.closedate) AS orderdate,
1020                     aqorders.quantity, aqorders.rrp AS unitpricesupplier,
1021                     aqorders.ecost as unitpricelib,
1022                     aqorders.quantity * aqorders.rrp AS subtotal
1023                     aqbookfund.bookfundname AS budget,
1024                     borrowers.branchcode AS branch,
1025                     aqbooksellers.name AS supplier,
1026                     biblio.title,
1027                     biblio.author,
1028                     biblioitems.publishercode AS publisher,
1029                     biblioitems.publicationyear,
1030                     (CURDATE -  closedate) AS latesince
1031                     FROM(( (
1032                         (aqorders LEFT JOIN biblio on biblio.biblionumber = aqorders.biblionumber)
1033                         LEFT JOIN biblioitems on  biblioitems.biblionumber=biblio.biblionumber)
1034                         LEFT JOIN aqorderbreakdown on aqorders.ordernumber = aqorderbreakdown.ordernumber)
1035                         LEFT JOIN aqbookfund ON aqorderbreakdown.bookfundid = aqbookfund.bookfundid),
1036                         (aqbasket LEFT JOIN borrowers on aqbasket.authorisedby = borrowers.borrowernumber) LEFT JOIN aqbooksellers ON aqbasket.booksellerid = aqbooksellers.id
1037                     WHERE aqorders.basketno = aqbasket.basketno
1038                     AND (closedate < (CURDATE -(INTERVAL $delay DAY))
1039                     AND ((datereceived = '' OR datereceived is null)
1040                     OR (aqorders.quantityreceived < aqorders.quantity) ) ";
1041         $strsth .= " AND aqbasket.booksellerid = $supplierid " if ($supplierid);
1042
1043         $strsth .= " AND borrowers.branchcode like \'" . $branch . "\'" if ($branch);
1044         $strsth .=" AND borrowers.branchcode like \'". C4::Context->userenv->{branch} . "\'"
1045             if (C4::Context->preference("IndependantBranches") && C4::Context->userenv->{flags} != 1 );
1046         $strsth .=" ORDER BY latesince,basketno,borrowers.branchcode, supplier";
1047     }
1048     my $sth = $dbh->prepare($strsth);
1049     $sth->execute;
1050     my @results;
1051     my $hilighted = 1;
1052     while ( my $data = $sth->fetchrow_hashref ) {
1053         $data->{hilighted} = $hilighted if ( $hilighted > 0 );
1054         $data->{orderdate} = format_date( $data->{orderdate} );
1055         push @results, $data;
1056         $hilighted = -$hilighted;
1057     }
1058     $sth->finish;
1059     return @results;
1060 }
1061
1062 #------------------------------------------------------------#
1063
1064 =head3 GetHistory
1065
1066 =over 4
1067
1068 (\@order_loop, $total_qty, $total_price, $total_qtyreceived)=&GetHistory( $title, $author, $name, $from_placed_on, $to_placed_on )
1069
1070 this function get the search history.
1071
1072 =back
1073
1074 =cut
1075
1076 sub GetHistory {
1077     my ( $title, $author, $name, $from_placed_on, $to_placed_on ) = @_;
1078     my @order_loop;
1079     my $total_qty         = 0;
1080     my $total_qtyreceived = 0;
1081     my $total_price       = 0;
1082
1083 # don't run the query if there are no parameters (list would be too long for sure !)
1084     if ( $title || $author || $name || $from_placed_on || $to_placed_on ) {
1085         my $dbh   = C4::Context->dbh;
1086         my $query ="
1087             SELECT
1088                 biblio.title,
1089                 biblio.author,
1090                 aqorders.basketno,
1091                 name,aqbasket.creationdate,
1092                 aqorders.datereceived,
1093                 aqorders.quantity,
1094                 aqorders.quantityreceived,
1095                 aqorders.ecost,
1096                 aqorders.ordernumber,
1097                 aqorders.booksellerinvoicenumber as invoicenumber,
1098                 aqbooksellers.id as id,
1099                 aqorders.biblionumber
1100             FROM aqorders 
1101             LEFT JOIN aqbasket ON aqorders.basketno=aqbasket.basketno 
1102             LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
1103             LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber";
1104
1105         $query .= " LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber"
1106           if ( C4::Context->preference("IndependantBranches") );
1107
1108         $query .= " WHERE 1 ";
1109         $query .= " AND biblio.title LIKE " . $dbh->quote( "%" . $title . "%" )
1110           if $title;
1111
1112         $query .=
1113           " AND biblio.author LIKE " . $dbh->quote( "%" . $author . "%" )
1114           if $author;
1115
1116         $query .= " AND name LIKE " . $dbh->quote( "%" . $name . "%" ) if $name;
1117
1118         $query .= " AND creationdate >" . $dbh->quote($from_placed_on)
1119           if $from_placed_on;
1120
1121         $query .= " AND creationdate<" . $dbh->quote($to_placed_on)
1122           if $to_placed_on;
1123         $query .= " AND (datecancellationprinted is NULL or datecancellationprinted='0000-00-00')";
1124
1125         if ( C4::Context->preference("IndependantBranches") ) {
1126             my $userenv = C4::Context->userenv;
1127             if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1128                 $query .=
1129                     " AND (borrowers.branchcode = '"
1130                   . $userenv->{branch}
1131                   . "' OR borrowers.branchcode ='')";
1132             }
1133         }
1134         $query .= " ORDER BY booksellerid";
1135         my $sth = $dbh->prepare($query);
1136         $sth->execute;
1137         my $cnt = 1;
1138         while ( my $line = $sth->fetchrow_hashref ) {
1139             $line->{count} = $cnt++;
1140             $line->{toggle} = 1 if $cnt % 2;
1141             push @order_loop, $line;
1142             $line->{creationdate} = format_date( $line->{creationdate} );
1143             $line->{datereceived} = format_date( $line->{datereceived} );
1144             $total_qty         += $line->{'quantity'};
1145             $total_qtyreceived += $line->{'quantityreceived'};
1146             $total_price       += $line->{'quantity'} * $line->{'ecost'};
1147         }
1148     }
1149     return \@order_loop, $total_qty, $total_price, $total_qtyreceived;
1150 }
1151
1152 =head2 GetRecentAcqui
1153
1154    $results = GetRecentAcqui($days);
1155
1156    C<$results> is a ref to a table which containts hashref
1157
1158 =cut
1159
1160 sub GetRecentAcqui {
1161     my $limit  = shift;
1162     my $dbh    = C4::Context->dbh;
1163     my $query = "
1164         SELECT *
1165         FROM   biblio
1166         ORDER BY timestamp DESC
1167         LIMIT  0,".$limit;
1168
1169     my $sth = $dbh->prepare($query);
1170     $sth->execute;
1171     my @results;
1172     while(my $data = $sth->fetchrow_hashref){
1173         push @results,$data;
1174     }
1175     return \@results;
1176 }
1177
1178 END { }    # module clean-up code here (global destructor)
1179
1180 1;
1181
1182 __END__
1183
1184 =back
1185
1186 =head1 AUTHOR
1187
1188 Koha Developement team <info@koha.org>
1189
1190 =cut