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
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
29 use C4
::Templates
qw(gettemplate);
30 use Koha
::DateUtils
qw( dt_from_string output_pref );
31 use Koha
::Acquisition
::Booksellers
;
32 use Koha
::Acquisition
::Orders
;
35 use Koha
::Number
::Price
;
37 use Koha
::CsvProfiles
;
47 use vars
qw(@ISA @EXPORT);
53 &GetBasket &NewBasket &CloseBasket &ReopenBasket &DelBasket &ModBasket
54 &GetBasketAsCSV &GetBasketGroupAsCSV
55 &GetBasketsByBookseller &GetBasketsByBasketgroup
56 &GetBasketsInfosByBookseller
58 &GetBasketUsers &ModBasketUsers
63 &ModBasketgroup &NewBasketgroup &DelBasketgroup &GetBasketgroup &CloseBasketgroup
64 &GetBasketgroups &ReOpenBasketgroup
66 &DelOrder &ModOrder &GetOrder &GetOrders &GetOrdersByBiblionumber
67 &GetLateOrders &GetOrderFromItemnumber
68 &SearchOrders &GetHistory &GetRecentAcqui
69 &ModReceiveOrder &CancelReceipt
71 &GetLastOrderNotReceivedFromSubscriptionid &GetLastOrderReceivedFromSubscriptionid
86 &GetItemnumbersFromOrder
89 &GetBiblioCountByBasketno
95 &FillWithDefaultValues
103 sub GetOrderFromItemnumber
{
104 my ($itemnumber) = @_;
105 my $dbh = C4
::Context
->dbh;
108 SELECT
* from aqorders LEFT JOIN aqorders_items
109 ON
( aqorders
.ordernumber
= aqorders_items
.ordernumber
)
110 WHERE itemnumber
= ?
|;
112 my $sth = $dbh->prepare($query);
116 $sth->execute($itemnumber);
118 my $order = $sth->fetchrow_hashref;
123 # Returns the itemnumber(s) associated with the ordernumber given in parameter
124 sub GetItemnumbersFromOrder
{
125 my ($ordernumber) = @_;
126 my $dbh = C4
::Context
->dbh;
127 my $query = "SELECT itemnumber FROM aqorders_items WHERE ordernumber=?";
128 my $sth = $dbh->prepare($query);
129 $sth->execute($ordernumber);
132 while (my $order = $sth->fetchrow_hashref) {
133 push @tab, $order->{'itemnumber'};
147 C4::Acquisition - Koha functions for dealing with orders and acquisitions
155 The functions in this module deal with acquisitions, managing book
156 orders, basket and parcels.
160 =head2 FUNCTIONS ABOUT BASKETS
164 $aqbasket = &GetBasket($basketnumber);
166 get all basket informations in aqbasket for a given basket
168 B<returns:> informations for a given basket returned as a hashref.
174 my $dbh = C4
::Context
->dbh;
177 concat( b.firstname,' ',b.surname) AS authorisedbyname
179 LEFT JOIN borrowers b ON aqbasket.authorisedby=b.borrowernumber
182 my $sth=$dbh->prepare($query);
183 $sth->execute($basketno);
184 my $basket = $sth->fetchrow_hashref;
188 #------------------------------------------------------------#
192 $basket = &NewBasket( $booksellerid, $authorizedby, $basketname,
193 $basketnote, $basketbooksellernote, $basketcontractnumber, $deliveryplace, $billingplace, $is_standing, $create_items );
195 Create a new basket in aqbasket table
199 =item C<$booksellerid> is a foreign key in the aqbasket table
201 =item C<$authorizedby> is the username of who created the basket
205 The other parameters are optional, see ModBasketHeader for more info on them.
210 my ( $booksellerid, $authorisedby, $basketname, $basketnote,
211 $basketbooksellernote, $basketcontractnumber, $deliveryplace,
212 $billingplace, $is_standing, $create_items ) = @_;
213 my $dbh = C4
::Context
->dbh;
215 'INSERT INTO aqbasket (creationdate,booksellerid,authorisedby) '
216 . 'VALUES (now(),?,?)';
217 $dbh->do( $query, {}, $booksellerid, $authorisedby );
219 my $basket = $dbh->{mysql_insertid
};
220 $basketname ||= q{}; # default to empty strings
222 $basketbooksellernote ||= q{};
223 ModBasketHeader
( $basket, $basketname, $basketnote, $basketbooksellernote,
224 $basketcontractnumber, $booksellerid, $deliveryplace, $billingplace, $is_standing, $create_items );
228 #------------------------------------------------------------#
232 &CloseBasket($basketno);
234 close a basket (becomes unmodifiable, except for receives)
240 my $dbh = C4
::Context
->dbh;
241 $dbh->do('UPDATE aqbasket SET closedate=now() WHERE basketno=?', {}, $basketno );
244 q{UPDATE aqorders SET orderstatus = 'ordered' WHERE basketno = ? AND orderstatus NOT IN ( 'complete', 'cancelled')},
252 &ReopenBasket($basketno);
260 my $dbh = C4
::Context
->dbh;
261 $dbh->do( q{UPDATE aqbasket SET closedate=NULL WHERE basketno=?}, {}, $basketno );
265 SET orderstatus = 'new'
267 AND orderstatus NOT IN ( 'complete', 'cancelled' )
272 #------------------------------------------------------------#
274 =head3 GetBasketAsCSV
276 &GetBasketAsCSV($basketno);
278 Export a basket as CSV
280 $cgi parameter is needed for column name translation
285 my ($basketno, $cgi, $csv_profile_id) = @_;
286 my $basket = GetBasket
($basketno);
287 my @orders = GetOrders
($basketno);
288 my $contract = GetContract
({
289 contractnumber
=> $basket->{'contractnumber'}
292 my $template = C4
::Templates
::gettemplate
("acqui/csv/basket.tt", "intranet", $cgi);
294 if ($csv_profile_id) {
295 my $csv_profile = Koha
::CsvProfiles
->find( $csv_profile_id );
296 die "There is no valid csv profile given" unless $csv_profile;
298 my $csv = Text
::CSV_XS
->new({'quote_char'=>'"','escape_char'=>'"','sep_char'=>$csv_profile->csv_separator,'binary'=>1});
299 my $csv_profile_content = $csv_profile->content;
300 my ( @headers, @fields );
301 while ( $csv_profile_content =~ /
304 ([^\
|]*) # fieldname (table.row or row)
308 my $field = ($2 eq '') ?
$1 : $2;
310 $header =~ s/^\s+|\s+$//g; # Trim whitespaces
311 push @headers, $header;
313 $field =~ s/[^\.]*\.{1}//; # Remove the table name if exists.
314 $field =~ s/^\s+|\s+$//g; # Trim whitespaces
315 push @fields, $field;
317 for my $order (@orders) {
319 my $biblio = Koha
::Biblios
->find( $order->{biblionumber
} );
320 my $biblioitem = $biblio->biblioitem;
321 $order = { %$order, %{ $biblioitem->unblessed } };
323 $order = {%$order, %$contract};
325 $order = {%$order, %$basket, %{ $biblio->unblessed }};
326 for my $field (@fields) {
327 push @row, $order->{$field};
331 my $content = join( $csv_profile->csv_separator, @headers ) . "\n";
332 for my $row ( @rows ) {
333 $csv->combine(@
$row);
334 my $string = $csv->string;
335 $content .= $string . "\n";
340 foreach my $order (@orders) {
341 my $biblio = Koha
::Biblios
->find( $order->{biblionumber
} );
342 my $biblioitem = $biblio->biblioitem;
344 contractname
=> $contract->{'contractname'},
345 ordernumber
=> $order->{'ordernumber'},
346 entrydate
=> $order->{'entrydate'},
347 isbn
=> $order->{'isbn'},
348 author
=> $biblio->author,
349 title
=> $biblio->title,
350 publicationyear
=> $biblioitem->publicationyear,
351 publishercode
=> $biblioitem->publishercode,
352 collectiontitle
=> $biblioitem->collectiontitle,
353 notes
=> $order->{'order_vendornote'},
354 quantity
=> $order->{'quantity'},
355 rrp
=> $order->{'rrp'},
357 for my $place ( qw( deliveryplace billingplace ) ) {
358 if ( my $library = Koha
::Libraries
->find( $row->{deliveryplace
} ) ) {
359 $row->{$place} = $library->branchname
363 contractname author title publishercode collectiontitle notes
364 deliveryplace billingplace
366 # Double the quotes to not be interpreted as a field end
367 $row->{$_} =~ s/"/""/g if $row->{$_};
373 if(defined $a->{publishercode
} and defined $b->{publishercode
}) {
374 $a->{publishercode
} cmp $b->{publishercode
};
378 $template->param(rows
=> \
@rows);
380 return $template->output;
385 =head3 GetBasketGroupAsCSV
387 &GetBasketGroupAsCSV($basketgroupid);
389 Export a basket group as CSV
391 $cgi parameter is needed for column name translation
395 sub GetBasketGroupAsCSV
{
396 my ($basketgroupid, $cgi) = @_;
397 my $baskets = GetBasketsByBasketgroup
($basketgroupid);
399 my $template = C4
::Templates
::gettemplate
('acqui/csv/basketgroup.tt', 'intranet', $cgi);
402 for my $basket (@
$baskets) {
403 my @orders = GetOrders
( $basket->{basketno
} );
404 my $contract = GetContract
({
405 contractnumber
=> $basket->{contractnumber
}
407 my $bookseller = Koha
::Acquisition
::Booksellers
->find( $basket->{booksellerid
} );
408 my $basketgroup = GetBasketgroup
( $$basket{basketgroupid
} );
410 foreach my $order (@orders) {
411 my $biblio = Koha
::Biblios
->find( $order->{biblionumber
} );
412 my $biblioitem = $biblio->biblioitem;
414 clientnumber
=> $bookseller->accountnumber,
415 basketname
=> $basket->{basketname
},
416 ordernumber
=> $order->{ordernumber
},
417 author
=> $biblio->author,
418 title
=> $biblio->title,
419 publishercode
=> $biblioitem->publishercode,
420 publicationyear
=> $biblioitem->publicationyear,
421 collectiontitle
=> $biblioitem->collectiontitle,
422 isbn
=> $order->{isbn
},
423 quantity
=> $order->{quantity
},
424 rrp_tax_included
=> $order->{rrp_tax_included
},
425 rrp_tax_excluded
=> $order->{rrp_tax_excluded
},
426 discount
=> $bookseller->discount,
427 ecost_tax_included
=> $order->{ecost_tax_included
},
428 ecost_tax_excluded
=> $order->{ecost_tax_excluded
},
429 notes
=> $order->{order_vendornote
},
430 entrydate
=> $order->{entrydate
},
431 booksellername
=> $bookseller->name,
432 bookselleraddress
=> $bookseller->address1,
433 booksellerpostal
=> $bookseller->postal,
434 contractnumber
=> $contract->{contractnumber
},
435 contractname
=> $contract->{contractname
},
438 basketgroupdeliveryplace
=> $basketgroup->{deliveryplace
},
439 basketgroupbillingplace
=> $basketgroup->{billingplace
},
440 basketdeliveryplace
=> $basket->{deliveryplace
},
441 basketbillingplace
=> $basket->{billingplace
},
443 for my $place (qw( basketgroupdeliveryplace basketgroupbillingplace basketdeliveryplace basketbillingplace )) {
444 if ( my $library = Koha
::Libraries
->find( $temp->{$place} ) ) {
445 $row->{$place} = $library->branchname;
449 basketname author title publishercode collectiontitle notes
450 booksellername bookselleraddress booksellerpostal contractname
451 basketgroupdeliveryplace basketgroupbillingplace
452 basketdeliveryplace basketbillingplace
454 # Double the quotes to not be interpreted as a field end
455 $row->{$_} =~ s/"/""/g if $row->{$_};
460 $template->param(rows
=> \
@rows);
462 return $template->output;
466 =head3 CloseBasketgroup
468 &CloseBasketgroup($basketgroupno);
474 sub CloseBasketgroup
{
475 my ($basketgroupno) = @_;
476 my $dbh = C4
::Context
->dbh;
477 my $sth = $dbh->prepare("
478 UPDATE aqbasketgroups
482 $sth->execute($basketgroupno);
485 #------------------------------------------------------------#
487 =head3 ReOpenBaskergroup($basketgroupno)
489 &ReOpenBaskergroup($basketgroupno);
495 sub ReOpenBasketgroup
{
496 my ($basketgroupno) = @_;
497 my $dbh = C4
::Context
->dbh;
498 my $sth = $dbh->prepare("
499 UPDATE aqbasketgroups
503 $sth->execute($basketgroupno);
506 #------------------------------------------------------------#
511 &DelBasket($basketno);
513 Deletes the basket that has basketno field $basketno in the aqbasket table.
517 =item C<$basketno> is the primary key of the basket in the aqbasket table.
524 my ( $basketno ) = @_;
525 my $query = "DELETE FROM aqbasket WHERE basketno=?";
526 my $dbh = C4
::Context
->dbh;
527 my $sth = $dbh->prepare($query);
528 $sth->execute($basketno);
532 #------------------------------------------------------------#
536 &ModBasket($basketinfo);
538 Modifies a basket, using a hashref $basketinfo for the relevant information, only $basketinfo->{'basketno'} is required.
542 =item C<$basketno> is the primary key of the basket in the aqbasket table.
549 my $basketinfo = shift;
550 my $query = "UPDATE aqbasket SET ";
552 foreach my $key (keys %$basketinfo){
553 if ($key ne 'basketno'){
554 $query .= "$key=?, ";
555 push(@params, $basketinfo->{$key} || undef );
558 # get rid of the "," at the end of $query
559 if (substr($query, length($query)-2) eq ', '){
564 $query .= "WHERE basketno=?";
565 push(@params, $basketinfo->{'basketno'});
566 my $dbh = C4
::Context
->dbh;
567 my $sth = $dbh->prepare($query);
568 $sth->execute(@params);
573 #------------------------------------------------------------#
575 =head3 ModBasketHeader
577 &ModBasketHeader($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid);
579 Modifies a basket's header.
583 =item C<$basketno> is the "basketno" field in the "aqbasket" table;
585 =item C<$basketname> is the "basketname" field in the "aqbasket" table;
587 =item C<$note> is the "note" field in the "aqbasket" table;
589 =item C<$booksellernote> is the "booksellernote" field in the "aqbasket" table;
591 =item C<$contractnumber> is the "contractnumber" (foreign) key in the "aqbasket" table.
593 =item C<$booksellerid> is the id (foreign) key in the "aqbooksellers" table for the vendor.
595 =item C<$deliveryplace> is the "deliveryplace" field in the aqbasket table.
597 =item C<$billingplace> is the "billingplace" field in the aqbasket table.
599 =item C<$is_standing> is the "is_standing" field in the aqbasket table.
601 =item C<$create_items> should be set to 'ordering', 'receiving' or 'cataloguing' (or undef, in which
602 case the AcqCreateItem syspref takes precedence).
608 sub ModBasketHeader
{
609 my ($basketno, $basketname, $note, $booksellernote, $contractnumber, $booksellerid, $deliveryplace, $billingplace, $is_standing, $create_items) = @_;
614 SET basketname
=?
, note
=?
, booksellernote
=?
, booksellerid
=?
, deliveryplace
=?
, billingplace
=?
, is_standing
=?
, create_items
=?
618 my $dbh = C4
::Context
->dbh;
619 my $sth = $dbh->prepare($query);
620 $sth->execute($basketname, $note, $booksellernote, $booksellerid, $deliveryplace, $billingplace, $is_standing, $create_items || undef, $basketno);
622 if ( $contractnumber ) {
623 my $query2 ="UPDATE aqbasket SET contractnumber=? WHERE basketno=?";
624 my $sth2 = $dbh->prepare($query2);
625 $sth2->execute($contractnumber,$basketno);
630 #------------------------------------------------------------#
632 =head3 GetBasketsByBookseller
634 @results = &GetBasketsByBookseller($booksellerid, $extra);
636 Returns a list of hashes of all the baskets that belong to bookseller 'booksellerid'.
640 =item C<$booksellerid> is the 'id' field of the bookseller in the aqbooksellers table
642 =item C<$extra> is the extra sql parameters, can be
644 $extra->{groupby}: group baskets by column
645 ex. $extra->{groupby} = aqbasket.basketgroupid
646 $extra->{orderby}: order baskets by column
647 $extra->{limit}: limit number of results (can be helpful for pagination)
653 sub GetBasketsByBookseller
{
654 my ($booksellerid, $extra) = @_;
655 my $query = "SELECT * FROM aqbasket WHERE booksellerid=?";
657 if ($extra->{groupby
}) {
658 $query .= " GROUP by $extra->{groupby}";
660 if ($extra->{orderby
}){
661 $query .= " ORDER by $extra->{orderby}";
663 if ($extra->{limit
}){
664 $query .= " LIMIT $extra->{limit}";
667 my $dbh = C4
::Context
->dbh;
668 my $sth = $dbh->prepare($query);
669 $sth->execute($booksellerid);
670 return $sth->fetchall_arrayref({});
673 =head3 GetBasketsInfosByBookseller
675 my $baskets = GetBasketsInfosByBookseller($supplierid, $allbaskets);
677 The optional second parameter allbaskets is a boolean allowing you to
678 select all baskets from the supplier; by default only active baskets (open or
679 closed but still something to receive) are returned.
681 Returns in a arrayref of hashref all about booksellers baskets, plus:
682 total_biblios: Number of distinct biblios in basket
683 total_items: Number of items in basket
684 expected_items: Number of non-received items in basket
688 sub GetBasketsInfosByBookseller
{
689 my ($supplierid, $allbaskets) = @_;
691 return unless $supplierid;
693 my $dbh = C4
::Context
->dbh;
695 SELECT aqbasket.basketno, aqbasket.basketname, aqbasket.note, aqbasket.booksellernote, aqbasket.contractnumber, aqbasket.creationdate, aqbasket.closedate, aqbasket.booksellerid, aqbasket.authorisedby, aqbasket.booksellerinvoicenumber, aqbasket.basketgroupid, aqbasket.deliveryplace, aqbasket.billingplace, aqbasket.branch, aqbasket.is_standing, aqbasket.create_items,
696 SUM(aqorders.quantity) AS total_items,
698 IF ( aqorders.orderstatus = 'cancelled', aqorders.quantity, 0 )
699 ) AS total_items_cancelled,
700 COUNT(DISTINCT aqorders.biblionumber) AS total_biblios,
702 IF(aqorders.datereceived IS NULL
703 AND aqorders.datecancellationprinted IS NULL
708 LEFT JOIN aqorders ON aqorders.basketno = aqbasket.basketno
709 WHERE booksellerid = ?};
711 unless ( $allbaskets ) {
712 $query.=" AND (closedate IS NULL OR (aqorders.quantity > aqorders.quantityreceived AND datecancellationprinted IS NULL))";
714 $query.=" GROUP BY aqbasket.basketno, aqbasket.basketname, aqbasket.note, aqbasket.booksellernote, aqbasket.contractnumber, aqbasket.creationdate, aqbasket.closedate, aqbasket.booksellerid, aqbasket.authorisedby, aqbasket.booksellerinvoicenumber, aqbasket.basketgroupid, aqbasket.deliveryplace, aqbasket.billingplace, aqbasket.branch, aqbasket.is_standing, aqbasket.create_items";
716 my $sth = $dbh->prepare($query);
717 $sth->execute($supplierid);
718 my $baskets = $sth->fetchall_arrayref({});
720 # Retrieve the number of biblios cancelled
721 my $cancelled_biblios = $dbh->selectall_hashref( q
|
722 SELECT COUNT
(DISTINCT
(biblionumber
)) AS total_biblios_cancelled
, aqbasket
.basketno
724 LEFT JOIN aqorders ON aqorders
.basketno
= aqbasket
.basketno
725 WHERE booksellerid
= ?
726 AND aqorders
.orderstatus
= 'cancelled'
727 GROUP BY aqbasket
.basketno
728 |, 'basketno', {}, $supplierid );
730 $_->{total_biblios_cancelled
} = $cancelled_biblios->{$_->{basketno
}}{total_biblios_cancelled
} || 0
736 =head3 GetBasketUsers
738 $basketusers_ids = &GetBasketUsers($basketno);
740 Returns a list of all borrowernumbers that are in basket users list
745 my $basketno = shift;
747 return unless $basketno;
750 SELECT borrowernumber
754 my $dbh = C4
::Context
->dbh;
755 my $sth = $dbh->prepare($query);
756 $sth->execute($basketno);
757 my $results = $sth->fetchall_arrayref( {} );
760 foreach (@
$results) {
761 push @borrowernumbers, $_->{'borrowernumber'};
764 return @borrowernumbers;
767 =head3 ModBasketUsers
769 my @basketusers_ids = (1, 2, 3);
770 &ModBasketUsers($basketno, @basketusers_ids);
772 Delete all users from basket users list, and add users in C<@basketusers_ids>
778 my ($basketno, @basketusers_ids) = @_;
780 return unless $basketno;
782 my $dbh = C4
::Context
->dbh;
784 DELETE FROM aqbasketusers
787 my $sth = $dbh->prepare($query);
788 $sth->execute($basketno);
791 INSERT INTO aqbasketusers
(basketno
, borrowernumber
)
794 $sth = $dbh->prepare($query);
795 foreach my $basketuser_id (@basketusers_ids) {
796 $sth->execute($basketno, $basketuser_id);
801 =head3 CanUserManageBasket
803 my $bool = CanUserManageBasket($borrower, $basket[, $userflags]);
804 my $bool = CanUserManageBasket($borrowernumber, $basketno[, $userflags]);
806 Check if a borrower can manage a basket, according to system preference
807 AcqViewBaskets, user permissions and basket properties (creator, users list,
810 First parameter can be either a borrowernumber or a hashref as returned by
811 Koha::Patron->unblessed
813 Second parameter can be either a basketno or a hashref as returned by
814 C4::Acquisition::GetBasket.
816 The third parameter is optional. If given, it should be a hashref as returned
817 by C4::Auth::getuserflags. If not, getuserflags is called.
819 If user is authorised to manage basket, returns 1.
824 sub CanUserManageBasket
{
825 my ($borrower, $basket, $userflags) = @_;
827 if (!ref $borrower) {
828 # FIXME This needs to be replaced
829 # We should not accept both scalar and array
830 # Tests need to be updated
831 $borrower = Koha
::Patrons
->find( $borrower )->unblessed;
834 $basket = GetBasket
($basket);
837 return 0 unless ($basket and $borrower);
839 my $borrowernumber = $borrower->{borrowernumber
};
840 my $basketno = $basket->{basketno
};
842 my $AcqViewBaskets = C4
::Context
->preference('AcqViewBaskets');
844 if (!defined $userflags) {
845 my $dbh = C4
::Context
->dbh;
846 my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE borrowernumber = ?");
847 $sth->execute($borrowernumber);
848 my ($flags) = $sth->fetchrow_array;
851 $userflags = C4
::Auth
::getuserflags
($flags, $borrower->{userid
}, $dbh);
854 unless ($userflags->{superlibrarian
}
855 || (ref $userflags->{acquisition
} && $userflags->{acquisition
}->{order_manage_all
})
856 || (!ref $userflags->{acquisition
} && $userflags->{acquisition
}))
858 if (not exists $userflags->{acquisition
}) {
862 if ( (ref $userflags->{acquisition
} && !$userflags->{acquisition
}->{order_manage
})
863 || (!ref $userflags->{acquisition
} && !$userflags->{acquisition
}) ) {
867 if ($AcqViewBaskets eq 'user'
868 && $basket->{authorisedby
} != $borrowernumber
869 && ! grep { $borrowernumber eq $_ } GetBasketUsers
($basketno)) {
873 if ($AcqViewBaskets eq 'branch' && defined $basket->{branch
}
874 && $basket->{branch
} ne $borrower->{branchcode
}) {
882 #------------------------------------------------------------#
884 =head3 GetBasketsByBasketgroup
886 $baskets = &GetBasketsByBasketgroup($basketgroupid);
888 Returns a reference to all baskets that belong to basketgroup $basketgroupid.
892 sub GetBasketsByBasketgroup
{
893 my $basketgroupid = shift;
895 SELECT
*, aqbasket
.booksellerid as booksellerid
897 LEFT JOIN aqcontract USING
(contractnumber
) WHERE basketgroupid
=?
899 my $dbh = C4
::Context
->dbh;
900 my $sth = $dbh->prepare($query);
901 $sth->execute($basketgroupid);
902 return $sth->fetchall_arrayref({});
905 #------------------------------------------------------------#
907 =head3 NewBasketgroup
909 $basketgroupid = NewBasketgroup(\%hashref);
911 Adds a basketgroup to the aqbasketgroups table, and add the initial baskets to it.
913 $hashref->{'booksellerid'} is the 'id' field of the bookseller in the aqbooksellers table,
915 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
917 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
919 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
921 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
923 $hashref->{'freedeliveryplace'} is the 'freedeliveryplace' field of the basketgroup in the aqbasketgroups table,
925 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
927 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
932 my $basketgroupinfo = shift;
933 die "booksellerid is required to create a basketgroup" unless $basketgroupinfo->{'booksellerid'};
934 my $query = "INSERT INTO aqbasketgroups (";
936 foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
937 if ( defined $basketgroupinfo->{$field} ) {
938 $query .= "$field, ";
939 push(@params, $basketgroupinfo->{$field});
942 $query .= "booksellerid) VALUES (";
947 push(@params, $basketgroupinfo->{'booksellerid'});
948 my $dbh = C4
::Context
->dbh;
949 my $sth = $dbh->prepare($query);
950 $sth->execute(@params);
951 my $basketgroupid = $dbh->{'mysql_insertid'};
952 if( $basketgroupinfo->{'basketlist'} ) {
953 foreach my $basketno (@
{$basketgroupinfo->{'basketlist'}}) {
954 my $query2 = "UPDATE aqbasket SET basketgroupid=? WHERE basketno=?";
955 my $sth2 = $dbh->prepare($query2);
956 $sth2->execute($basketgroupid, $basketno);
959 return $basketgroupid;
962 #------------------------------------------------------------#
964 =head3 ModBasketgroup
966 ModBasketgroup(\%hashref);
968 Modifies a basketgroup in the aqbasketgroups table, and add the baskets to it.
970 $hashref->{'id'} is the 'id' field of the basketgroup in the aqbasketgroup table, this parameter is mandatory,
972 $hashref->{'name'} is the 'name' field of the basketgroup in the aqbasketgroups table,
974 $hashref->{'basketlist'} is a list reference of the 'id's of the baskets that belong to this group,
976 $hashref->{'billingplace'} is the 'billingplace' field of the basketgroup in the aqbasketgroups table,
978 $hashref->{'deliveryplace'} is the 'deliveryplace' field of the basketgroup in the aqbasketgroups table,
980 $hashref->{'freedeliveryplace'} is the 'freedeliveryplace' field of the basketgroup in the aqbasketgroups table,
982 $hashref->{'deliverycomment'} is the 'deliverycomment' field of the basketgroup in the aqbasketgroups table,
984 $hashref->{'closed'} is the 'closed' field of the aqbasketgroups table, it is false if 0, true otherwise.
989 my $basketgroupinfo = shift;
990 die "basketgroup id is required to edit a basketgroup" unless $basketgroupinfo->{'id'};
991 my $dbh = C4
::Context
->dbh;
992 my $query = "UPDATE aqbasketgroups SET ";
994 foreach my $field (qw(name billingplace deliveryplace freedeliveryplace deliverycomment closed)) {
995 if ( defined $basketgroupinfo->{$field} ) {
996 $query .= "$field=?, ";
997 push(@params, $basketgroupinfo->{$field});
1002 $query .= " WHERE id=?";
1003 push(@params, $basketgroupinfo->{'id'});
1004 my $sth = $dbh->prepare($query);
1005 $sth->execute(@params);
1007 $sth = $dbh->prepare('UPDATE aqbasket SET basketgroupid = NULL WHERE basketgroupid = ?');
1008 $sth->execute($basketgroupinfo->{'id'});
1010 if($basketgroupinfo->{'basketlist'} && @
{$basketgroupinfo->{'basketlist'}}){
1011 $sth = $dbh->prepare("UPDATE aqbasket SET basketgroupid=? WHERE basketno=?");
1012 foreach my $basketno (@
{$basketgroupinfo->{'basketlist'}}) {
1013 $sth->execute($basketgroupinfo->{'id'}, $basketno);
1019 #------------------------------------------------------------#
1021 =head3 DelBasketgroup
1023 DelBasketgroup($basketgroupid);
1025 Deletes a basketgroup in the aqbasketgroups table, and removes the reference to it from the baskets,
1029 =item C<$basketgroupid> is the 'id' field of the basket in the aqbasketgroup table
1035 sub DelBasketgroup
{
1036 my $basketgroupid = shift;
1037 die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
1038 my $query = "DELETE FROM aqbasketgroups WHERE id=?";
1039 my $dbh = C4
::Context
->dbh;
1040 my $sth = $dbh->prepare($query);
1041 $sth->execute($basketgroupid);
1045 #------------------------------------------------------------#
1048 =head2 FUNCTIONS ABOUT ORDERS
1050 =head3 GetBasketgroup
1052 $basketgroup = &GetBasketgroup($basketgroupid);
1054 Returns a reference to the hash containing all information about the basketgroup.
1058 sub GetBasketgroup
{
1059 my $basketgroupid = shift;
1060 die "basketgroup id is required to edit a basketgroup" unless $basketgroupid;
1061 my $dbh = C4
::Context
->dbh;
1062 my $result_set = $dbh->selectall_arrayref(
1063 'SELECT * FROM aqbasketgroups WHERE id=?',
1067 return $result_set->[0]; # id is unique
1070 #------------------------------------------------------------#
1072 =head3 GetBasketgroups
1074 $basketgroups = &GetBasketgroups($booksellerid);
1076 Returns a reference to the array of all the basketgroups of bookseller $booksellerid.
1080 sub GetBasketgroups
{
1081 my $booksellerid = shift;
1082 die 'bookseller id is required to edit a basketgroup' unless $booksellerid;
1083 my $query = 'SELECT * FROM aqbasketgroups WHERE booksellerid=? ORDER BY id DESC';
1084 my $dbh = C4
::Context
->dbh;
1085 my $sth = $dbh->prepare($query);
1086 $sth->execute($booksellerid);
1087 return $sth->fetchall_arrayref({});
1090 #------------------------------------------------------------#
1092 =head2 FUNCTIONS ABOUT ORDERS
1096 @orders = &GetOrders( $basketno, { orderby => 'biblio.title', cancelled => 0|1 } );
1098 Looks up the pending (non-cancelled) orders with the given basket
1101 If cancelled is set, only cancelled orders will be returned.
1106 my ( $basketno, $params ) = @_;
1108 return () unless $basketno;
1110 my $orderby = $params->{orderby
};
1111 my $cancelled = $params->{cancelled
} || 0;
1113 my $dbh = C4
::Context
->dbh;
1115 SELECT biblio
.*,biblioitems
.*,
1119 $query .= $cancelled
1121 aqorders_transfers
.ordernumber_to AS transferred_to
,
1122 aqorders_transfers
.timestamp AS transferred_to_timestamp
1125 aqorders_transfers
.ordernumber_from AS transferred_from
,
1126 aqorders_transfers
.timestamp AS transferred_from_timestamp
1130 LEFT JOIN aqbudgets ON aqbudgets
.budget_id
= aqorders
.budget_id
1131 LEFT JOIN biblio ON biblio
.biblionumber
= aqorders
.biblionumber
1132 LEFT JOIN biblioitems ON biblioitems
.biblionumber
=biblio
.biblionumber
1134 $query .= $cancelled
1136 LEFT JOIN aqorders_transfers ON aqorders_transfers
.ordernumber_from
= aqorders
.ordernumber
1139 LEFT JOIN aqorders_transfers ON aqorders_transfers
.ordernumber_to
= aqorders
.ordernumber
1147 $orderby ||= q
|biblioitems
.publishercode
, biblio
.title
|;
1149 AND
(datecancellationprinted IS NOT NULL
1150 AND datecancellationprinted
<> '0000-00-00')
1155 q
|aqorders
.datecancellationprinted desc
, aqorders
.timestamp desc
|;
1157 AND
(datecancellationprinted IS NULL OR datecancellationprinted
='0000-00-00')
1161 $query .= " ORDER BY $orderby";
1163 $dbh->selectall_arrayref( $query, { Slice
=> {} }, $basketno );
1168 #------------------------------------------------------------#
1170 =head3 GetOrdersByBiblionumber
1172 @orders = &GetOrdersByBiblionumber($biblionumber);
1174 Looks up the orders with linked to a specific $biblionumber, including
1175 cancelled orders and received orders.
1178 C<@orders> is an array of references-to-hash, whose keys are the
1179 fields from the aqorders, biblio, and biblioitems tables in the Koha database.
1183 sub GetOrdersByBiblionumber
{
1184 my $biblionumber = shift;
1185 return unless $biblionumber;
1186 my $dbh = C4
::Context
->dbh;
1188 SELECT biblio.*,biblioitems.*,
1192 LEFT JOIN aqbudgets ON aqbudgets.budget_id = aqorders.budget_id
1193 LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
1194 LEFT JOIN biblioitems ON biblioitems.biblionumber =biblio.biblionumber
1195 WHERE aqorders.biblionumber=?
1198 $dbh->selectall_arrayref( $query, { Slice
=> {} }, $biblionumber );
1199 return @
{$result_set};
1203 #------------------------------------------------------------#
1207 $order = &GetOrder($ordernumber);
1209 Looks up an order by order number.
1211 Returns a reference-to-hash describing the order. The keys of
1212 C<$order> are fields from the biblio, biblioitems, aqorders tables of the Koha database.
1217 my ($ordernumber) = @_;
1218 return unless $ordernumber;
1220 my $dbh = C4
::Context
->dbh;
1221 my $query = qq{SELECT
1225 aqbasket
.basketname
,
1226 borrowers
.branchcode
,
1227 biblioitems
.publicationyear
,
1228 biblio
.copyrightdate
,
1229 biblioitems
.editionstatement
,
1233 biblioitems
.publishercode
,
1234 aqorders
.rrp AS unitpricesupplier
,
1235 aqorders
.ecost AS unitpricelib
,
1236 aqorders
.claims_count AS claims_count
,
1237 aqorders
.claimed_date AS claimed_date
,
1238 aqbudgets
.budget_name AS budget
,
1239 aqbooksellers
.name AS supplier
,
1240 aqbooksellers
.id AS supplierid
,
1241 biblioitems
.publishercode AS publisher
,
1242 ADDDATE
(aqbasket
.closedate
, INTERVAL aqbooksellers
.deliverytime DAY
) AS estimateddeliverydate
,
1243 DATE
(aqbasket
.closedate
) AS orderdate
,
1244 aqorders
.quantity
- COALESCE
(aqorders
.quantityreceived
,0) AS quantity_to_receive
,
1245 (aqorders
.quantity
- COALESCE
(aqorders
.quantityreceived
,0)) * aqorders
.rrp AS subtotal
,
1246 DATEDIFF
(CURDATE
( ),closedate
) AS latesince
1247 FROM aqorders LEFT JOIN biblio ON biblio
.biblionumber
= aqorders
.biblionumber
1248 LEFT JOIN biblioitems ON biblioitems
.biblionumber
= biblio
.biblionumber
1249 LEFT JOIN aqbudgets ON aqorders
.budget_id
= aqbudgets
.budget_id
,
1250 aqbasket LEFT JOIN borrowers ON aqbasket
.authorisedby
= borrowers
.borrowernumber
1251 LEFT JOIN aqbooksellers ON aqbasket
.booksellerid
= aqbooksellers
.id
1252 WHERE aqorders
.basketno
= aqbasket
.basketno
1255 $dbh->selectall_arrayref( $query, { Slice
=> {} }, $ordernumber );
1257 # result_set assumed to contain 1 match
1258 return $result_set->[0];
1261 =head3 GetLastOrderNotReceivedFromSubscriptionid
1263 $order = &GetLastOrderNotReceivedFromSubscriptionid($subscriptionid);
1265 Returns a reference-to-hash describing the last order not received for a subscription.
1269 sub GetLastOrderNotReceivedFromSubscriptionid
{
1270 my ( $subscriptionid ) = @_;
1271 my $dbh = C4
::Context
->dbh;
1273 SELECT
* FROM aqorders
1274 LEFT JOIN subscription
1275 ON
( aqorders
.subscriptionid
= subscription
.subscriptionid
)
1276 WHERE aqorders
.subscriptionid
= ?
1277 AND aqorders
.datereceived IS NULL
1281 $dbh->selectall_arrayref( $query, { Slice
=> {} }, $subscriptionid );
1283 # result_set assumed to contain 1 match
1284 return $result_set->[0];
1287 =head3 GetLastOrderReceivedFromSubscriptionid
1289 $order = &GetLastOrderReceivedFromSubscriptionid($subscriptionid);
1291 Returns a reference-to-hash describing the last order received for a subscription.
1295 sub GetLastOrderReceivedFromSubscriptionid
{
1296 my ( $subscriptionid ) = @_;
1297 my $dbh = C4
::Context
->dbh;
1299 SELECT
* FROM aqorders
1300 LEFT JOIN subscription
1301 ON
( aqorders
.subscriptionid
= subscription
.subscriptionid
)
1302 WHERE aqorders
.subscriptionid
= ?
1303 AND aqorders
.datereceived
=
1305 SELECT MAX
( aqorders
.datereceived
)
1307 LEFT JOIN subscription
1308 ON
( aqorders
.subscriptionid
= subscription
.subscriptionid
)
1309 WHERE aqorders
.subscriptionid
= ?
1310 AND aqorders
.datereceived IS NOT NULL
1312 ORDER BY ordernumber DESC
1316 $dbh->selectall_arrayref( $query, { Slice
=> {} }, $subscriptionid, $subscriptionid );
1318 # result_set assumed to contain 1 match
1319 return $result_set->[0];
1323 #------------------------------------------------------------#
1327 &ModOrder(\%hashref);
1329 Modifies an existing order. Updates the order with order number
1330 $hashref->{'ordernumber'} and biblionumber $hashref->{'biblionumber'}. All
1331 other keys of the hash update the fields with the same name in the aqorders
1332 table of the Koha database.
1337 my $orderinfo = shift;
1339 die "Ordernumber is required" if $orderinfo->{'ordernumber'} eq '';
1341 my $dbh = C4
::Context
->dbh;
1344 # update uncertainprice to an integer, just in case (under FF, checked boxes have the value "ON" by default)
1345 $orderinfo->{uncertainprice
}=1 if $orderinfo->{uncertainprice
};
1347 # delete($orderinfo->{'branchcode'});
1348 # the hash contains a lot of entries not in aqorders, so get the columns ...
1349 my $sth = $dbh->prepare("SELECT * FROM aqorders LIMIT 1;");
1351 my $colnames = $sth->{NAME
};
1352 #FIXME Be careful. If aqorders would have columns with diacritics,
1353 #you should need to decode what you get back from NAME.
1354 #See report 10110 and guided_reports.pl
1355 my $query = "UPDATE aqorders SET ";
1357 foreach my $orderinfokey (grep(!/ordernumber/, keys %$orderinfo)){
1358 # ... and skip hash entries that are not in the aqorders table
1359 # FIXME : probably not the best way to do it (would be better to have a correct hash)
1360 next unless grep(/^$orderinfokey$/, @
$colnames);
1361 $query .= "$orderinfokey=?, ";
1362 push(@params, $orderinfo->{$orderinfokey});
1365 $query .= "timestamp=NOW() WHERE ordernumber=?";
1366 push(@params, $orderinfo->{'ordernumber'} );
1367 $sth = $dbh->prepare($query);
1368 $sth->execute(@params);
1372 #------------------------------------------------------------#
1376 ModItemOrder($itemnumber, $ordernumber);
1378 Modifies the ordernumber of an item in aqorders_items.
1383 my ($itemnumber, $ordernumber) = @_;
1385 return unless ($itemnumber and $ordernumber);
1387 my $dbh = C4
::Context
->dbh;
1389 UPDATE aqorders_items
1391 WHERE itemnumber
= ?
1393 my $sth = $dbh->prepare($query);
1394 return $sth->execute($ordernumber, $itemnumber);
1397 #------------------------------------------------------------#
1399 =head3 ModReceiveOrder
1401 my ( $date_received, $new_ordernumber ) = ModReceiveOrder(
1403 biblionumber => $biblionumber,
1405 quantityreceived => $quantityreceived,
1407 invoice => $invoice,
1408 budget_id => $budget_id,
1409 received_itemnumbers => \@received_itemnumbers,
1410 order_internalnote => $order_internalnote,
1414 Updates an order, to reflect the fact that it was received, at least
1417 If a partial order is received, splits the order into two.
1419 Updates the order with biblionumber C<$biblionumber> and ordernumber
1420 C<$order->{ordernumber}>.
1425 sub ModReceiveOrder
{
1427 my $biblionumber = $params->{biblionumber
};
1428 my $order = { %{ $params->{order
} } }; # Copy the order, we don't want to modify it
1429 my $invoice = $params->{invoice
};
1430 my $quantrec = $params->{quantityreceived
};
1431 my $user = $params->{user
};
1432 my $budget_id = $params->{budget_id
};
1433 my $received_items = $params->{received_items
};
1435 my $dbh = C4
::Context
->dbh;
1436 my $datereceived = ( $invoice and $invoice->{datereceived
} ) ?
$invoice->{datereceived
} : dt_from_string
;
1437 my $suggestionid = GetSuggestionFromBiblionumber
( $biblionumber );
1438 if ($suggestionid) {
1439 ModSuggestion
( {suggestionid
=>$suggestionid,
1440 STATUS
=>'AVAILABLE',
1441 biblionumber
=> $biblionumber}
1445 my $result_set = $dbh->selectrow_arrayref(
1446 q{SELECT aqbasket.is_standing
1448 WHERE basketno=?},{ Slice
=> {} }, $order->{basketno
});
1449 my $is_standing = $result_set->[0]; # we assume we have a unique basket
1451 my $new_ordernumber = $order->{ordernumber
};
1452 if ( $is_standing || $order->{quantity
} > $quantrec ) {
1453 # Split order line in two parts: the first is the original order line
1454 # without received items (the quantity is decreased),
1455 # the second part is a new order line with quantity=quantityrec
1456 # (entirely received)
1460 orderstatus
= 'partial'|;
1461 $query .= q
|, order_internalnote
= ?
| if defined $order->{order_internalnote
};
1462 $query .= q
| WHERE ordernumber
= ?
|;
1463 my $sth = $dbh->prepare($query);
1466 ( $is_standing ?
1 : ($order->{quantity
} - $quantrec) ),
1467 ( defined $order->{order_internalnote
} ?
$order->{order_internalnote
} : () ),
1468 $order->{ordernumber
}
1471 # Recalculate tax_value
1475 tax_value_on_ordering
= quantity
* ecost_tax_excluded
* tax_rate_on_ordering
,
1476 tax_value_on_receiving
= quantity
* unitprice_tax_excluded
* tax_rate_on_receiving
1477 WHERE ordernumber
= ?
1478 |, undef, $order->{ordernumber
});
1480 delete $order->{ordernumber
};
1481 $order->{budget_id
} = ( $budget_id || $order->{budget_id
} );
1482 $order->{quantity
} = $quantrec;
1483 $order->{quantityreceived
} = $quantrec;
1484 $order->{ecost_tax_excluded
} //= 0;
1485 $order->{tax_rate_on_ordering
} //= 0;
1486 $order->{unitprice_tax_excluded
} //= 0;
1487 $order->{tax_rate_on_receiving
} //= 0;
1488 $order->{tax_value_on_ordering
} = $order->{quantity
} * $order->{ecost_tax_excluded
} * $order->{tax_rate_on_ordering
};
1489 $order->{tax_value_on_receiving
} = $order->{quantity
} * $order->{unitprice_tax_excluded
} * $order->{tax_rate_on_receiving
};
1490 $order->{datereceived
} = $datereceived;
1491 $order->{invoiceid
} = $invoice->{invoiceid
};
1492 $order->{orderstatus
} = 'complete';
1493 $new_ordernumber = Koha
::Acquisition
::Order
->new($order)->store->ordernumber; # TODO What if the store fails?
1495 if ($received_items) {
1496 foreach my $itemnumber (@
$received_items) {
1497 ModItemOrder
($itemnumber, $new_ordernumber);
1503 SET quantityreceived
= ?
,
1507 orderstatus
= 'complete'
1511 , unitprice
= ?
, unitprice_tax_included
= ?
, unitprice_tax_excluded
= ?
1512 | if defined $order->{unitprice
};
1515 ,tax_value_on_receiving
= ?
1516 | if defined $order->{tax_value_on_receiving
};
1519 ,tax_rate_on_receiving
= ?
1520 | if defined $order->{tax_rate_on_receiving
};
1523 , order_internalnote
= ?
1524 | if defined $order->{order_internalnote
};
1526 $query .= q
| where biblionumber
=?
and ordernumber
=?
|;
1528 my $sth = $dbh->prepare( $query );
1529 my @params = ( $quantrec, $datereceived, $invoice->{invoiceid
}, ( $budget_id ?
$budget_id : $order->{budget_id
} ) );
1531 if ( defined $order->{unitprice
} ) {
1532 push @params, $order->{unitprice
}, $order->{unitprice_tax_included
}, $order->{unitprice_tax_excluded
};
1535 if ( defined $order->{tax_value_on_receiving
} ) {
1536 push @params, $order->{tax_value_on_receiving
};
1539 if ( defined $order->{tax_rate_on_receiving
} ) {
1540 push @params, $order->{tax_rate_on_receiving
};
1543 if ( defined $order->{order_internalnote
} ) {
1544 push @params, $order->{order_internalnote
};
1547 push @params, ( $biblionumber, $order->{ordernumber
} );
1549 $sth->execute( @params );
1551 # All items have been received, sent a notification to users
1552 NotifyOrderUsers
( $order->{ordernumber
} );
1555 return ($datereceived, $new_ordernumber);
1558 =head3 CancelReceipt
1560 my $parent_ordernumber = CancelReceipt($ordernumber);
1562 Cancel an order line receipt and update the parent order line, as if no
1564 If items are created at receipt (AcqCreateItem = receiving) then delete
1570 my $ordernumber = shift;
1572 return unless $ordernumber;
1574 my $dbh = C4
::Context
->dbh;
1576 SELECT datereceived
, parent_ordernumber
, quantity
1578 WHERE ordernumber
= ?
1580 my $sth = $dbh->prepare($query);
1581 $sth->execute($ordernumber);
1582 my $order = $sth->fetchrow_hashref;
1584 warn "CancelReceipt: order $ordernumber does not exist";
1587 unless($order->{'datereceived'}) {
1588 warn "CancelReceipt: order $ordernumber is not received";
1592 my $parent_ordernumber = $order->{'parent_ordernumber'};
1594 my @itemnumbers = GetItemnumbersFromOrder
( $ordernumber );
1595 my $order_obj = Koha
::Acquisition
::Orders
->find( $ordernumber ); # FIXME rewrite all this subroutine using this object
1597 if($parent_ordernumber == $ordernumber || not $parent_ordernumber) {
1598 # The order line has no parent, just mark it as not received
1601 SET quantityreceived
= ?
,
1604 orderstatus
= 'ordered'
1605 WHERE ordernumber
= ?
1607 $sth = $dbh->prepare($query);
1608 $sth->execute(0, undef, undef, $ordernumber);
1609 _cancel_items_receipt
( $order_obj );
1611 # The order line has a parent, increase parent quantity and delete
1614 SELECT quantity
, datereceived
1616 WHERE ordernumber
= ?
1618 $sth = $dbh->prepare($query);
1619 $sth->execute($parent_ordernumber);
1620 my $parent_order = $sth->fetchrow_hashref;
1621 unless($parent_order) {
1622 warn "Parent order $parent_ordernumber does not exist.";
1625 if($parent_order->{'datereceived'}) {
1626 warn "CancelReceipt: parent order is received.".
1627 " Can't cancel receipt.";
1633 orderstatus
= 'ordered'
1634 WHERE ordernumber
= ?
1636 $sth = $dbh->prepare($query);
1637 my $rv = $sth->execute(
1638 $order->{'quantity'} + $parent_order->{'quantity'},
1642 warn "Cannot update parent order line, so do not cancel".
1647 # Recalculate tax_value
1651 tax_value_on_ordering
= quantity
* ecost_tax_excluded
* tax_rate_on_ordering
,
1652 tax_value_on_receiving
= quantity
* unitprice_tax_excluded
* tax_rate_on_receiving
1653 WHERE ordernumber
= ?
1654 |, undef, $parent_ordernumber);
1656 _cancel_items_receipt
( $order_obj, $parent_ordernumber );
1659 DELETE FROM aqorders
1660 WHERE ordernumber
= ?
1662 $sth = $dbh->prepare($query);
1663 $sth->execute($ordernumber);
1667 if( $order_obj->basket->effective_create_items eq 'ordering' ) {
1668 my @affects = split q{\|}, C4
::Context
->preference("AcqItemSetSubfieldsWhenReceiptIsCancelled");
1670 for my $in ( @itemnumbers ) {
1671 my $item = Koha
::Items
->find( $in );
1672 my $biblio = $item->biblio;
1673 my ( $itemfield ) = GetMarcFromKohaField
( 'items.itemnumber', $biblio->frameworkcode );
1674 my $item_marc = C4
::Items
::GetMarcItem
( $biblio->biblionumber, $in );
1675 for my $affect ( @affects ) {
1676 my ( $sf, $v ) = split q{=}, $affect, 2;
1677 foreach ( $item_marc->field($itemfield) ) {
1678 $_->update( $sf => $v );
1681 C4
::Items
::ModItemFromMarc
( $item_marc, $biblio->biblionumber, $in );
1686 return $parent_ordernumber;
1689 sub _cancel_items_receipt
{
1690 my ( $order, $parent_ordernumber ) = @_;
1691 $parent_ordernumber ||= $order->ordernumber;
1693 my @itemnumbers = GetItemnumbersFromOrder
($order->ordernumber); # FIXME Must be $order->items
1694 if ( $order->basket->effective_create_items eq 'receiving' ) {
1695 # Remove items that were created at receipt
1697 DELETE FROM items
, aqorders_items
1698 USING items
, aqorders_items
1699 WHERE items
.itemnumber
= ? AND aqorders_items
.itemnumber
= ?
1701 my $dbh = C4
::Context
->dbh;
1702 my $sth = $dbh->prepare($query);
1703 foreach my $itemnumber (@itemnumbers) {
1704 $sth->execute($itemnumber, $itemnumber);
1708 foreach my $itemnumber (@itemnumbers) {
1709 ModItemOrder
($itemnumber, $parent_ordernumber);
1714 #------------------------------------------------------------#
1718 @results = &SearchOrders({
1719 ordernumber => $ordernumber,
1722 booksellerid => $booksellerid,
1723 basketno => $basketno,
1724 basketname => $basketname,
1725 basketgroupname => $basketgroupname,
1729 biblionumber => $biblionumber,
1730 budget_id => $budget_id
1733 Searches for orders filtered by criteria.
1735 C<$ordernumber> Finds matching orders or transferred orders by ordernumber.
1736 C<$search> Finds orders matching %$search% in title, author, or isbn.
1737 C<$owner> Finds order for the logged in user.
1738 C<$pending> Finds pending orders. Ignores completed and cancelled orders.
1739 C<$ordered> Finds orders to receive only (status 'ordered' or 'partial').
1742 C<@results> is an array of references-to-hash with the keys are fields
1743 from aqorders, biblio, biblioitems and aqbasket tables.
1748 my ( $params ) = @_;
1749 my $ordernumber = $params->{ordernumber
};
1750 my $search = $params->{search
};
1751 my $ean = $params->{ean
};
1752 my $booksellerid = $params->{booksellerid
};
1753 my $basketno = $params->{basketno
};
1754 my $basketname = $params->{basketname
};
1755 my $basketgroupname = $params->{basketgroupname
};
1756 my $owner = $params->{owner
};
1757 my $pending = $params->{pending
};
1758 my $ordered = $params->{ordered
};
1759 my $biblionumber = $params->{biblionumber
};
1760 my $budget_id = $params->{budget_id
};
1762 my $dbh = C4
::Context
->dbh;
1765 SELECT aqbasket.basketno,
1767 borrowers.firstname,
1770 biblioitems.biblioitemnumber,
1771 biblioitems.publishercode,
1772 biblioitems.publicationyear,
1773 aqbasket.authorisedby,
1774 aqbasket.booksellerid,
1776 aqbasket.creationdate,
1777 aqbasket.basketname,
1778 aqbasketgroups.id as basketgroupid,
1779 aqbasketgroups.name as basketgroupname,
1782 LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
1783 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid = aqbasketgroups.id
1784 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
1785 LEFT JOIN biblio ON aqorders.biblionumber=biblio.biblionumber
1786 LEFT JOIN biblioitems ON biblioitems.biblionumber=biblio.biblionumber
1789 # If we search on ordernumber, we retrieve the transferred order if a transfer has been done.
1791 LEFT JOIN aqorders_transfers ON aqorders_transfers.ordernumber_to = aqorders.ordernumber
1795 WHERE (datecancellationprinted is NULL)
1798 if ( $pending or $ordered ) {
1801 ( aqbasket.is_standing AND aqorders.orderstatus IN ( "new", "ordered", "partial" ) )
1803 ( quantity > quantityreceived OR quantityreceived is NULL )
1807 $query .= q{ AND aqorders.orderstatus IN ( "ordered", "partial" )};
1815 my $userenv = C4
::Context
->userenv;
1816 if ( C4
::Context
->preference("IndependentBranches") ) {
1817 unless ( C4
::Context
->IsSuperLibrarian() ) {
1820 borrowers.branchcode = ?
1821 OR borrowers.branchcode = ''
1824 push @args, $userenv->{branch
};
1828 if ( $ordernumber ) {
1829 $query .= ' AND ( aqorders.ordernumber = ? OR aqorders_transfers.ordernumber_from = ? ) ';
1830 push @args, ( $ordernumber, $ordernumber );
1832 if ( $biblionumber ) {
1833 $query .= 'AND aqorders.biblionumber = ?';
1834 push @args, $biblionumber;
1837 $query .= ' AND (biblio.title LIKE ? OR biblio.author LIKE ? OR biblioitems.isbn LIKE ?)';
1838 push @args, ("%$search%","%$search%","%$search%");
1841 $query .= ' AND biblioitems.ean = ?';
1844 if ( $booksellerid ) {
1845 $query .= 'AND aqbasket.booksellerid = ?';
1846 push @args, $booksellerid;
1849 $query .= 'AND aqbasket.basketno = ?';
1850 push @args, $basketno;
1853 $query .= 'AND aqbasket.basketname LIKE ?';
1854 push @args, "%$basketname%";
1856 if( $basketgroupname ) {
1857 $query .= ' AND aqbasketgroups.name LIKE ?';
1858 push @args, "%$basketgroupname%";
1862 $query .= ' AND aqbasket.authorisedby=? ';
1863 push @args, $userenv->{'number'};
1867 $query .= ' AND aqorders.budget_id = ?';
1868 push @args, $budget_id;
1871 $query .= ' ORDER BY aqbasket.basketno';
1873 my $sth = $dbh->prepare($query);
1874 $sth->execute(@args);
1875 return $sth->fetchall_arrayref({});
1878 #------------------------------------------------------------#
1882 &DelOrder($biblionumber, $ordernumber);
1884 Cancel the order with the given order and biblio numbers. It does not
1885 delete any entries in the aqorders table, it merely marks them as
1891 my ( $bibnum, $ordernumber, $delete_biblio, $reason ) = @_;
1894 my $dbh = C4
::Context
->dbh;
1897 SET datecancellationprinted=now(), orderstatus='cancelled'
1900 $query .= ", cancellationreason = ? ";
1903 WHERE biblionumber=? AND ordernumber=?
1905 my $sth = $dbh->prepare($query);
1907 $sth->execute($reason, $bibnum, $ordernumber);
1909 $sth->execute( $bibnum, $ordernumber );
1913 my @itemnumbers = GetItemnumbersFromOrder
( $ordernumber );
1914 foreach my $itemnumber (@itemnumbers){
1915 my $delcheck = C4
::Items
::DelItemCheck
( $bibnum, $itemnumber );
1917 if($delcheck != 1) {
1918 $error->{'delitem'} = 1;
1922 if($delete_biblio) {
1923 # We get the number of remaining items
1924 my $biblio = Koha
::Biblios
->find( $bibnum );
1925 my $itemcount = $biblio->items->count;
1927 # If there are no items left,
1928 if ( $itemcount == 0 ) {
1929 # We delete the record
1930 my $delcheck = DelBiblio
($bibnum);
1933 $error->{'delbiblio'} = 1;
1941 =head3 TransferOrder
1943 my $newordernumber = TransferOrder($ordernumber, $basketno);
1945 Transfer an order line to a basket.
1946 Mark $ordernumber as cancelled with an internal note 'Cancelled and transferred
1947 to BOOKSELLER on DATE' and create new order with internal note
1948 'Transferred from BOOKSELLER on DATE'.
1949 Move all attached items to the new order.
1950 Received orders cannot be transferred.
1951 Return the ordernumber of created order.
1956 my ($ordernumber, $basketno) = @_;
1958 return unless ($ordernumber and $basketno);
1960 my $order = Koha
::Acquisition
::Orders
->find( $ordernumber ) or return;
1961 return if $order->datereceived;
1963 $order = $order->unblessed;
1965 my $basket = GetBasket
($basketno);
1966 return unless $basket;
1968 my $dbh = C4
::Context
->dbh;
1969 my ($query, $sth, $rv);
1973 SET datecancellationprinted = CAST(NOW() AS date), orderstatus = ?
1974 WHERE ordernumber = ?
1976 $sth = $dbh->prepare($query);
1977 $rv = $sth->execute('cancelled', $ordernumber);
1979 delete $order->{'ordernumber'};
1980 delete $order->{parent_ordernumber
};
1981 $order->{'basketno'} = $basketno;
1983 my $newordernumber = Koha
::Acquisition
::Order
->new($order)->store->ordernumber;
1986 UPDATE aqorders_items
1988 WHERE ordernumber = ?
1990 $sth = $dbh->prepare($query);
1991 $sth->execute($newordernumber, $ordernumber);
1994 INSERT INTO aqorders_transfers (ordernumber_from, ordernumber_to)
1997 $sth = $dbh->prepare($query);
1998 $sth->execute($ordernumber, $newordernumber);
2000 return $newordernumber;
2003 =head2 FUNCTIONS ABOUT PARCELS
2007 $results = &GetParcels($bookseller, $order, $code, $datefrom, $dateto);
2009 get a lists of parcels.
2016 is the bookseller this function has to get parcels.
2019 To know on what criteria the results list has to be ordered.
2022 is the booksellerinvoicenumber.
2024 =item $datefrom & $dateto
2025 to know on what date this function has to filter its search.
2030 a pointer on a hash list containing parcel informations as such :
2036 =item Last operation
2038 =item Number of biblio
2040 =item Number of items
2047 my ($bookseller,$order, $code, $datefrom, $dateto) = @_;
2048 my $dbh = C4
::Context
->dbh;
2049 my @query_params = ();
2051 SELECT aqinvoices.invoicenumber,
2052 datereceived,purchaseordernumber,
2053 count(DISTINCT biblionumber) AS biblio,
2054 sum(quantity) AS itemsexpected,
2055 sum(quantityreceived) AS itemsreceived
2056 FROM aqorders LEFT JOIN aqbasket ON aqbasket.basketno = aqorders.basketno
2057 LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
2058 WHERE aqbasket.booksellerid = ? and datereceived IS NOT NULL
2060 push @query_params, $bookseller;
2062 if ( defined $code ) {
2063 $strsth .= ' and aqinvoices.invoicenumber like ? ';
2064 # add a % to the end of the code to allow stemming.
2065 push @query_params, "$code%";
2068 if ( defined $datefrom ) {
2069 $strsth .= ' and datereceived >= ? ';
2070 push @query_params, $datefrom;
2073 if ( defined $dateto ) {
2074 $strsth .= 'and datereceived <= ? ';
2075 push @query_params, $dateto;
2078 $strsth .= "group by aqinvoices.invoicenumber,datereceived ";
2080 # can't use a placeholder to place this column name.
2081 # but, we could probably be checking to make sure it is a column that will be fetched.
2082 $strsth .= "order by $order " if ($order);
2084 my $sth = $dbh->prepare($strsth);
2086 $sth->execute( @query_params );
2087 my $results = $sth->fetchall_arrayref({});
2091 #------------------------------------------------------------#
2093 =head3 GetLateOrders
2095 @results = &GetLateOrders;
2097 Searches for bookseller with late orders.
2100 the table of supplier with late issues. This table is full of hashref.
2106 my $supplierid = shift;
2108 my $estimateddeliverydatefrom = shift;
2109 my $estimateddeliverydateto = shift;
2111 my $dbh = C4
::Context
->dbh;
2113 #BEWARE, order of parenthesis and LEFT JOIN is important for speed
2114 my $dbdriver = C4
::Context
->config("db_scheme") || "mysql";
2116 my @query_params = ();
2118 SELECT aqbasket.basketno,
2119 aqorders.ordernumber,
2120 DATE(aqbasket.closedate) AS orderdate,
2121 aqbasket.basketname AS basketname,
2122 aqbasket.basketgroupid AS basketgroupid,
2123 aqbasketgroups.name AS basketgroupname,
2124 aqorders.rrp AS unitpricesupplier,
2125 aqorders.ecost AS unitpricelib,
2126 aqorders.claims_count AS claims_count,
2127 aqorders.claimed_date AS claimed_date,
2128 aqbudgets.budget_name AS budget,
2129 borrowers.branchcode AS branch,
2130 aqbooksellers.name AS supplier,
2131 aqbooksellers.id AS supplierid,
2132 biblio.author, biblio.title,
2133 biblioitems.publishercode AS publisher,
2134 biblioitems.publicationyear,
2135 ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) AS estimateddeliverydate,
2139 aqorders LEFT JOIN biblio ON biblio.biblionumber = aqorders.biblionumber
2140 LEFT JOIN biblioitems ON biblioitems.biblionumber = biblio.biblionumber
2141 LEFT JOIN aqbudgets ON aqorders.budget_id = aqbudgets.budget_id,
2142 aqbasket LEFT JOIN borrowers ON aqbasket.authorisedby = borrowers.borrowernumber
2143 LEFT JOIN aqbooksellers ON aqbasket.booksellerid = aqbooksellers.id
2144 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid = aqbasketgroups.id
2145 WHERE aqorders.basketno = aqbasket.basketno
2146 AND ( datereceived = ''
2147 OR datereceived IS NULL
2148 OR aqorders.quantityreceived < aqorders.quantity
2150 AND aqbasket.closedate IS NOT NULL
2151 AND (aqorders.datecancellationprinted IS NULL OR aqorders.datecancellationprinted='0000-00-00')
2153 if ($dbdriver eq "mysql") {
2155 aqorders.quantity - COALESCE(aqorders.quantityreceived,0) AS quantity,
2156 (aqorders.quantity - COALESCE(aqorders.quantityreceived,0)) * aqorders.rrp AS subtotal,
2157 DATEDIFF(CAST(now() AS date),closedate) AS latesince
2159 if ( defined $delay ) {
2160 $from .= " AND (closedate <= DATE_SUB(CAST(now() AS date),INTERVAL ? DAY)) " ;
2161 push @query_params, $delay;
2163 $from .= " AND aqorders.quantity - COALESCE(aqorders.quantityreceived,0) <> 0";
2165 # FIXME: account for IFNULL as above
2167 aqorders.quantity AS quantity,
2168 aqorders.quantity * aqorders.rrp AS subtotal,
2169 (CAST(now() AS date) - closedate) AS latesince
2171 if ( defined $delay ) {
2172 $from .= " AND (closedate <= (CAST(now() AS date) -(INTERVAL ? DAY)) ";
2173 push @query_params, $delay;
2175 $from .= " AND aqorders.quantity <> 0";
2177 if (defined $supplierid) {
2178 $from .= ' AND aqbasket.booksellerid = ? ';
2179 push @query_params, $supplierid;
2181 if (defined $branch) {
2182 $from .= ' AND borrowers.branchcode LIKE ? ';
2183 push @query_params, $branch;
2186 if ( defined $estimateddeliverydatefrom or defined $estimateddeliverydateto ) {
2187 $from .= ' AND aqbooksellers.deliverytime IS NOT NULL ';
2189 if ( defined $estimateddeliverydatefrom ) {
2190 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) >= ?';
2191 push @query_params, $estimateddeliverydatefrom;
2193 if ( defined $estimateddeliverydateto ) {
2194 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= ?';
2195 push @query_params, $estimateddeliverydateto;
2197 if ( defined $estimateddeliverydatefrom and not defined $estimateddeliverydateto ) {
2198 $from .= ' AND ADDDATE(aqbasket.closedate, INTERVAL aqbooksellers.deliverytime DAY) <= CAST(now() AS date)';
2200 if (C4
::Context
->preference("IndependentBranches")
2201 && !C4
::Context
->IsSuperLibrarian() ) {
2202 $from .= ' AND borrowers.branchcode LIKE ? ';
2203 push @query_params, C4
::Context
->userenv->{branch
};
2205 $from .= " AND orderstatus <> 'cancelled' ";
2206 my $query = "$select $from \nORDER BY latesince, basketno, borrowers.branchcode, supplier";
2207 $debug and print STDERR
"GetLateOrders query: $query\nGetLateOrders args: " . join(" ",@query_params);
2208 my $sth = $dbh->prepare($query);
2209 $sth->execute(@query_params);
2211 while (my $data = $sth->fetchrow_hashref) {
2212 push @results, $data;
2217 #------------------------------------------------------------#
2221 \@order_loop = GetHistory( %params );
2223 Retreives some acquisition history information
2233 basket - search both basket name and number
2234 booksellerinvoicenumber
2237 orderstatus (note that orderstatus '' will retrieve orders
2238 of any status except cancelled)
2240 get_canceled_order (if set to a true value, cancelled orders will
2244 $order_loop is a list of hashrefs that each look like this:
2246 'author' => 'Twain, Mark',
2248 'biblionumber' => '215',
2250 'creationdate' => 'MM/DD/YYYY',
2251 'datereceived' => undef,
2254 'invoicenumber' => undef,
2256 'ordernumber' => '1',
2258 'quantityreceived' => undef,
2259 'title' => 'The Adventures of Huckleberry Finn'
2265 # don't run the query if there are no parameters (list would be too long for sure !)
2266 croak
"No search params" unless @_;
2268 my $title = $params{title
};
2269 my $author = $params{author
};
2270 my $isbn = $params{isbn
};
2271 my $ean = $params{ean
};
2272 my $name = $params{name
};
2273 my $from_placed_on = $params{from_placed_on
};
2274 my $to_placed_on = $params{to_placed_on
};
2275 my $basket = $params{basket
};
2276 my $booksellerinvoicenumber = $params{booksellerinvoicenumber
};
2277 my $basketgroupname = $params{basketgroupname
};
2278 my $budget = $params{budget
};
2279 my $orderstatus = $params{orderstatus
};
2280 my $biblionumber = $params{biblionumber
};
2281 my $get_canceled_order = $params{get_canceled_order
} || 0;
2282 my $ordernumber = $params{ordernumber
};
2283 my $search_children_too = $params{search_children_too
} || 0;
2284 my $created_by = $params{created_by
} || [];
2288 my $total_qtyreceived = 0;
2289 my $total_price = 0;
2291 #get variation of isbn
2295 if ( C4
::Context
->preference("SearchWithISBNVariations") ){
2296 @isbns = C4
::Koha
::GetVariationsOfISBN
( $isbn );
2297 foreach my $isb (@isbns){
2298 push @isbn_params, '?';
2303 push @isbn_params, '?';
2307 my $dbh = C4
::Context
->dbh;
2310 COALESCE(biblio.title, deletedbiblio.title) AS title,
2311 COALESCE(biblio.author, deletedbiblio.author) AS author,
2312 COALESCE(biblioitems.isbn, deletedbiblioitems.isbn) AS isbn,
2313 COALESCE(biblioitems.ean, deletedbiblioitems.ean) AS ean,
2315 aqbasket.basketname,
2316 aqbasket.basketgroupid,
2317 aqbasket.authorisedby,
2318 concat( borrowers.firstname,' ',borrowers.surname) AS authorisedbyname,
2319 aqbasketgroups.name as groupname,
2321 aqbasket.creationdate,
2322 aqorders.datereceived,
2324 aqorders.quantityreceived,
2326 aqorders.ordernumber,
2328 aqinvoices.invoicenumber,
2329 aqbooksellers.id as id,
2330 aqorders.biblionumber,
2331 aqorders.orderstatus,
2332 aqorders.parent_ordernumber,
2333 aqbudgets.budget_name
2335 $query .= ", aqbudgets.budget_id AS budget" if defined $budget;
2338 LEFT JOIN aqbasket ON aqorders.basketno=aqbasket.basketno
2339 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid=aqbasketgroups.id
2340 LEFT JOIN aqbooksellers ON aqbasket.booksellerid=aqbooksellers.id
2341 LEFT JOIN biblioitems ON biblioitems.biblionumber=aqorders.biblionumber
2342 LEFT JOIN biblio ON biblio.biblionumber=aqorders.biblionumber
2343 LEFT JOIN aqbudgets ON aqorders.budget_id=aqbudgets.budget_id
2344 LEFT JOIN aqinvoices ON aqorders.invoiceid = aqinvoices.invoiceid
2345 LEFT JOIN deletedbiblio ON deletedbiblio.biblionumber=aqorders.biblionumber
2346 LEFT JOIN deletedbiblioitems ON deletedbiblioitems.biblionumber=aqorders.biblionumber
2347 LEFT JOIN borrowers ON aqbasket.authorisedby=borrowers.borrowernumber
2350 $query .= " WHERE 1 ";
2352 unless ($get_canceled_order or (defined $orderstatus and $orderstatus eq 'cancelled')) {
2353 $query .= " AND (datecancellationprinted is NULL or datecancellationprinted='0000-00-00') ";
2356 my @query_params = ();
2358 if ( $biblionumber ) {
2359 $query .= " AND biblio.biblionumber = ?";
2360 push @query_params, $biblionumber;
2364 $query .= " AND biblio.title LIKE ? ";
2365 $title =~ s/\s+/%/g;
2366 push @query_params, "%$title%";
2370 $query .= " AND biblio.author LIKE ? ";
2371 push @query_params, "%$author%";
2375 $query .= " AND ( biblioitems.isbn LIKE " . join (" OR biblioitems.isbn LIKE ", @isbn_params ) . ")";
2376 foreach my $isb (@isbns){
2377 push @query_params, "%$isb%";
2382 $query .= " AND biblioitems.ean = ? ";
2383 push @query_params, "$ean";
2386 $query .= " AND aqbooksellers.name LIKE ? ";
2387 push @query_params, "%$name%";
2391 $query .= " AND aqbudgets.budget_id = ? ";
2392 push @query_params, "$budget";
2395 if ( $from_placed_on ) {
2396 $query .= " AND creationdate >= ? ";
2397 push @query_params, $from_placed_on;
2400 if ( $to_placed_on ) {
2401 $query .= " AND creationdate <= ? ";
2402 push @query_params, $to_placed_on;
2405 if ( defined $orderstatus and $orderstatus ne '') {
2406 $query .= " AND aqorders.orderstatus = ? ";
2407 push @query_params, "$orderstatus";
2411 if ($basket =~ m/^\d+$/) {
2412 $query .= " AND aqorders.basketno = ? ";
2413 push @query_params, $basket;
2415 $query .= " AND aqbasket.basketname LIKE ? ";
2416 push @query_params, "%$basket%";
2420 if ($booksellerinvoicenumber) {
2421 $query .= " AND aqinvoices.invoicenumber LIKE ? ";
2422 push @query_params, "%$booksellerinvoicenumber%";
2425 if ($basketgroupname) {
2426 $query .= " AND aqbasketgroups.name LIKE ? ";
2427 push @query_params, "%$basketgroupname%";
2431 $query .= " AND (aqorders.ordernumber = ? ";
2432 push @query_params, $ordernumber;
2433 if ($search_children_too) {
2434 $query .= " OR aqorders.parent_ordernumber = ? ";
2435 push @query_params, $ordernumber;
2440 if ( @
$created_by ) {
2441 $query .= ' AND aqbasket.authorisedby IN ( ' . join( ',', ('?') x @
$created_by ) . ')';
2442 push @query_params, @
$created_by;
2446 if ( C4
::Context
->preference("IndependentBranches") ) {
2447 unless ( C4
::Context
->IsSuperLibrarian() ) {
2448 $query .= " AND (borrowers.branchcode = ? OR borrowers.branchcode ='' ) ";
2449 push @query_params, C4
::Context
->userenv->{branch
};
2452 $query .= " ORDER BY id";
2454 return $dbh->selectall_arrayref( $query, { Slice
=> {} }, @query_params );
2457 =head2 GetRecentAcqui
2459 $results = GetRecentAcqui($days);
2461 C<$results> is a ref to a table which contains hashref
2465 sub GetRecentAcqui
{
2467 my $dbh = C4
::Context
->dbh;
2471 ORDER BY timestamp DESC
2474 my $sth = $dbh->prepare($query);
2476 my $results = $sth->fetchall_arrayref({});
2480 #------------------------------------------------------------#
2484 &AddClaim($ordernumber);
2486 Add a claim for an order
2491 my ($ordernumber) = @_;
2492 my $dbh = C4
::Context
->dbh;
2495 claims_count = claims_count + 1,
2496 claimed_date = CURDATE()
2497 WHERE ordernumber = ?
2499 my $sth = $dbh->prepare($query);
2500 $sth->execute($ordernumber);
2505 my @invoices = GetInvoices(
2506 invoicenumber => $invoicenumber,
2507 supplierid => $supplierid,
2508 suppliername => $suppliername,
2509 shipmentdatefrom => $shipmentdatefrom, # ISO format
2510 shipmentdateto => $shipmentdateto, # ISO format
2511 billingdatefrom => $billingdatefrom, # ISO format
2512 billingdateto => $billingdateto, # ISO format
2513 isbneanissn => $isbn_or_ean_or_issn,
2516 publisher => $publisher,
2517 publicationyear => $publicationyear,
2518 branchcode => $branchcode,
2519 order_by => $order_by
2522 Return a list of invoices that match all given criteria.
2524 $order_by is "column_name (asc|desc)", where column_name is any of
2525 'invoicenumber', 'booksellerid', 'shipmentdate', 'billingdate', 'closedate',
2526 'shipmentcost', 'shipmentcost_budgetid'.
2528 asc is the default if omitted
2535 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2536 closedate shipmentcost shipmentcost_budgetid);
2538 my $dbh = C4
::Context
->dbh;
2540 SELECT aqinvoices
.invoiceid
, aqinvoices
.invoicenumber
, aqinvoices
.booksellerid
, aqinvoices
.shipmentdate
, aqinvoices
.billingdate
, aqinvoices
.closedate
, aqinvoices
.shipmentcost
, aqinvoices
.shipmentcost_budgetid
, aqinvoices
.message_id
,
2541 aqbooksellers
.name AS suppliername
,
2544 aqorders
.datereceived IS NOT NULL
,
2545 aqorders
.biblionumber
,
2548 ) AS receivedbiblios
,
2551 aqorders
.subscriptionid IS NOT NULL
,
2552 aqorders
.subscriptionid
,
2555 ) AS is_linked_to_subscriptions
,
2556 SUM
(aqorders
.quantityreceived
) AS receiveditems
2558 LEFT JOIN aqbooksellers ON aqbooksellers
.id
= aqinvoices
.booksellerid
2559 LEFT JOIN aqorders ON aqorders
.invoiceid
= aqinvoices
.invoiceid
2560 LEFT JOIN aqbasket ON aqbasket
.basketno
=aqorders
.basketno
2561 LEFT JOIN borrowers ON aqbasket
.authorisedby
=borrowers
.borrowernumber
2562 LEFT JOIN biblio ON aqorders
.biblionumber
= biblio
.biblionumber
2563 LEFT JOIN biblioitems ON biblio
.biblionumber
= biblioitems
.biblionumber
2564 LEFT JOIN subscription ON biblio
.biblionumber
= subscription
.biblionumber
2569 if($args{supplierid
}) {
2570 push @bind_strs, " aqinvoices.booksellerid = ? ";
2571 push @bind_args, $args{supplierid
};
2573 if($args{invoicenumber
}) {
2574 push @bind_strs, " aqinvoices.invoicenumber LIKE ? ";
2575 push @bind_args, "%$args{invoicenumber}%";
2577 if($args{suppliername
}) {
2578 push @bind_strs, " aqbooksellers.name LIKE ? ";
2579 push @bind_args, "%$args{suppliername}%";
2581 if($args{shipmentdatefrom
}) {
2582 push @bind_strs, " aqinvoices.shipmentdate >= ? ";
2583 push @bind_args, $args{shipmentdatefrom
};
2585 if($args{shipmentdateto
}) {
2586 push @bind_strs, " aqinvoices.shipmentdate <= ? ";
2587 push @bind_args, $args{shipmentdateto
};
2589 if($args{billingdatefrom
}) {
2590 push @bind_strs, " aqinvoices.billingdate >= ? ";
2591 push @bind_args, $args{billingdatefrom
};
2593 if($args{billingdateto
}) {
2594 push @bind_strs, " aqinvoices.billingdate <= ? ";
2595 push @bind_args, $args{billingdateto
};
2597 if($args{isbneanissn
}) {
2598 push @bind_strs, " (biblioitems.isbn LIKE CONCAT('%', ?, '%') OR biblioitems.ean LIKE CONCAT('%', ?, '%') OR biblioitems.issn LIKE CONCAT('%', ?, '%') ) ";
2599 push @bind_args, $args{isbneanissn
}, $args{isbneanissn
}, $args{isbneanissn
};
2602 push @bind_strs, " biblio.title LIKE CONCAT('%', ?, '%') ";
2603 push @bind_args, $args{title
};
2606 push @bind_strs, " biblio.author LIKE CONCAT('%', ?, '%') ";
2607 push @bind_args, $args{author
};
2609 if($args{publisher
}) {
2610 push @bind_strs, " biblioitems.publishercode LIKE CONCAT('%', ?, '%') ";
2611 push @bind_args, $args{publisher
};
2613 if($args{publicationyear
}) {
2614 push @bind_strs, " ((biblioitems.publicationyear LIKE CONCAT('%', ?, '%')) OR (biblio.copyrightdate LIKE CONCAT('%', ?, '%'))) ";
2615 push @bind_args, $args{publicationyear
}, $args{publicationyear
};
2617 if($args{branchcode
}) {
2618 push @bind_strs, " borrowers.branchcode = ? ";
2619 push @bind_args, $args{branchcode
};
2621 if($args{message_id
}) {
2622 push @bind_strs, " aqinvoices.message_id = ? ";
2623 push @bind_args, $args{message_id
};
2626 $query .= " WHERE " . join(" AND ", @bind_strs) if @bind_strs;
2627 $query .= " GROUP BY aqinvoices.invoiceid, aqinvoices.invoicenumber, aqinvoices.booksellerid, aqinvoices.shipmentdate, aqinvoices.billingdate, aqinvoices.closedate, aqinvoices.shipmentcost, aqinvoices.shipmentcost_budgetid, aqinvoices.message_id, aqbooksellers.name";
2629 if($args{order_by
}) {
2630 my ($column, $direction) = split / /, $args{order_by
};
2631 if(grep /^$column$/, @columns) {
2632 $direction ||= 'ASC';
2633 $query .= " ORDER BY $column $direction";
2637 my $sth = $dbh->prepare($query);
2638 $sth->execute(@bind_args);
2640 my $results = $sth->fetchall_arrayref({});
2646 my $invoice = GetInvoice($invoiceid);
2648 Get informations about invoice with given $invoiceid
2650 Return a hash filled with aqinvoices.* fields
2655 my ($invoiceid) = @_;
2658 return unless $invoiceid;
2660 my $dbh = C4
::Context
->dbh;
2666 my $sth = $dbh->prepare($query);
2667 $sth->execute($invoiceid);
2669 $invoice = $sth->fetchrow_hashref;
2673 =head3 GetInvoiceDetails
2675 my $invoice = GetInvoiceDetails($invoiceid)
2677 Return informations about an invoice + the list of related order lines
2679 Orders informations are in $invoice->{orders} (array ref)
2683 sub GetInvoiceDetails
{
2684 my ($invoiceid) = @_;
2686 if ( !defined $invoiceid ) {
2687 carp
'GetInvoiceDetails called without an invoiceid';
2691 my $dbh = C4
::Context
->dbh;
2693 SELECT aqinvoices.*, aqbooksellers.name AS suppliername
2695 LEFT JOIN aqbooksellers ON aqinvoices.booksellerid = aqbooksellers.id
2698 my $sth = $dbh->prepare($query);
2699 $sth->execute($invoiceid);
2701 my $invoice = $sth->fetchrow_hashref;
2706 biblio.copyrightdate,
2708 biblioitems.publishercode,
2709 biblioitems.publicationyear,
2710 aqbasket.basketname,
2711 aqbasketgroups.id AS basketgroupid,
2712 aqbasketgroups.name AS basketgroupname
2714 LEFT JOIN aqbasket ON aqorders.basketno = aqbasket.basketno
2715 LEFT JOIN aqbasketgroups ON aqbasket.basketgroupid = aqbasketgroups.id
2716 LEFT JOIN biblio ON aqorders.biblionumber = biblio.biblionumber
2717 LEFT JOIN biblioitems ON aqorders.biblionumber = biblioitems.biblionumber
2720 $sth = $dbh->prepare($query);
2721 $sth->execute($invoiceid);
2722 $invoice->{orders
} = $sth->fetchall_arrayref({});
2723 $invoice->{orders
} ||= []; # force an empty arrayref if fetchall_arrayref fails
2730 my $invoiceid = AddInvoice(
2731 invoicenumber => $invoicenumber,
2732 booksellerid => $booksellerid,
2733 shipmentdate => $shipmentdate,
2734 billingdate => $billingdate,
2735 closedate => $closedate,
2736 shipmentcost => $shipmentcost,
2737 shipmentcost_budgetid => $shipmentcost_budgetid
2740 Create a new invoice and return its id or undef if it fails.
2747 return unless(%invoice and $invoice{invoicenumber
});
2749 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2750 closedate shipmentcost shipmentcost_budgetid message_id);
2754 foreach my $key (keys %invoice) {
2755 if(0 < grep(/^$key$/, @columns)) {
2756 push @set_strs, "$key = ?";
2757 push @set_args, ($invoice{$key} || undef);
2763 my $dbh = C4
::Context
->dbh;
2764 my $query = "INSERT INTO aqinvoices SET ";
2765 $query .= join (",", @set_strs);
2766 my $sth = $dbh->prepare($query);
2767 $rv = $sth->execute(@set_args);
2769 $rv = $dbh->last_insert_id(undef, undef, 'aqinvoices', undef);
2778 invoiceid => $invoiceid, # Mandatory
2779 invoicenumber => $invoicenumber,
2780 booksellerid => $booksellerid,
2781 shipmentdate => $shipmentdate,
2782 billingdate => $billingdate,
2783 closedate => $closedate,
2784 shipmentcost => $shipmentcost,
2785 shipmentcost_budgetid => $shipmentcost_budgetid
2788 Modify an invoice, invoiceid is mandatory.
2790 Return undef if it fails.
2797 return unless(%invoice and $invoice{invoiceid
});
2799 my @columns = qw(invoicenumber booksellerid shipmentdate billingdate
2800 closedate shipmentcost shipmentcost_budgetid);
2804 foreach my $key (keys %invoice) {
2805 if(0 < grep(/^$key$/, @columns)) {
2806 push @set_strs, "$key = ?";
2807 push @set_args, ($invoice{$key} || undef);
2811 my $dbh = C4
::Context
->dbh;
2812 my $query = "UPDATE aqinvoices SET ";
2813 $query .= join(",", @set_strs);
2814 $query .= " WHERE invoiceid = ?";
2816 my $sth = $dbh->prepare($query);
2817 $sth->execute(@set_args, $invoice{invoiceid
});
2822 CloseInvoice($invoiceid);
2826 Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => undef);
2831 my ($invoiceid) = @_;
2833 return unless $invoiceid;
2835 my $dbh = C4
::Context
->dbh;
2838 SET closedate
= CAST
(NOW
() AS DATE
)
2841 my $sth = $dbh->prepare($query);
2842 $sth->execute($invoiceid);
2845 =head3 ReopenInvoice
2847 ReopenInvoice($invoiceid);
2851 Equivalent to ModInvoice(invoiceid => $invoiceid, closedate => output_pref({ dt=>dt_from_string, dateonly=>1, otputpref=>'iso' }))
2856 my ($invoiceid) = @_;
2858 return unless $invoiceid;
2860 my $dbh = C4
::Context
->dbh;
2863 SET closedate
= NULL
2866 my $sth = $dbh->prepare($query);
2867 $sth->execute($invoiceid);
2872 DelInvoice($invoiceid);
2874 Delete an invoice if there are no items attached to it.
2879 my ($invoiceid) = @_;
2881 return unless $invoiceid;
2883 my $dbh = C4
::Context
->dbh;
2889 my $sth = $dbh->prepare($query);
2890 $sth->execute($invoiceid);
2891 my $res = $sth->fetchrow_arrayref;
2892 if ( $res && $res->[0] == 0 ) {
2894 DELETE FROM aqinvoices
2897 my $sth = $dbh->prepare($query);
2898 return ( $sth->execute($invoiceid) > 0 );
2903 =head3 MergeInvoices
2905 MergeInvoices($invoiceid, \@sourceids);
2907 Merge the invoices identified by the IDs in \@sourceids into
2908 the invoice identified by $invoiceid.
2913 my ($invoiceid, $sourceids) = @_;
2915 return unless $invoiceid;
2916 foreach my $sourceid (@
$sourceids) {
2917 next if $sourceid == $invoiceid;
2918 my $source = GetInvoiceDetails
($sourceid);
2919 foreach my $order (@
{$source->{'orders'}}) {
2920 $order->{'invoiceid'} = $invoiceid;
2923 DelInvoice
($source->{'invoiceid'});
2928 =head3 GetBiblioCountByBasketno
2930 $biblio_count = &GetBiblioCountByBasketno($basketno);
2932 Looks up the biblio's count that has basketno value $basketno
2938 sub GetBiblioCountByBasketno
{
2939 my ($basketno) = @_;
2940 my $dbh = C4
::Context
->dbh;
2942 SELECT COUNT( DISTINCT( biblionumber ) )
2945 AND (datecancellationprinted IS NULL OR datecancellationprinted='0000-00-00')
2948 my $sth = $dbh->prepare($query);
2949 $sth->execute($basketno);
2950 return $sth->fetchrow;
2953 # Note this subroutine should be moved to Koha::Acquisition::Order
2954 # Will do when a DBIC decision will be taken.
2955 sub populate_order_with_prices
{
2958 my $order = $params->{order
};
2959 my $booksellerid = $params->{booksellerid
};
2960 return unless $booksellerid;
2962 my $bookseller = Koha
::Acquisition
::Booksellers
->find( $booksellerid );
2964 my $receiving = $params->{receiving
};
2965 my $ordering = $params->{ordering
};
2966 my $discount = $order->{discount
};
2967 $discount /= 100 if $discount > 1;
2970 $order->{tax_rate_on_ordering
} //= $order->{tax_rate
};
2971 if ( $bookseller->listincgst ) {
2972 # The user entered the rrp tax included
2973 $order->{rrp_tax_included
} = $order->{rrp
};
2975 # rrp tax excluded = rrp tax included / ( 1 + tax rate )
2976 $order->{rrp_tax_excluded
} = $order->{rrp_tax_included
} / ( 1 + $order->{tax_rate_on_ordering
} );
2978 # ecost tax excluded = rrp tax excluded * ( 1 - discount )
2979 $order->{ecost_tax_excluded
} = $order->{rrp_tax_excluded
} * ( 1 - $discount );
2981 # ecost tax included = rrp tax included ( 1 - discount )
2982 $order->{ecost_tax_included
} = $order->{rrp_tax_included
} * ( 1 - $discount );
2985 # The user entered the rrp tax excluded
2986 $order->{rrp_tax_excluded
} = $order->{rrp
};
2988 # rrp tax included = rrp tax excluded * ( 1 - tax rate )
2989 $order->{rrp_tax_included
} = $order->{rrp_tax_excluded
} * ( 1 + $order->{tax_rate_on_ordering
} );
2991 # ecost tax excluded = rrp tax excluded * ( 1 - discount )
2992 $order->{ecost_tax_excluded
} = $order->{rrp_tax_excluded
} * ( 1 - $discount );
2994 # ecost tax included = rrp tax excluded * ( 1 + tax rate ) * ( 1 - discount )
2995 $order->{ecost_tax_included
} =
2996 $order->{rrp_tax_excluded
} *
2997 ( 1 + $order->{tax_rate_on_ordering
} ) *
3001 # tax value = quantity * ecost tax excluded * tax rate
3002 $order->{tax_value_on_ordering
} =
3003 $order->{quantity
} * $order->{ecost_tax_excluded
} * $order->{tax_rate_on_ordering
};
3007 $order->{tax_rate_on_receiving
} //= $order->{tax_rate
};
3008 if ( $bookseller->invoiceincgst ) {
3009 # Trick for unitprice. If the unit price rounded value is the same as the ecost rounded value
3010 # we need to keep the exact ecost value
3011 if ( Koha
::Number
::Price
->new( $order->{unitprice
} )->round == Koha
::Number
::Price
->new( $order->{ecost_tax_included
} )->round ) {
3012 $order->{unitprice
} = $order->{ecost_tax_included
};
3015 # The user entered the unit price tax included
3016 $order->{unitprice_tax_included
} = $order->{unitprice
};
3018 # unit price tax excluded = unit price tax included / ( 1 + tax rate )
3019 $order->{unitprice_tax_excluded
} = $order->{unitprice_tax_included
} / ( 1 + $order->{tax_rate_on_receiving
} );
3022 # Trick for unitprice. If the unit price rounded value is the same as the ecost rounded value
3023 # we need to keep the exact ecost value
3024 if ( Koha
::Number
::Price
->new( $order->{unitprice
} )->round == Koha
::Number
::Price
->new( $order->{ecost_tax_excluded
} )->round ) {
3025 $order->{unitprice
} = $order->{ecost_tax_excluded
};
3028 # The user entered the unit price tax excluded
3029 $order->{unitprice_tax_excluded
} = $order->{unitprice
};
3032 # unit price tax included = unit price tax included * ( 1 + tax rate )
3033 $order->{unitprice_tax_included
} = $order->{unitprice_tax_excluded
} * ( 1 + $order->{tax_rate_on_receiving
} );
3036 # tax value = quantity * unit price tax excluded * tax rate
3037 $order->{tax_value_on_receiving
} = $order->{quantity
} * $order->{unitprice_tax_excluded
} * $order->{tax_rate_on_receiving
};
3043 =head3 GetOrderUsers
3045 $order_users_ids = &GetOrderUsers($ordernumber);
3047 Returns a list of all borrowernumbers that are in order users list
3052 my ($ordernumber) = @_;
3054 return unless $ordernumber;
3057 SELECT borrowernumber
3059 WHERE ordernumber
= ?
3061 my $dbh = C4
::Context
->dbh;
3062 my $sth = $dbh->prepare($query);
3063 $sth->execute($ordernumber);
3064 my $results = $sth->fetchall_arrayref( {} );
3066 my @borrowernumbers;
3067 foreach (@
$results) {
3068 push @borrowernumbers, $_->{'borrowernumber'};
3071 return @borrowernumbers;
3074 =head3 ModOrderUsers
3076 my @order_users_ids = (1, 2, 3);
3077 &ModOrderUsers($ordernumber, @basketusers_ids);
3079 Delete all users from order users list, and add users in C<@order_users_ids>
3085 my ( $ordernumber, @order_users_ids ) = @_;
3087 return unless $ordernumber;
3089 my $dbh = C4
::Context
->dbh;
3091 DELETE FROM aqorder_users
3092 WHERE ordernumber
= ?
3094 my $sth = $dbh->prepare($query);
3095 $sth->execute($ordernumber);
3098 INSERT INTO aqorder_users
(ordernumber
, borrowernumber
)
3101 $sth = $dbh->prepare($query);
3102 foreach my $order_user_id (@order_users_ids) {
3103 $sth->execute( $ordernumber, $order_user_id );
3107 sub NotifyOrderUsers
{
3108 my ($ordernumber) = @_;
3110 my @borrowernumbers = GetOrderUsers
($ordernumber);
3111 return unless @borrowernumbers;
3113 my $order = GetOrder
( $ordernumber );
3114 for my $borrowernumber (@borrowernumbers) {
3115 my $patron = Koha
::Patrons
->find( $borrowernumber );
3116 my $library = $patron->library->unblessed;
3117 my $biblio = Koha
::Biblios
->find( $order->{biblionumber
} )->unblessed;
3118 my $letter = C4
::Letters
::GetPreparedLetter
(
3119 module
=> 'acquisition',
3120 letter_code
=> 'ACQ_NOTIF_ON_RECEIV',
3121 branchcode
=> $library->{branchcode
},
3122 lang
=> $patron->lang,
3124 'branches' => $library,
3125 'borrowers' => $patron->unblessed,
3126 'biblio' => $biblio,
3127 'aqorders' => $order,
3131 C4
::Letters
::EnqueueLetter
(
3134 borrowernumber
=> $borrowernumber,
3135 LibraryName
=> C4
::Context
->preference("LibraryName"),
3136 message_transport_type
=> 'email',
3138 ) or warn "can't enqueue letter $letter";
3143 =head3 FillWithDefaultValues
3145 FillWithDefaultValues( $marc_record );
3147 This will update the record with default value defined in the ACQ framework.
3148 For all existing fields, if a default value exists and there are no subfield, it will be created.
3149 If the field does not exist, it will be created too.
3153 sub FillWithDefaultValues
{
3155 my $tagslib = C4
::Biblio
::GetMarcStructure
( 1, 'ACQ', { unsafe
=> 1 } );
3158 C4
::Biblio
::GetMarcFromKohaField
( 'items.itemnumber', '' );
3159 for my $tag ( sort keys %$tagslib ) {
3161 next if $tag == $itemfield;
3162 for my $subfield ( sort keys %{ $tagslib->{$tag} } ) {
3163 next if IsMarcStructureInternal
($tagslib->{$tag}{$subfield});
3164 my $defaultvalue = $tagslib->{$tag}{$subfield}{defaultvalue
};
3165 if ( defined $defaultvalue and $defaultvalue ne '' ) {
3166 my @fields = $record->field($tag);
3168 for my $field (@fields) {
3169 unless ( defined $field->subfield($subfield) ) {
3170 $field->add_subfields(
3171 $subfield => $defaultvalue );
3176 $record->insert_fields_ordered(
3178 $tag, '', '', $subfield => $defaultvalue
3193 Koha Development Team <http://koha-community.org/>