Bug 7213 - simple /svc/ HTTP example
[koha.git] / C4 / Acquisition.pm
blobe881a166a312946d65d83933fdc3f45c5f6efbff
1 package C4::Acquisition;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
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.
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.
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.
21 use strict;
22 use warnings;
23 use Carp;
24 use C4::Context;
25 use C4::Debug;
26 use C4::Dates qw(format_date format_date_in_iso);
27 use MARC::Record;
28 use C4::Suggestions;
29 use C4::Biblio;
30 use C4::Debug;
31 use C4::SQLHelper qw(InsertInTable);
33 use Time::localtime;
34 use HTML::Entities;
36 use vars qw($VERSION @ISA @EXPORT);
38 BEGIN {
39 # set the version for version checking
40 $VERSION = 3.01;
41 require Exporter;
42 @ISA = qw(Exporter);
43 @EXPORT = qw(
44 &GetBasket &NewBasket &CloseBasket &DelBasket &ModBasket
45 &GetBasketAsCSV
46 &GetBasketsByBookseller &GetBasketsByBasketgroup
47 &GetBasketsInfosByBookseller
49 &ModBasketHeader
51 &ModBasketgroup &NewBasketgroup &DelBasketgroup &GetBasketgroup &CloseBasketgroup
52 &GetBasketgroups &ReOpenBasketgroup
54 &NewOrder &DelOrder &ModOrder &GetPendingOrders &GetOrder &GetOrders
55 &GetOrderNumber &GetLateOrders &GetOrderFromItemnumber
56 &SearchOrder &GetHistory &GetRecentAcqui
57 &ModReceiveOrder &ModOrderBiblioitemNumber
58 &GetCancelledOrders
60 &NewOrderItem &ModOrderItem
62 &GetParcels &GetParcel
63 &GetContracts &GetContract
65 &GetItemnumbersFromOrder
67 &AddClaim
75 sub GetOrderFromItemnumber {
76 my ($itemnumber) = @_;
77 my $dbh = C4::Context->dbh;
78 my $query = qq|
80 SELECT * from aqorders LEFT JOIN aqorders_items
81 ON ( aqorders.ordernumber = aqorders_items.ordernumber )
82 WHERE itemnumber = ? |;
84 my $sth = $dbh->prepare($query);
86 # $sth->trace(3);
88 $sth->execute($itemnumber);
90 my $order = $sth->fetchrow_hashref;
91 return ( $order );
95 # Returns the itemnumber(s) associated with the ordernumber given in parameter
96 sub GetItemnumbersFromOrder {
97 my ($ordernumber) = @_;
98 my $dbh = C4::Context->dbh;
99 my $query = "SELECT itemnumber FROM aqorders_items WHERE ordernumber=?";
100 my $sth = $dbh->prepare($query);
101 $sth->execute($ordernumber);
102 my @tab;
104 while (my $order = $sth->fetchrow_hashref) {
105 push @tab, $order->{'itemnumber'};
108 return @tab;
117 =head1 NAME
119 C4::Acquisition - Koha functions for dealing with orders and acquisitions
121 =head1 SYNOPSIS
123 use C4::Acquisition;
125 =head1 DESCRIPTION
127 The functions in this module deal with acquisitions, managing book
128 orders, basket and parcels.
130 =head1 FUNCTIONS
132 =head2 FUNCTIONS ABOUT BASKETS
134 =head3 GetBasket
136 $aqbasket = &GetBasket($basketnumber);
138 get all basket informations in aqbasket for a given basket
140 B<returns:> informations for a given basket returned as a hashref.
142 =cut
144 sub GetBasket {
145 my ($basketno) = @_;
146 my $dbh = C4::Context->dbh;
147 my $query = "
148 SELECT aqbasket.*,
149 concat( b.firstname,' ',b.surname) AS authorisedbyname,
150 b.branchcode AS branch
151 FROM aqbasket
152 LEFT JOIN borrowers b ON aqbasket.authorisedby=b.borrowernumber
153 WHERE basketno=?
155 my $sth=$dbh->prepare($query);
156 $sth->execute($basketno);
157 my $basket = $sth->fetchrow_hashref;
158 return ( $basket );
161 #------------------------------------------------------------#
163 =head3 NewBasket
165 $basket = &NewBasket( $booksellerid, $authorizedby, $basketname,
166 $basketnote, $basketbooksellernote, $basketcontractnumber );
168 Create a new basket in aqbasket table
170 =over
172 =item C<$booksellerid> is a foreign key in the aqbasket table
174 =item C<$authorizedby> is the username of who created the basket
176 =back
178 The other parameters are optional, see ModBasketHeader for more info on them.
180 =cut
182 # FIXME : this function seems to be unused.
184 sub NewBasket {
185 my ( $booksellerid, $authorisedby, $basketname, $basketnote, $basketbooksellernote, $basketcontractnumber ) = @_;
186 my $dbh = C4::Context->dbh;
187 my $query = "
188 INSERT INTO aqbasket
189 (creationdate,booksellerid,authorisedby)
190 VALUES (now(),'$booksellerid','$authorisedby')
192 my $sth =
193 $dbh->do($query);
194 #find & return basketno MYSQL dependant, but $dbh->last_insert_id always returns null :-(
195 my $basket = $dbh->{'mysql_insertid'};
196 ModBasketHeader($basket, $basketname || '', $basketnote || '', $basketbooksellernote || '', $basketcontractnumber || undef);
197 return $basket;
200 #------------------------------------------------------------#
202 =head3 CloseBasket
204 &CloseBasket($basketno);
206 close a basket (becomes unmodifiable,except for recieves)
208 =cut
210 sub CloseBasket {
211 my ($basketno) = @_;
212 my $dbh = C4::Context->dbh;
213 my $query = "
214 UPDATE aqbasket
215 SET closedate=now()
216 WHERE basketno=?
218 my $sth = $dbh->prepare($query);
219 $sth->execute($basketno);
222 #------------------------------------------------------------#
224 =head3 GetBasketAsCSV
226 &GetBasketAsCSV($basketno);
228 Export a basket as CSV
230 =cut
232 sub GetBasketAsCSV {
233 my ($basketno) = @_;
234 my $basket = GetBasket($basketno);
235 my @orders = GetOrders($basketno);
236 my $contract = GetContract($basket->{'contractnumber'});
237 my $csv = Text::CSV->new();
238 my $output;
240 # TODO: Translate headers
241 my @headers = qw(contractname ordernumber entrydate isbn author title publishercode collectiontitle notes quantity rrp);
243 $csv->combine(@headers);
244 $output = $csv->string() . "\n";
246 my @rows;
247 foreach my $order (@orders) {
248 my @cols;
249 # newlines are not valid characters for Text::CSV combine()
250 $order->{'notes'} =~ s/[\r\n]+//g;
251 push(@cols,
252 $contract->{'contractname'},
253 $order->{'ordernumber'},
254 $order->{'entrydate'},
255 $order->{'isbn'},
256 $order->{'author'},
257 $order->{'title'},
258 $order->{'publishercode'},
259 $order->{'collectiontitle'},
260 $order->{'notes'},
261 $order->{'quantity'},
262 $order->{'rrp'},
264 push (@rows, \@cols);
267 foreach my $row (@rows) {
268 $csv->combine(@$row);
269 $output .= $csv->string() . "\n";
273 return $output;
278 =head3 CloseBasketgroup
280 &CloseBasketgroup($basketgroupno);
282 close a basketgroup
284 =cut
286 sub CloseBasketgroup {
287 my ($basketgroupno) = @_;
288 my $dbh = C4::Context->dbh;
289 my $sth = $dbh->prepare("
290 UPDATE aqbasketgroups
291 SET closed=1
292 WHERE id=?
294 $sth->execute($basketgroupno);
297 #------------------------------------------------------------#
299 =head3 ReOpenBaskergroup($basketgroupno)
301 &ReOpenBaskergroup($basketgroupno);
303 reopen a basketgroup
305 =cut
307 sub ReOpenBasketgroup {
308 my ($basketgroupno) = @_;
309 my $dbh = C4::Context->dbh;
310 my $sth = $dbh->prepare("
311 UPDATE aqbasketgroups
312 SET closed=0
313 WHERE id=?
315 $sth->execute($basketgroupno);
318 #------------------------------------------------------------#
321 =head3 DelBasket
323 &DelBasket($basketno);
325 Deletes the basket that has basketno field $basketno in the aqbasket table.
327 =over
329 =item C<$basketno> is the primary key of the basket in the aqbasket table.
331 =back
333 =cut
335 sub DelBasket {
336 my ( $basketno ) = @_;
337 my $query = "DELETE FROM aqbasket WHERE basketno=?";
338 my $dbh = C4::Context->dbh;
339 my $sth = $dbh->prepare($query);
340 $sth->execute($basketno);
341 $sth->finish;
344 #------------------------------------------------------------#
346 =head3 ModBasket
348 &ModBasket($basketinfo);
350 Modifies a basket, using a hashref $basketinfo for the relevant information, only $basketinfo->{'basketno'} is required.
352 =over
354 =item C<$basketno> is the primary key of the basket in the aqbasket table.
356 =back
358 =cut
360 sub ModBasket {
361 my $basketinfo = shift;
362 my $query = "UPDATE aqbasket SET ";
363 my @params;
364 foreach my $key (keys %$basketinfo){
365 if ($key ne 'basketno'){
366 $query .= "$key=?, ";
367 push(@params, $basketinfo->{$key} || undef );
370 # get rid of the "," at the end of $query
371 if (substr($query, length($query)-2) eq ', '){
372 chop($query);
373 chop($query);
374 $query .= ' ';
376 $query .= "WHERE basketno=?";
377 push(@params, $basketinfo->{'basketno'});
378 my $dbh = C4::Context->dbh;
379 my $sth = $dbh->prepare($query);
380 $sth->execute(@params);
381 $sth->finish;
384 #------------------------------------------------------------#
386 =head3 ModBasketHeader
388 &ModBasketHeader($basketno, $basketname, $note, $booksellernote, $contractnumber);
390 Modifies a basket's header.
392 =over
394 =item C<$basketno> is the "basketno" field in the "aqbasket" table;
396 =item C<$basketname> is the "basketname" field in the "aqbasket" table;
398 =item C<$note> is the "note" field in the "aqbasket" table;
400 =item C<$booksellernote> is the "booksellernote" field in the "aqbasket" table;
402 =item C<$contractnumber> is the "contractnumber" (foreign) key in the "aqbasket" table.
404 =back
406 =cut
408 sub ModBasketHeader {
409 my ($basketno, $basketname, $note, $booksellernote, $contractnumber) = @_;
410 my $query = "UPDATE aqbasket SET basketname=?, note=?, booksellernote=? WHERE basketno=?";
411 my $dbh = C4::Context->dbh;
412 my $sth = $dbh->prepare($query);
413 $sth->execute($basketname,$note,$booksellernote,$basketno);
414 if ( $contractnumber ) {
415 my $query2 ="UPDATE aqbasket SET contractnumber=? WHERE basketno=?";
416 my $sth2 = $dbh->prepare($query2);
417 $sth2->execute($contractnumber,$basketno);
418 $sth2->finish;
420 $sth->finish;
423 #------------------------------------------------------------#
425 =head3 GetBasketsByBookseller
427 @results = &GetBasketsByBookseller($booksellerid, $extra);
429 Returns a list of hashes of all the baskets that belong to bookseller 'booksellerid'.
431 =over
433 =item C<$booksellerid> is the 'id' field of the bookseller in the aqbooksellers table
435 =item C<$extra> is the extra sql parameters, can be
437 $extra->{groupby}: group baskets by column
438 ex. $extra->{groupby} = aqbasket.basketgroupid
439 $extra->{orderby}: order baskets by column
440 $extra->{limit}: limit number of results (can be helpful for pagination)
442 =back
444 =cut
446 sub GetBasketsByBookseller {
447 my ($booksellerid, $extra) = @_;
448 my $query = "SELECT * FROM aqbasket WHERE booksellerid=?";
449 if ($extra){
450 if ($extra->{groupby}) {
451 $query .= " GROUP by $extra->{groupby}";
453 if ($extra->{orderby}){
454 $query .= " ORDER by $extra->{orderby}";
456 if ($extra->{limit}){
457 $query .= " LIMIT $extra->{limit}";
460 my $dbh = C4::Context->dbh;
461 my $sth = $dbh->prepare($query);
462 $sth->execute($booksellerid);
463 my $results = $sth->fetchall_arrayref({});
464 $sth->finish;
465 return $results
468 =head3 GetBasketsInfosByBookseller
470 my $baskets = GetBasketsInfosByBookseller($supplierid);
472 Returns in a arrayref of hashref all about booksellers baskets, plus:
473 total_biblios: Number of distinct biblios in basket
474 total_items: Number of items in basket
475 expected_items: Number of non-received items in basket
477 =cut
479 sub GetBasketsInfosByBookseller {
480 my ($supplierid) = @_;
482 return unless $supplierid;
484 my $dbh = C4::Context->dbh;
485 my $query = qq{
486 SELECT aqbasket.*,
487 SUM(aqorders.quantity) AS total_items,
488 COUNT(DISTINCT aqorders.biblionumber) AS total_biblios,
489 SUM(IF(aqorders.datereceived IS NULL, aqorders.quantity, 0)) AS expected_items
490 FROM aqbasket
491 LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
492 WHERE booksellerid = ?
493 GROUP BY aqbasket.basketno
495 my $sth = $dbh->prepare($query);
496 $sth->execute($supplierid);
497 return $sth->fetchall_arrayref({});
501 #------------------------------------------------------------#
503 =head3 GetBasketsByBasketgroup
505 $baskets = &GetBasketsByBasketgroup($basketgroupid);
507 Returns a reference to all baskets that belong to basketgroup $basketgroupid.
509 =cut
511 sub GetBasketsByBasketgroup {
512 my $basketgroupid = shift;
513 my $query = "SELECT * FROM aqbasket
514 LEFT JOIN aqcontract USING(contractnumber) WHERE basketgroupid=?";
515 my $dbh = C4::Context->dbh;
516 my $sth = $dbh->prepare($query);
517 $sth->execute($basketgroupid);
518 my $results = $sth->fetchall_arrayref({});
519 $sth->finish;
520 return $results
523 #------------------------------------------------------------#
525 =head3 NewBasketgroup
527 $basketgroupid = NewBasketgroup(\%hashref);
529 Adds a basketgroup to the aqbasketgroups table, and add the initial baskets to it.
531 $hashref->{'booksellerid'} is the 'id' field of the bookseller in the aqbooksellers table,
533 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
535 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
537 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
539 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
541 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
543 =cut
545 sub NewBasketgroup {
546 my $basketgroupinfo = shift;
547 die "booksellerid is required to create a basketgroup" unless $basketgroupinfo->{'booksellerid'};
548 my $query = "INSERT INTO aqbasketgroups (";
549 my @params;
550 foreach my $field ('name', 'deliveryplace', 'deliverycomment', 'closed') {
551 if ( $basketgroupinfo->{$field} ) {
552 $query .= "$field, ";
553 push(@params, $basketgroupinfo->{$field});
556 $query .= "booksellerid) VALUES (";
557 foreach (@params) {
558 $query .= "?, ";
560 $query .= "?)";
561 push(@params, $basketgroupinfo->{'booksellerid'});
562 my $dbh = C4::Context->dbh;
563 my $sth = $dbh->prepare($query);
564 $sth->execute(@params);
565 my $basketgroupid = $dbh->{'mysql_insertid'};
566 if( $basketgroupinfo->{'basketlist'} ) {
567 foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
568 my $query2 = "UPDATE aqbasket SET basketgroupid=? WHERE basketno=?";
569 my $sth2 = $dbh->prepare($query2);
570 $sth2->execute($basketgroupid, $basketno);
573 return $basketgroupid;
576 #------------------------------------------------------------#
578 =head3 ModBasketgroup
580 ModBasketgroup(\%hashref);
582 Modifies a basketgroup in the aqbasketgroups table, and add the baskets to it.
584 $hashref->{'id'} is the 'id' field of the basketgroup in the aqbasketgroup table, this parameter is mandatory,
586 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
588 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
590 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
592 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
594 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
596 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
598 =cut
600 sub ModBasketgroup {
601 my $basketgroupinfo = shift;
602 die "basketgroup id is required to edit a basketgroup" unless $basketgroupinfo->{'id'};
603 my $dbh = C4::Context->dbh;
604 my $query = "UPDATE aqbasketgroups SET ";
605 my @params;
606 foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
607 if ( defined $basketgroupinfo->{$field} ) {
608 $query .= "$field=?, ";
609 push(@params, $basketgroupinfo->{$field});
612 chop($query);
613 chop($query);
614 $query .= " WHERE id=?";
615 push(@params, $basketgroupinfo->{'id'});
616 my $sth = $dbh->prepare($query);
617 $sth->execute(@params);
619 $sth = $dbh->prepare('UPDATE aqbasket SET basketgroupid = NULL WHERE basketgroupid = ?');
620 $sth->execute($basketgroupinfo->{'id'});
622 if($basketgroupinfo->{'basketlist'} && @{$basketgroupinfo->{'basketlist'}}){
623 $sth = $dbh->prepare("UPDATE aqbasket SET basketgroupid=? WHERE basketno=?");
624 foreach my $basketno (@{$basketgroupinfo->{'basketlist'}}) {
625 $sth->execute($basketgroupinfo->{'id'}, $basketno);
626 $sth->finish;
629 $sth->finish;
632 #------------------------------------------------------------#
634 =head3 DelBasketgroup
636 DelBasketgroup($basketgroupid);
638 Deletes a basketgroup in the aqbasketgroups table, and removes the reference to it from the baskets,
640 =over
642 =item C<$basketgroupid> is the 'id' field of the basket in the aqbasketgroup table
644 =back
646 =cut
648 sub DelBasketgroup {
649 my $basketgroupid = shift;
650 die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
651 my $query = "DELETE FROM aqbasketgroups WHERE id=?";
652 my $dbh = C4::Context->dbh;
653 my $sth = $dbh->prepare($query);
654 $sth->execute($basketgroupid);
655 $sth->finish;
658 #------------------------------------------------------------#
661 =head2 FUNCTIONS ABOUT ORDERS
663 =head3 GetBasketgroup
665 $basketgroup = &GetBasketgroup($basketgroupid);
667 Returns a reference to the hash containing all infermation about the basketgroup.
669 =cut
671 sub GetBasketgroup {
672 my $basketgroupid = shift;
673 die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
674 my $query = "SELECT * FROM aqbasketgroups WHERE id=?";
675 my $dbh = C4::Context->dbh;
676 my $sth = $dbh->prepare($query);
677 $sth->execute($basketgroupid);
678 my $result = $sth->fetchrow_hashref;
679 $sth->finish;
680 return $result
683 #------------------------------------------------------------#
685 =head3 GetBasketgroups
687 $basketgroups = &GetBasketgroups($booksellerid);
689 Returns a reference to the array of all the basketgroups of bookseller $booksellerid.
691 =cut
693 sub GetBasketgroups {
694 my $booksellerid = shift;
695 die "bookseller id is required to edit a basketgroup" unless $booksellerid;
696 my $query = "SELECT * FROM aqbasketgroups WHERE booksellerid=? ORDER BY `id` DESC";
697 my $dbh = C4::Context->dbh;
698 my $sth = $dbh->prepare($query);
699 $sth->execute($booksellerid);
700 my $results = $sth->fetchall_arrayref({});
701 $sth->finish;
702 return $results
705 #------------------------------------------------------------#
707 =head2 FUNCTIONS ABOUT ORDERS
709 =cut
711 #------------------------------------------------------------#
713 =head3 GetPendingOrders
715 $orders = &GetPendingOrders($booksellerid, $grouped, $owner);
717 Finds pending orders from the bookseller with the given ID. Ignores
718 completed and cancelled orders.
720 C<$booksellerid> contains the bookseller identifier
721 C<$grouped> contains 0 or 1. 0 means returns the list, 1 means return the total
722 C<$owner> contains 0 or 1. 0 means any owner. 1 means only the list of orders entered by the user itself.
724 C<$orders> is a reference-to-array; each element is a
725 reference-to-hash with the following fields:
726 C<$grouped> is a boolean that, if set to 1 will group all order lines of the same basket
727 in a single result line
729 =over
731 =item C<authorizedby>
733 =item C<entrydate>
735 =item C<basketno>
737 =back
739 These give the value of the corresponding field in the aqorders table
740 of the Koha database.
742 Results are ordered from most to least recent.
744 =cut
746 sub GetPendingOrders {
747 my ($supplierid,$grouped,$owner,$basketno) = @_;
748 my $dbh = C4::Context->dbh;
749 my $strsth = "
750 SELECT ".($grouped?"count(*),":"")."aqbasket.basketno,
751 surname,firstname,biblio.*,biblioitems.isbn,
752 aqbasket.closedate, aqbasket.creationdate, aqbasket.basketname,
753 aqorders.*
754 FROM aqorders
755 LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
756 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
757 LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
758 LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
759 WHERE booksellerid=?
760 AND (quantity > quantityreceived OR quantityreceived is NULL)
761 AND datecancellationprinted IS NULL";
762 my @query_params = ( $supplierid );
763 my $userenv = C4::Context->userenv;
764 if ( C4::Context->preference("IndependantBranches") ) {
765 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
766 $strsth .= " and (borrowers.branchcode = ?
767 or borrowers.branchcode = '')";
768 push @query_params, $userenv->{branch};
771 if ($owner) {
772 $strsth .= " AND aqbasket.authorisedby=? ";
773 push @query_params, $userenv->{'number'};
775 if ($basketno) {
776 $strsth .= " AND aqbasket.basketno=? ";
777 push @query_params, $basketno;
779 $strsth .= " group by aqbasket.basketno" if $grouped;
780 $strsth .= " order by aqbasket.basketno";
782 my $sth = $dbh->prepare($strsth);
783 $sth->execute( @query_params );
784 my $results = $sth->fetchall_arrayref({});
785 $sth->finish;
786 return $results;
789 #------------------------------------------------------------#
791 =head3 GetOrders
793 @orders = &GetOrders($basketnumber, $orderby);
795 Looks up the pending (non-cancelled) orders with the given basket
796 number. If C<$booksellerID> is non-empty, only orders from that seller
797 are returned.
799 return :
800 C<&basket> returns a two-element array. C<@orders> is an array of
801 references-to-hash, whose keys are the fields from the aqorders,
802 biblio, and biblioitems tables in the Koha database.
804 =cut
806 sub GetOrders {
807 my ( $basketno, $orderby ) = @_;
808 my $dbh = C4::Context->dbh;
809 my $query ="
810 SELECT biblio.*,biblioitems.*,
811 aqorders.*,
812 aqbudgets.*,
813 biblio.title
814 FROM aqorders
815 LEFT JOIN aqbudgets ON aqbudgets.budget_id = aqorders.budget_id
816 LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
817 LEFT JOIN biblioitems ON biblioitems.biblionumber =biblio.biblionumber
818 WHERE basketno=?
819 AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
822 $orderby = "biblioitems.publishercode,biblio.title" unless $orderby;
823 $query .= " ORDER BY $orderby";
824 my $sth = $dbh->prepare($query);
825 $sth->execute($basketno);
826 my $results = $sth->fetchall_arrayref({});
827 $sth->finish;
828 return @$results;
831 #------------------------------------------------------------#
833 =head3 GetOrderNumber
835 $ordernumber = &GetOrderNumber($biblioitemnumber, $biblionumber);
837 Looks up the ordernumber with the given biblionumber and biblioitemnumber.
839 Returns the number of this order.
841 =over
843 =item C<$ordernumber> is the order number.
845 =back
847 =cut
849 sub GetOrderNumber {
850 my ( $biblionumber,$biblioitemnumber ) = @_;
851 my $dbh = C4::Context->dbh;
852 my $query = "
853 SELECT ordernumber
854 FROM aqorders
855 WHERE biblionumber=?
856 AND biblioitemnumber=?
858 my $sth = $dbh->prepare($query);
859 $sth->execute( $biblionumber, $biblioitemnumber );
861 return $sth->fetchrow;
864 #------------------------------------------------------------#
866 =head3 GetOrder
868 $order = &GetOrder($ordernumber);
870 Looks up an order by order number.
872 Returns a reference-to-hash describing the order. The keys of
873 C<$order> are fields from the biblio, biblioitems, aqorders tables of the Koha database.
875 =cut
877 sub GetOrder {
878 my ($ordernumber) = @_;
879 my $dbh = C4::Context->dbh;
880 my $query = "
881 SELECT biblioitems.*, biblio.*, aqorders.*
882 FROM aqorders
883 LEFT JOIN biblio on biblio.biblionumber=aqorders.biblionumber
884 LEFT JOIN biblioitems on biblioitems.biblionumber=aqorders.biblionumber
885 WHERE aqorders.ordernumber=?
888 my $sth= $dbh->prepare($query);
889 $sth->execute($ordernumber);
890 my $data = $sth->fetchrow_hashref;
891 $sth->finish;
892 return $data;
895 #------------------------------------------------------------#
897 =head3 NewOrder
899 &NewOrder(\%hashref);
901 Adds a new order to the database. Any argument that isn't described
902 below is the new value of the field with the same name in the aqorders
903 table of the Koha database.
905 =over
907 =item $hashref->{'basketno'} is the basketno foreign key in aqorders, it is mandatory
909 =item $hashref->{'ordernumber'} is a "minimum order number."
911 =item $hashref->{'budgetdate'} is effectively ignored.
912 If it's undef (anything false) or the string 'now', the current day is used.
913 Else, the upcoming July 1st is used.
915 =item $hashref->{'subscription'} may be either "yes", or anything else for "no".
917 =item $hashref->{'uncertainprice'} may be 0 for "the price is known" or 1 for "the price is uncertain"
919 =item defaults entrydate to Now
921 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".
923 =back
925 =cut
927 sub NewOrder {
928 my $orderinfo = shift;
929 #### ------------------------------
930 my $dbh = C4::Context->dbh;
931 my @params;
934 # if these parameters are missing, we can't continue
935 for my $key (qw/basketno quantity biblionumber budget_id/) {
936 croak "Mandatory parameter $key missing" unless $orderinfo->{$key};
939 if ( defined $orderinfo->{subscription} && $orderinfo->{'subscription'} eq 'yes' ) {
940 $orderinfo->{'subscription'} = 1;
941 } else {
942 $orderinfo->{'subscription'} = 0;
944 $orderinfo->{'entrydate'} ||= C4::Dates->new()->output("iso");
945 if (!$orderinfo->{quantityreceived}) {
946 $orderinfo->{quantityreceived} = 0;
949 my $ordernumber=InsertInTable("aqorders",$orderinfo);
950 return ( $orderinfo->{'basketno'}, $ordernumber );
955 #------------------------------------------------------------#
957 =head3 NewOrderItem
959 &NewOrderItem();
961 =cut
963 sub NewOrderItem {
964 my ($itemnumber, $ordernumber) = @_;
965 my $dbh = C4::Context->dbh;
966 my $query = qq|
967 INSERT INTO aqorders_items
968 (itemnumber, ordernumber)
969 VALUES (?,?) |;
971 my $sth = $dbh->prepare($query);
972 $sth->execute( $itemnumber, $ordernumber);
975 #------------------------------------------------------------#
977 =head3 ModOrder
979 &ModOrder(\%hashref);
981 Modifies an existing order. Updates the order with order number
982 $hashref->{'ordernumber'} and biblionumber $hashref->{'biblionumber'}. All
983 other keys of the hash update the fields with the same name in the aqorders
984 table of the Koha database.
986 =cut
988 sub ModOrder {
989 my $orderinfo = shift;
991 die "Ordernumber is required" if $orderinfo->{'ordernumber'} eq '' ;
992 die "Biblionumber is required" if $orderinfo->{'biblionumber'} eq '';
994 my $dbh = C4::Context->dbh;
995 my @params;
997 # update uncertainprice to an integer, just in case (under FF, checked boxes have the value "ON" by default)
998 $orderinfo->{uncertainprice}=1 if $orderinfo->{uncertainprice};
1000 # delete($orderinfo->{'branchcode'});
1001 # the hash contains a lot of entries not in aqorders, so get the columns ...
1002 my $sth = $dbh->prepare("SELECT * FROM aqorders LIMIT 1;");
1003 $sth->execute;
1004 my $colnames = $sth->{NAME};
1005 my $query = "UPDATE aqorders SET ";
1007 foreach my $orderinfokey (grep(!/ordernumber/, keys %$orderinfo)){
1008 # ... and skip hash entries that are not in the aqorders table
1009 # FIXME : probably not the best way to do it (would be better to have a correct hash)
1010 next unless grep(/^$orderinfokey$/, @$colnames);
1011 $query .= "$orderinfokey=?, ";
1012 push(@params, $orderinfo->{$orderinfokey});
1015 $query .= "timestamp=NOW() WHERE ordernumber=?";
1016 # push(@params, $specorderinfo{'ordernumber'});
1017 push(@params, $orderinfo->{'ordernumber'} );
1018 $sth = $dbh->prepare($query);
1019 $sth->execute(@params);
1020 $sth->finish;
1023 #------------------------------------------------------------#
1025 =head3 ModOrderItem
1027 &ModOrderItem(\%hashref);
1029 Modifies the itemnumber in the aqorders_items table. The input hash needs three entities:
1031 =over
1033 =item - itemnumber: the old itemnumber
1034 =item - ordernumber: the order this item is attached to
1035 =item - newitemnumber: the new itemnumber we want to attach the line to
1037 =back
1039 =cut
1041 sub ModOrderItem {
1042 my $orderiteminfo = shift;
1043 if (! $orderiteminfo->{'ordernumber'} || ! $orderiteminfo->{'itemnumber'} || ! $orderiteminfo->{'newitemnumber'}){
1044 die "Ordernumber, itemnumber and newitemnumber is required";
1047 my $dbh = C4::Context->dbh;
1049 my $query = "UPDATE aqorders_items set itemnumber=? where itemnumber=? and ordernumber=?";
1050 my @params = ($orderiteminfo->{'newitemnumber'}, $orderiteminfo->{'itemnumber'}, $orderiteminfo->{'ordernumber'});
1051 my $sth = $dbh->prepare($query);
1052 $sth->execute(@params);
1053 return 0;
1056 #------------------------------------------------------------#
1059 =head3 ModOrderBibliotemNumber
1061 &ModOrderBiblioitemNumber($biblioitemnumber,$ordernumber, $biblionumber);
1063 Modifies the biblioitemnumber for an existing order.
1064 Updates the order with order number C<$ordernum> and biblionumber C<$biblionumber>.
1066 =cut
1068 #FIXME: is this used at all?
1069 sub ModOrderBiblioitemNumber {
1070 my ($biblioitemnumber,$ordernumber, $biblionumber) = @_;
1071 my $dbh = C4::Context->dbh;
1072 my $query = "
1073 UPDATE aqorders
1074 SET biblioitemnumber = ?
1075 WHERE ordernumber = ?
1076 AND biblionumber = ?";
1077 my $sth = $dbh->prepare($query);
1078 $sth->execute( $biblioitemnumber, $ordernumber, $biblionumber );
1081 =head3 GetCancelledOrders
1083 my @orders = GetCancelledOrders($basketno, $orderby);
1085 Returns cancelled orders for a basket
1087 =cut
1089 sub GetCancelledOrders {
1090 my ( $basketno, $orderby ) = @_;
1092 return () unless $basketno;
1094 my $dbh = C4::Context->dbh;
1095 my $query = "
1096 SELECT biblio.*, biblioitems.*, aqorders.*, aqbudgets.*
1097 FROM aqorders
1098 LEFT JOIN aqbudgets ON aqbudgets.budget_id = aqorders.budget_id
1099 LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1100 LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
1101 WHERE basketno = ?
1102 AND (datecancellationprinted IS NOT NULL
1103 AND datecancellationprinted <> '0000-00-00')
1106 $orderby = "aqorders.datecancellationprinted desc, aqorders.timestamp desc"
1107 unless $orderby;
1108 $query .= " ORDER BY $orderby";
1109 my $sth = $dbh->prepare($query);
1110 $sth->execute($basketno);
1111 my $results = $sth->fetchall_arrayref( {} );
1113 return @$results;
1117 #------------------------------------------------------------#
1119 =head3 ModReceiveOrder
1121 &ModReceiveOrder($biblionumber, $ordernumber, $quantityreceived, $user,
1122 $unitprice, $booksellerinvoicenumber, $biblioitemnumber,
1123 $freight, $bookfund, $rrp);
1125 Updates an order, to reflect the fact that it was received, at least
1126 in part. All arguments not mentioned below update the fields with the
1127 same name in the aqorders table of the Koha database.
1129 If a partial order is received, splits the order into two. The received
1130 portion must have a booksellerinvoicenumber.
1132 Updates the order with bibilionumber C<$biblionumber> and ordernumber
1133 C<$ordernumber>.
1135 =cut
1138 sub ModReceiveOrder {
1139 my (
1140 $biblionumber, $ordernumber, $quantrec, $user, $cost,
1141 $invoiceno, $freight, $rrp, $budget_id, $datereceived
1143 = @_;
1144 my $dbh = C4::Context->dbh;
1145 $datereceived = C4::Dates->output('iso') unless $datereceived;
1146 my $suggestionid = GetSuggestionFromBiblionumber( $biblionumber );
1147 if ($suggestionid) {
1148 ModSuggestion( {suggestionid=>$suggestionid,
1149 STATUS=>'AVAILABLE',
1150 biblionumber=> $biblionumber}
1154 my $sth=$dbh->prepare("
1155 SELECT * FROM aqorders
1156 WHERE biblionumber=? AND aqorders.ordernumber=?");
1158 $sth->execute($biblionumber,$ordernumber);
1159 my $order = $sth->fetchrow_hashref();
1160 $sth->finish();
1162 if ( $order->{quantity} > $quantrec ) {
1163 $sth=$dbh->prepare("
1164 UPDATE aqorders
1165 SET quantityreceived=?
1166 , datereceived=?
1167 , booksellerinvoicenumber=?
1168 , unitprice=?
1169 , freight=?
1170 , rrp=?
1171 , quantity=?
1172 WHERE biblionumber=? AND ordernumber=?");
1174 $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$quantrec,$biblionumber,$ordernumber);
1175 $sth->finish;
1177 # create a new order for the remaining items, and set its bookfund.
1178 foreach my $orderkey ( "linenumber", "allocation" ) {
1179 delete($order->{'$orderkey'});
1181 $order->{'quantity'} -= $quantrec;
1182 $order->{'quantityreceived'} = 0;
1183 my $newOrder = NewOrder($order);
1184 } else {
1185 $sth=$dbh->prepare("update aqorders
1186 set quantityreceived=?,datereceived=?,booksellerinvoicenumber=?,
1187 unitprice=?,freight=?,rrp=?
1188 where biblionumber=? and ordernumber=?");
1189 $sth->execute($quantrec,$datereceived,$invoiceno,$cost,$freight,$rrp,$biblionumber,$ordernumber);
1190 $sth->finish;
1192 return $datereceived;
1194 #------------------------------------------------------------#
1196 =head3 SearchOrder
1198 @results = &SearchOrder($search, $biblionumber, $complete);
1200 Searches for orders.
1202 C<$search> may take one of several forms: if it is an ISBN,
1203 C<&ordersearch> returns orders with that ISBN. If C<$search> is an
1204 order number, C<&ordersearch> returns orders with that order number
1205 and biblionumber C<$biblionumber>. Otherwise, C<$search> is considered
1206 to be a space-separated list of search terms; in this case, all of the
1207 terms must appear in the title (matching the beginning of title
1208 words).
1210 If C<$complete> is C<yes>, the results will include only completed
1211 orders. In any case, C<&ordersearch> ignores cancelled orders.
1213 C<&ordersearch> returns an array.
1214 C<@results> is an array of references-to-hash with the following keys:
1216 =over 4
1218 =item C<author>
1220 =item C<seriestitle>
1222 =item C<branchcode>
1224 =item C<bookfundid>
1226 =back
1228 =cut
1230 sub SearchOrder {
1231 #### -------- SearchOrder-------------------------------
1232 my ($ordernumber, $search, $supplierid, $basket) = @_;
1234 my $dbh = C4::Context->dbh;
1235 my @args = ();
1236 my $query =
1237 "SELECT *
1238 FROM aqorders
1239 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1240 LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
1241 LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
1242 WHERE (datecancellationprinted is NULL)";
1244 if($ordernumber){
1245 $query .= " AND (aqorders.ordernumber=?)";
1246 push @args, $ordernumber;
1248 if($search){
1249 $query .= " AND (biblio.title like ? OR biblio.author LIKE ? OR biblioitems.isbn like ?)";
1250 push @args, ("%$search%","%$search%","%$search%");
1252 if($supplierid){
1253 $query .= "AND aqbasket.booksellerid = ?";
1254 push @args, $supplierid;
1256 if($basket){
1257 $query .= "AND aqorders.basketno = ?";
1258 push @args, $basket;
1261 my $sth = $dbh->prepare($query);
1262 $sth->execute(@args);
1263 my $results = $sth->fetchall_arrayref({});
1264 $sth->finish;
1265 return $results;
1268 #------------------------------------------------------------#
1270 =head3 DelOrder
1272 &DelOrder($biblionumber, $ordernumber);
1274 Cancel the order with the given order and biblio numbers. It does not
1275 delete any entries in the aqorders table, it merely marks them as
1276 cancelled.
1278 =cut
1280 sub DelOrder {
1281 my ( $bibnum, $ordernumber ) = @_;
1282 my $dbh = C4::Context->dbh;
1283 my $query = "
1284 UPDATE aqorders
1285 SET datecancellationprinted=now()
1286 WHERE biblionumber=? AND ordernumber=?
1288 my $sth = $dbh->prepare($query);
1289 $sth->execute( $bibnum, $ordernumber );
1290 $sth->finish;
1291 my @itemnumbers = GetItemnumbersFromOrder( $ordernumber );
1292 foreach my $itemnumber (@itemnumbers){
1293 C4::Items::DelItem( $dbh, $bibnum, $itemnumber );
1298 =head2 FUNCTIONS ABOUT PARCELS
1300 =cut
1302 #------------------------------------------------------------#
1304 =head3 GetParcel
1306 @results = &GetParcel($booksellerid, $code, $date);
1308 Looks up all of the received items from the supplier with the given
1309 bookseller ID at the given date, for the given code (bookseller Invoice number). Ignores cancelled and completed orders.
1311 C<@results> is an array of references-to-hash. The keys of each element are fields from
1312 the aqorders, biblio, and biblioitems tables of the Koha database.
1314 C<@results> is sorted alphabetically by book title.
1316 =cut
1318 sub GetParcel {
1319 #gets all orders from a certain supplier, orders them alphabetically
1320 my ( $supplierid, $code, $datereceived ) = @_;
1321 my $dbh = C4::Context->dbh;
1322 my @results = ();
1323 $code .= '%'
1324 if $code; # add % if we search on a given code (otherwise, let him empty)
1325 my $strsth ="
1326 SELECT authorisedby,
1327 creationdate,
1328 aqbasket.basketno,
1329 closedate,surname,
1330 firstname,
1331 aqorders.biblionumber,
1332 aqorders.ordernumber,
1333 aqorders.quantity,
1334 aqorders.quantityreceived,
1335 aqorders.unitprice,
1336 aqorders.listprice,
1337 aqorders.rrp,
1338 aqorders.ecost,
1339 biblio.title
1340 FROM aqorders
1341 LEFT JOIN aqbasket ON aqbasket.basketno=aqorders.basketno
1342 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
1343 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1344 WHERE
1345 aqbasket.booksellerid = ?
1346 AND aqorders.booksellerinvoicenumber LIKE ?
1347 AND aqorders.datereceived = ? ";
1349 my @query_params = ( $supplierid, $code, $datereceived );
1350 if ( C4::Context->preference("IndependantBranches") ) {
1351 my $userenv = C4::Context->userenv;
1352 if ( ($userenv) && ( $userenv->{flags} != 1 ) ) {
1353 $strsth .= " and (borrowers.branchcode = ?
1354 or borrowers.branchcode = '')";
1355 push @query_params, $userenv->{branch};
1358 $strsth .= " ORDER BY aqbasket.basketno";
1359 # ## parcelinformation : $strsth
1360 my $sth = $dbh->prepare($strsth);
1361 $sth->execute( @query_params );
1362 while ( my $data = $sth->fetchrow_hashref ) {
1363 push( @results, $data );
1365 # ## countparcelbiblio: scalar(@results)
1366 $sth->finish;
1368 return @results;
1371 #------------------------------------------------------------#
1373 =head3 GetParcels
1375 $results = &GetParcels($bookseller, $order, $code, $datefrom, $dateto);
1377 get a lists of parcels.
1379 * Input arg :
1381 =over
1383 =item $bookseller
1384 is the bookseller this function has to get parcels.
1386 =item $order
1387 To know on what criteria the results list has to be ordered.
1389 =item $code
1390 is the booksellerinvoicenumber.
1392 =item $datefrom & $dateto
1393 to know on what date this function has to filter its search.
1395 =back
1397 * return:
1398 a pointer on a hash list containing parcel informations as such :
1400 =over
1402 =item Creation date
1404 =item Last operation
1406 =item Number of biblio
1408 =item Number of items
1410 =back
1412 =cut
1414 sub GetParcels {
1415 my ($bookseller,$order, $code, $datefrom, $dateto) = @_;
1416 my $dbh = C4::Context->dbh;
1417 my @query_params = ();
1418 my $strsth ="
1419 SELECT aqorders.booksellerinvoicenumber,
1420 datereceived,purchaseordernumber,
1421 count(DISTINCT biblionumber) AS biblio,
1422 sum(quantity) AS itemsexpected,
1423 sum(quantityreceived) AS itemsreceived
1424 FROM aqorders LEFT JOIN aqbasket ON aqbasket.basketno = aqorders.basketno
1425 WHERE aqbasket.booksellerid = ? and datereceived IS NOT NULL
1427 push @query_params, $bookseller;
1429 if ( defined $code ) {
1430 $strsth .= ' and aqorders.booksellerinvoicenumber like ? ';
1431 # add a % to the end of the code to allow stemming.
1432 push @query_params, "$code%";
1435 if ( defined $datefrom ) {
1436 $strsth .= ' and datereceived >= ? ';
1437 push @query_params, $datefrom;
1440 if ( defined $dateto ) {
1441 $strsth .= 'and datereceived <= ? ';
1442 push @query_params, $dateto;
1445 $strsth .= "group by aqorders.booksellerinvoicenumber,datereceived ";
1447 # can't use a placeholder to place this column name.
1448 # but, we could probably be checking to make sure it is a column that will be fetched.
1449 $strsth .= "order by $order " if ($order);
1451 my $sth = $dbh->prepare($strsth);
1453 $sth->execute( @query_params );
1454 my $results = $sth->fetchall_arrayref({});
1455 $sth->finish;
1456 return @$results;
1459 #------------------------------------------------------------#
1461 =head3 GetLateOrders
1463 @results = &GetLateOrders;
1465 Searches for bookseller with late orders.
1467 return:
1468 the table of supplier with late issues. This table is full of hashref.
1470 =cut
1472 sub GetLateOrders {
1473 my $delay = shift;
1474 my $supplierid = shift;
1475 my $branch = shift;
1476 my $estimateddeliverydatefrom = shift;
1477 my $estimateddeliverydateto = shift;
1479 my $dbh = C4::Context->dbh;
1481 #BEWARE, order of parenthesis and LEFT JOIN is important for speed
1482 my $dbdriver = C4::Context->config("db_scheme") || "mysql";
1484 my @query_params = ();
1485 my $select = "
1486 SELECT aqbasket.basketno,
1487 aqorders.ordernumber,
1488 DATE(aqbasket.closedate) AS orderdate,
1489 aqorders.rrp AS unitpricesupplier,
1490 aqorders.ecost AS unitpricelib,
1491 aqorders.claims_count AS claims_count,
1492 aqorders.claimed_date AS claimed_date,
1493 aqbudgets.budget_name AS budget,
1494 borrowers.branchcode AS branch,
1495 aqbooksellers.name AS supplier,
1496 aqbooksellers.id AS supplierid,
1497 biblio.author, biblio.title,
1498 biblioitems.publishercode AS publisher,
1499 biblioitems.publicationyear,
1500 ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) AS estimateddeliverydate,
1502 my $from = "
1503 FROM
1504 aqorders LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1505 LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
1506 LEFT JOIN aqbudgets ON aqorders.budget_id = aqbudgets.budget_id,
1507 aqbasket LEFT JOIN borrowers ON aqbasket.authorisedby = borrowers.borrowernumber
1508 LEFT JOIN aqbooksellers ON aqbasket.booksellerid = aqbooksellers.id
1509 WHERE aqorders.basketno = aqbasket.basketno
1510 AND ( datereceived = ''
1511 OR datereceived IS NULL
1512 OR aqorders.quantityreceived < aqorders.quantity
1514 AND aqbasket.closedate IS NOT NULL
1515 AND (aqorders.datecancellationprinted IS NULL OR aqorders.datecancellationprinted='0000-00-00')
1517 my $having = "";
1518 if ($dbdriver eq "mysql") {
1519 $select .= "
1520 aqorders.quantity - IFNULL(aqorders.quantityreceived,0) AS quantity,
1521 (aqorders.quantity - IFNULL(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
1522 DATEDIFF(CAST(now() AS date),closedate) AS latesince
1524 if ( defined $delay ) {
1525 $from .= " AND (closedate <= DATE_SUB(CAST(now() AS date),INTERVAL ? DAY)) " ;
1526 push @query_params, $delay;
1528 $having = "
1529 HAVING quantity <> 0
1530 AND unitpricesupplier <> 0
1531 AND unitpricelib <> 0
1533 } else {
1534 # FIXME: account for IFNULL as above
1535 $select .= "
1536 aqorders.quantity AS quantity,
1537 aqorders.quantity * aqorders.rrp AS subtotal,
1538 (CAST(now() AS date) - closedate) AS latesince
1540 if ( defined $delay ) {
1541 $from .= " AND (closedate <= (CAST(now() AS date) -(INTERVAL ? DAY)) ";
1542 push @query_params, $delay;
1545 if (defined $supplierid) {
1546 $from .= ' AND aqbasket.booksellerid = ? ';
1547 push @query_params, $supplierid;
1549 if (defined $branch) {
1550 $from .= ' AND borrowers.branchcode LIKE ? ';
1551 push @query_params, $branch;
1553 if ( defined $estimateddeliverydatefrom ) {
1554 $from .= '
1555 AND aqbooksellers.deliverytime IS NOT NULL
1556 AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) >= ?';
1557 push @query_params, $estimateddeliverydatefrom;
1559 if ( defined $estimateddeliverydatefrom and defined $estimateddeliverydateto ) {
1560 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= ?';
1561 push @query_params, $estimateddeliverydateto;
1562 } elsif ( defined $estimateddeliverydatefrom ) {
1563 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= CAST(now() AS date)';
1565 if (C4::Context->preference("IndependantBranches")
1566 && C4::Context->userenv
1567 && C4::Context->userenv->{flags} != 1 ) {
1568 $from .= ' AND borrowers.branchcode LIKE ? ';
1569 push @query_params, C4::Context->userenv->{branch};
1571 my $query = "$select $from $having\nORDER BY latesince, basketno, borrowers.branchcode, supplier";
1572 $debug and print STDERR "GetLateOrders query: $query\nGetLateOrders args: " . join(" ",@query_params);
1573 my $sth = $dbh->prepare($query);
1574 $sth->execute(@query_params);
1575 my @results;
1576 while (my $data = $sth->fetchrow_hashref) {
1577 $data->{orderdate} = format_date($data->{orderdate});
1578 $data->{claimed_date} = format_date($data->{claimed_date});
1579 push @results, $data;
1581 return @results;
1584 #------------------------------------------------------------#
1586 =head3 GetHistory
1588 (\@order_loop, $total_qty, $total_price, $total_qtyreceived) = GetHistory( %params );
1590 Retreives some acquisition history information
1592 params:
1593 title
1594 author
1595 name
1596 from_placed_on
1597 to_placed_on
1598 basket - search both basket name and number
1599 booksellerinvoicenumber
1601 returns:
1602 $order_loop is a list of hashrefs that each look like this:
1604 'author' => 'Twain, Mark',
1605 'basketno' => '1',
1606 'biblionumber' => '215',
1607 'count' => 1,
1608 'creationdate' => 'MM/DD/YYYY',
1609 'datereceived' => undef,
1610 'ecost' => '1.00',
1611 'id' => '1',
1612 'invoicenumber' => undef,
1613 'name' => '',
1614 'ordernumber' => '1',
1615 'quantity' => 1,
1616 'quantityreceived' => undef,
1617 'title' => 'The Adventures of Huckleberry Finn'
1619 $total_qty is the sum of all of the quantities in $order_loop
1620 $total_price is the cost of each in $order_loop times the quantity
1621 $total_qtyreceived is the sum of all of the quantityreceived entries in $order_loop
1623 =cut
1625 sub GetHistory {
1626 # don't run the query if there are no parameters (list would be too long for sure !)
1627 croak "No search params" unless @_;
1628 my %params = @_;
1629 my $title = $params{title};
1630 my $author = $params{author};
1631 my $isbn = $params{isbn};
1632 my $name = $params{name};
1633 my $from_placed_on = $params{from_placed_on};
1634 my $to_placed_on = $params{to_placed_on};
1635 my $basket = $params{basket};
1636 my $booksellerinvoicenumber = $params{booksellerinvoicenumber};
1638 my @order_loop;
1639 my $total_qty = 0;
1640 my $total_qtyreceived = 0;
1641 my $total_price = 0;
1643 my $dbh = C4::Context->dbh;
1644 my $query ="
1645 SELECT
1646 biblio.title,
1647 biblio.author,
1648 biblioitems.isbn,
1649 aqorders.basketno,
1650 aqbasket.basketname,
1651 aqbasket.basketgroupid,
1652 aqbasketgroups.name as groupname,
1653 aqbooksellers.name,
1654 aqbasket.creationdate,
1655 aqorders.datereceived,
1656 aqorders.quantity,
1657 aqorders.quantityreceived,
1658 aqorders.ecost,
1659 aqorders.ordernumber,
1660 aqorders.booksellerinvoicenumber as invoicenumber,
1661 aqbooksellers.id as id,
1662 aqorders.biblionumber
1663 FROM aqorders
1664 LEFT JOIN aqbasket ON aqorders.basketno=aqbasket.basketno
1665 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid=aqbasketgroups.id
1666 LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
1667 LEFT JOIN biblioitems ON biblioitems.biblionumber=aqorders.biblionumber
1668 LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber";
1670 $query .= " LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber"
1671 if ( C4::Context->preference("IndependantBranches") );
1673 $query .= " WHERE (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') ";
1675 my @query_params = ();
1677 if ( $title ) {
1678 $query .= " AND biblio.title LIKE ? ";
1679 $title =~ s/\s+/%/g;
1680 push @query_params, "%$title%";
1683 if ( $author ) {
1684 $query .= " AND biblio.author LIKE ? ";
1685 push @query_params, "%$author%";
1688 if ( $isbn ) {
1689 $query .= " AND biblioitems.isbn LIKE ? ";
1690 push @query_params, "%$isbn%";
1693 if ( $name ) {
1694 $query .= " AND aqbooksellers.name LIKE ? ";
1695 push @query_params, "%$name%";
1698 if ( $from_placed_on ) {
1699 $query .= " AND creationdate >= ? ";
1700 push @query_params, $from_placed_on;
1703 if ( $to_placed_on ) {
1704 $query .= " AND creationdate <= ? ";
1705 push @query_params, $to_placed_on;
1708 if ($basket) {
1709 if ($basket =~ m/^\d+$/) {
1710 $query .= " AND aqorders.basketno = ? ";
1711 push @query_params, $basket;
1712 } else {
1713 $query .= " AND aqbasket.basketname LIKE ? ";
1714 push @query_params, "%$basket%";
1718 if ($booksellerinvoicenumber) {
1719 $query .= " AND (aqorders.booksellerinvoicenumber LIKE ? OR aqbasket.booksellerinvoicenumber LIKE ?)";
1720 push @query_params, "%$booksellerinvoicenumber%", "%$booksellerinvoicenumber%";
1723 if ( C4::Context->preference("IndependantBranches") ) {
1724 my $userenv = C4::Context->userenv;
1725 if ( $userenv && ($userenv->{flags} || 0) != 1 ) {
1726 $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
1727 push @query_params, $userenv->{branch};
1730 $query .= " ORDER BY id";
1731 my $sth = $dbh->prepare($query);
1732 $sth->execute( @query_params );
1733 my $cnt = 1;
1734 while ( my $line = $sth->fetchrow_hashref ) {
1735 $line->{count} = $cnt++;
1736 $line->{toggle} = 1 if $cnt % 2;
1737 push @order_loop, $line;
1738 $total_qty += $line->{'quantity'};
1739 $total_qtyreceived += $line->{'quantityreceived'};
1740 $total_price += $line->{'quantity'} * $line->{'ecost'};
1742 return \@order_loop, $total_qty, $total_price, $total_qtyreceived;
1745 =head2 GetRecentAcqui
1747 $results = GetRecentAcqui($days);
1749 C<$results> is a ref to a table which containts hashref
1751 =cut
1753 sub GetRecentAcqui {
1754 my $limit = shift;
1755 my $dbh = C4::Context->dbh;
1756 my $query = "
1757 SELECT *
1758 FROM biblio
1759 ORDER BY timestamp DESC
1760 LIMIT 0,".$limit;
1762 my $sth = $dbh->prepare($query);
1763 $sth->execute;
1764 my $results = $sth->fetchall_arrayref({});
1765 return $results;
1768 =head3 GetContracts
1770 $contractlist = &GetContracts($booksellerid, $activeonly);
1772 Looks up the contracts that belong to a bookseller
1774 Returns a list of contracts
1776 =over
1778 =item C<$booksellerid> is the "id" field in the "aqbooksellers" table.
1780 =item C<$activeonly> if exists get only contracts that are still active.
1782 =back
1784 =cut
1786 sub GetContracts {
1787 my ( $booksellerid, $activeonly ) = @_;
1788 my $dbh = C4::Context->dbh;
1789 my $query;
1790 if (! $activeonly) {
1791 $query = "
1792 SELECT *
1793 FROM aqcontract
1794 WHERE booksellerid=?
1796 } else {
1797 $query = "SELECT *
1798 FROM aqcontract
1799 WHERE booksellerid=?
1800 AND contractenddate >= CURDATE( )";
1802 my $sth = $dbh->prepare($query);
1803 $sth->execute( $booksellerid );
1804 my @results;
1805 while (my $data = $sth->fetchrow_hashref ) {
1806 push(@results, $data);
1808 $sth->finish;
1809 return @results;
1812 #------------------------------------------------------------#
1814 =head3 GetContract
1816 $contract = &GetContract($contractID);
1818 Looks up the contract that has PRIMKEY (contractnumber) value $contractID
1820 Returns a contract
1822 =cut
1824 sub GetContract {
1825 my ( $contractno ) = @_;
1826 my $dbh = C4::Context->dbh;
1827 my $query = "
1828 SELECT *
1829 FROM aqcontract
1830 WHERE contractnumber=?
1833 my $sth = $dbh->prepare($query);
1834 $sth->execute( $contractno );
1835 my $result = $sth->fetchrow_hashref;
1836 return $result;
1839 =head3 AddClaim
1841 =over 4
1843 &AddClaim($ordernumber);
1845 Add a claim for an order
1847 =back
1849 =cut
1850 sub AddClaim {
1851 my ($ordernumber) = @_;
1852 my $dbh = C4::Context->dbh;
1853 my $query = "
1854 UPDATE aqorders SET
1855 claims_count = claims_count + 1,
1856 claimed_date = CURDATE()
1857 WHERE ordernumber = ?
1859 my $sth = $dbh->prepare($query);
1860 $sth->execute($ordernumber);
1865 __END__
1867 =head1 AUTHOR
1869 Koha Development Team <http://koha-community.org/>
1871 =cut