Bug 17585: Replace ->get_account_lines with ->account
[koha.git] / C4 / Reserves.pm
blob9ef33ad8baa12aeae619a43a2a2581ea9deae9a0
1 package C4::Reserves;
3 # Copyright 2000-2002 Katipo Communications
4 # 2006 SAN Ouest Provence
5 # 2007-2010 BibLibre Paul POULAIN
6 # 2011 Catalyst IT
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
24 use strict;
25 #use warnings; FIXME - Bug 2505
26 use C4::Context;
27 use C4::Biblio;
28 use C4::Members;
29 use C4::Items;
30 use C4::Circulation;
31 use C4::Accounts;
33 # for _koha_notify_reserve
34 use C4::Members::Messaging;
35 use C4::Members qw();
36 use C4::Letters;
37 use C4::Log;
39 use Koha::DateUtils;
40 use Koha::Calendar;
41 use Koha::Database;
42 use Koha::Hold;
43 use Koha::Old::Hold;
44 use Koha::Holds;
45 use Koha::Libraries;
46 use Koha::IssuingRules;
47 use Koha::Items;
48 use Koha::ItemTypes;
49 use Koha::Patrons;
51 use List::MoreUtils qw( firstidx any );
52 use Carp;
53 use Data::Dumper;
55 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
57 =head1 NAME
59 C4::Reserves - Koha functions for dealing with reservation.
61 =head1 SYNOPSIS
63 use C4::Reserves;
65 =head1 DESCRIPTION
67 This modules provides somes functions to deal with reservations.
69 Reserves are stored in reserves table.
70 The following columns contains important values :
71 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
72 =0 : then the reserve is being dealed
73 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
74 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
75 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
76 F(inished) : the reserve has been completed, and is done
77 - itemnumber : empty : the reserve is still unaffected to an item
78 filled: the reserve is attached to an item
79 The complete workflow is :
80 ==== 1st use case ====
81 patron request a document, 1st available : P >0, F=NULL, I=NULL
82 a library having it run "transfertodo", and clic on the list
83 if there is no transfer to do, the reserve waiting
84 patron can pick it up P =0, F=W, I=filled
85 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
86 The pickup library receive the book, it check in P =0, F=W, I=filled
87 The patron borrow the book P =0, F=F, I=filled
89 ==== 2nd use case ====
90 patron requests a document, a given item,
91 If pickup is holding branch P =0, F=W, I=filled
92 If transfer needed, write in branchtransfer P =0, F=T, I=filled
93 The pickup library receive the book, it checks it in P =0, F=W, I=filled
94 The patron borrow the book P =0, F=F, I=filled
96 =head1 FUNCTIONS
98 =cut
100 BEGIN {
101 require Exporter;
102 @ISA = qw(Exporter);
103 @EXPORT = qw(
104 &AddReserve
106 &GetReserve
107 &GetReservesFromItemnumber
108 &GetReservesFromBiblionumber
109 &GetReservesFromBorrowernumber
110 &GetReservesForBranch
111 &GetReservesToBranch
112 &GetReserveCount
113 &GetReserveInfo
114 &GetReserveStatus
116 &GetOtherReserves
118 &ModReserveFill
119 &ModReserveAffect
120 &ModReserve
121 &ModReserveStatus
122 &ModReserveCancelAll
123 &ModReserveMinusPriority
124 &MoveReserve
126 &CheckReserves
127 &CanBookBeReserved
128 &CanItemBeReserved
129 &CanReserveBeCanceledFromOpac
130 &CancelReserve
131 &CancelExpiredReserves
133 &AutoUnsuspendReserves
135 &IsAvailableForItemLevelRequest
137 &OPACItemHoldsAllowed
139 &AlterPriority
140 &ToggleLowestPriority
142 &ReserveSlip
143 &ToggleSuspend
144 &SuspendAll
146 &GetReservesControlBranch
148 IsItemOnHoldAndFound
150 GetMaxPatronHoldsForRecord
152 @EXPORT_OK = qw( MergeHolds );
155 =head2 AddReserve
157 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
159 Adds reserve and generates HOLDPLACED message.
161 The following tables are available witin the HOLDPLACED message:
163 branches
164 borrowers
165 biblio
166 biblioitems
167 items
169 =cut
171 sub AddReserve {
172 my (
173 $branch, $borrowernumber, $biblionumber, $bibitems,
174 $priority, $resdate, $expdate, $notes,
175 $title, $checkitem, $found, $itemtype
176 ) = @_;
178 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
179 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
181 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
183 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
185 # Make room in reserves for this before those of a later reserve date
186 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
189 my $waitingdate;
191 # If the reserv had the waiting status, we had the value of the resdate
192 if ( $found eq 'W' ) {
193 $waitingdate = $resdate;
196 # Don't add itemtype limit if specific item is selected
197 $itemtype = undef if $checkitem;
199 # updates take place here
200 my $hold = Koha::Hold->new(
202 borrowernumber => $borrowernumber,
203 biblionumber => $biblionumber,
204 reservedate => $resdate,
205 branchcode => $branch,
206 priority => $priority,
207 reservenotes => $notes,
208 itemnumber => $checkitem,
209 found => $found,
210 waitingdate => $waitingdate,
211 expirationdate => $expdate,
212 itemtype => $itemtype,
214 )->store();
216 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
217 if C4::Context->preference('HoldsLog');
219 my $reserve_id = $hold->id();
221 # add a reserve fee if needed
222 my $fee = GetReserveFee( $borrowernumber, $biblionumber );
223 ChargeReserveFee( $borrowernumber, $fee, $title );
225 _FixPriority({ biblionumber => $biblionumber});
227 # Send e-mail to librarian if syspref is active
228 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
229 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
230 my $library = Koha::Libraries->find($borrower->{branchcode})->unblessed;
231 if ( my $letter = C4::Letters::GetPreparedLetter (
232 module => 'reserves',
233 letter_code => 'HOLDPLACED',
234 branchcode => $branch,
235 tables => {
236 'branches' => $library,
237 'borrowers' => $borrower,
238 'biblio' => $biblionumber,
239 'biblioitems' => $biblionumber,
240 'items' => $checkitem,
242 ) ) {
244 my $admin_email_address = $library->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
246 C4::Letters::EnqueueLetter(
247 { letter => $letter,
248 borrowernumber => $borrowernumber,
249 message_transport_type => 'email',
250 from_address => $admin_email_address,
251 to_address => $admin_email_address,
257 return $reserve_id;
260 =head2 GetReserve
262 $res = GetReserve( $reserve_id );
264 Return the current reserve.
266 =cut
268 sub GetReserve {
269 my ($reserve_id) = @_;
271 my $dbh = C4::Context->dbh;
273 my $query = "SELECT * FROM reserves WHERE reserve_id = ?";
274 my $sth = $dbh->prepare( $query );
275 $sth->execute( $reserve_id );
276 return $sth->fetchrow_hashref();
279 =head2 GetReservesFromBiblionumber
281 my $reserves = GetReservesFromBiblionumber({
282 biblionumber => $biblionumber,
283 [ itemnumber => $itemnumber, ]
284 [ all_dates => 1|0 ]
287 This function gets the list of reservations for one C<$biblionumber>,
288 returning an arrayref pointing to the reserves for C<$biblionumber>.
290 By default, only reserves whose start date falls before the current
291 time are returned. To return all reserves, including future ones,
292 the C<all_dates> parameter can be included and set to a true value.
294 If the C<itemnumber> parameter is supplied, reserves must be targeted
295 to that item or not targeted to any item at all; otherwise, they
296 are excluded from the list.
298 =cut
300 sub GetReservesFromBiblionumber {
301 my ( $params ) = @_;
302 my $biblionumber = $params->{biblionumber} or return [];
303 my $itemnumber = $params->{itemnumber};
304 my $all_dates = $params->{all_dates} // 0;
305 my $dbh = C4::Context->dbh;
307 # Find the desired items in the reserves
308 my @params;
309 my $query = "
310 SELECT reserve_id,
311 branchcode,
312 timestamp AS rtimestamp,
313 priority,
314 biblionumber,
315 borrowernumber,
316 reservedate,
317 found,
318 itemnumber,
319 reservenotes,
320 expirationdate,
321 lowestPriority,
322 suspend,
323 suspend_until,
324 itemtype
325 FROM reserves
326 WHERE biblionumber = ? ";
327 push( @params, $biblionumber );
328 unless ( $all_dates ) {
329 $query .= " AND reservedate <= CAST(NOW() AS DATE) ";
331 if ( $itemnumber ) {
332 $query .= " AND ( itemnumber IS NULL OR itemnumber = ? )";
333 push( @params, $itemnumber );
335 $query .= "ORDER BY priority";
336 my $sth = $dbh->prepare($query);
337 $sth->execute( @params );
338 my @results;
339 while ( my $data = $sth->fetchrow_hashref ) {
340 push @results, $data;
342 return \@results;
345 =head2 GetReservesFromItemnumber
347 ( $reservedate, $borrowernumber, $branchcode, $reserve_id, $waitingdate ) = GetReservesFromItemnumber($itemnumber);
349 Get the first reserve for a specific item number (based on priority). Returns the abovementioned values for that reserve.
351 The routine does not look at future reserves (read: item level holds), but DOES include future waits (a confirmed future hold).
353 =cut
355 sub GetReservesFromItemnumber {
356 my ($itemnumber) = @_;
358 my $schema = Koha::Database->new()->schema();
360 my $r = $schema->resultset('Reserve')->search(
362 itemnumber => $itemnumber,
363 suspend => 0,
364 -or => [
365 reservedate => \'<= CAST( NOW() AS DATE )',
366 waitingdate => { '!=', undef }
370 order_by => 'priority',
372 )->first();
374 return unless $r;
376 return (
377 $r->reservedate(),
378 $r->get_column('borrowernumber'),
379 $r->get_column('branchcode'),
380 $r->reserve_id(),
381 $r->waitingdate(),
385 =head2 GetReservesFromBorrowernumber
387 $borrowerreserv = GetReservesFromBorrowernumber($borrowernumber,$tatus);
389 TODO :: Descritpion
391 =cut
393 sub GetReservesFromBorrowernumber {
394 my ( $borrowernumber, $status ) = @_;
395 my $dbh = C4::Context->dbh;
396 my $sth;
397 if ($status) {
398 $sth = $dbh->prepare("
399 SELECT *
400 FROM reserves
401 WHERE borrowernumber=?
402 AND found =?
403 ORDER BY reservedate
405 $sth->execute($borrowernumber,$status);
406 } else {
407 $sth = $dbh->prepare("
408 SELECT *
409 FROM reserves
410 WHERE borrowernumber=?
411 ORDER BY reservedate
413 $sth->execute($borrowernumber);
415 my $data = $sth->fetchall_arrayref({});
416 return @$data;
419 =head2 CanBookBeReserved
421 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
422 if ($canReserve eq 'OK') { #We can reserve this Item! }
424 See CanItemBeReserved() for possible return values.
426 =cut
428 sub CanBookBeReserved{
429 my ($borrowernumber, $biblionumber) = @_;
431 my $items = GetItemnumbersForBiblio($biblionumber);
432 #get items linked via host records
433 my @hostitems = get_hostitemnumbers_of($biblionumber);
434 if (@hostitems){
435 push (@$items,@hostitems);
438 my $canReserve;
439 foreach my $item (@$items) {
440 $canReserve = CanItemBeReserved( $borrowernumber, $item );
441 return 'OK' if $canReserve eq 'OK';
443 return $canReserve;
446 =head2 CanItemBeReserved
448 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
449 if ($canReserve eq 'OK') { #We can reserve this Item! }
451 @RETURNS OK, if the Item can be reserved.
452 ageRestricted, if the Item is age restricted for this borrower.
453 damaged, if the Item is damaged.
454 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
455 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
456 notReservable, if holds on this item are not allowed
458 =cut
460 sub CanItemBeReserved {
461 my ( $borrowernumber, $itemnumber ) = @_;
463 my $dbh = C4::Context->dbh;
464 my $ruleitemtype; # itemtype of the matching issuing rule
465 my $allowedreserves = 0; # Total number of holds allowed across all records
466 my $holds_per_record = 1; # Total number of holds allowed for this one given record
468 # we retrieve borrowers and items informations #
469 # item->{itype} will come for biblioitems if necessery
470 my $item = GetItem($itemnumber);
471 my $biblioData = C4::Biblio::GetBiblioData( $item->{biblionumber} );
472 my $borrower = C4::Members::GetMember( 'borrowernumber' => $borrowernumber );
474 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
475 return 'damaged'
476 if ( $item->{damaged}
477 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
479 # Check for the age restriction
480 my ( $ageRestriction, $daysToAgeRestriction ) =
481 C4::Circulation::GetAgeRestriction( $biblioData->{agerestriction}, $borrower );
482 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
484 # Check that the patron doesn't have an item level hold on this item already
485 return 'itemAlreadyOnHold'
486 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
488 my $controlbranch = C4::Context->preference('ReservesControlBranch');
490 my $querycount = q{
491 SELECT count(*) AS count
492 FROM reserves
493 LEFT JOIN items USING (itemnumber)
494 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
495 LEFT JOIN borrowers USING (borrowernumber)
496 WHERE borrowernumber = ?
499 my $branchcode = "";
500 my $branchfield = "reserves.branchcode";
502 if ( $controlbranch eq "ItemHomeLibrary" ) {
503 $branchfield = "items.homebranch";
504 $branchcode = $item->{homebranch};
506 elsif ( $controlbranch eq "PatronLibrary" ) {
507 $branchfield = "borrowers.branchcode";
508 $branchcode = $borrower->{branchcode};
511 # we retrieve rights
512 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
513 $ruleitemtype = $rights->{itemtype};
514 $allowedreserves = $rights->{reservesallowed};
515 $holds_per_record = $rights->{holds_per_record};
517 else {
518 $ruleitemtype = '*';
521 $item = Koha::Items->find( $itemnumber );
522 my $holds = Koha::Holds->search(
524 borrowernumber => $borrowernumber,
525 biblionumber => $item->biblionumber,
526 found => undef, # Found holds don't count against a patron's holds limit
529 if ( $holds->count() >= $holds_per_record ) {
530 return "tooManyHoldsForThisRecord";
533 # we retrieve count
535 $querycount .= "AND $branchfield = ?";
537 # If using item-level itypes, fall back to the record
538 # level itemtype if the hold has no associated item
539 $querycount .=
540 C4::Context->preference('item-level_itypes')
541 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
542 : " AND biblioitems.itemtype = ?"
543 if ( $ruleitemtype ne "*" );
545 my $sthcount = $dbh->prepare($querycount);
547 if ( $ruleitemtype eq "*" ) {
548 $sthcount->execute( $borrowernumber, $branchcode );
550 else {
551 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
554 my $reservecount = "0";
555 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
556 $reservecount = $rowcount->{count};
559 # we check if it's ok or not
560 if ( $reservecount >= $allowedreserves ) {
561 return 'tooManyReserves';
564 my $circ_control_branch =
565 C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
566 my $branchitemrule =
567 C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype );
569 if ( $branchitemrule->{holdallowed} == 0 ) {
570 return 'notReservable';
573 if ( $branchitemrule->{holdallowed} == 1
574 && $borrower->{branchcode} ne $item->homebranch )
576 return 'cannotReserveFromOtherBranches';
579 # If reservecount is ok, we check item branch if IndependentBranches is ON
580 # and canreservefromotherbranches is OFF
581 if ( C4::Context->preference('IndependentBranches')
582 and !C4::Context->preference('canreservefromotherbranches') )
584 my $itembranch = $item->{homebranch};
585 if ( $itembranch ne $borrower->{branchcode} ) {
586 return 'cannotReserveFromOtherBranches';
590 return 'OK';
593 =head2 CanReserveBeCanceledFromOpac
595 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
597 returns 1 if reserve can be cancelled by user from OPAC.
598 First check if reserve belongs to user, next checks if reserve is not in
599 transfer or waiting status
601 =cut
603 sub CanReserveBeCanceledFromOpac {
604 my ($reserve_id, $borrowernumber) = @_;
606 return unless $reserve_id and $borrowernumber;
607 my $reserve = GetReserve($reserve_id);
609 return 0 unless $reserve->{borrowernumber} == $borrowernumber;
610 return 0 if ( $reserve->{found} eq 'W' ) or ( $reserve->{found} eq 'T' );
612 return 1;
616 =head2 GetReserveCount
618 $number = &GetReserveCount($borrowernumber);
620 this function returns the number of reservation for a borrower given on input arg.
622 =cut
624 sub GetReserveCount {
625 my ($borrowernumber) = @_;
627 my $dbh = C4::Context->dbh;
629 my $query = "
630 SELECT COUNT(*) AS counter
631 FROM reserves
632 WHERE borrowernumber = ?
634 my $sth = $dbh->prepare($query);
635 $sth->execute($borrowernumber);
636 my $row = $sth->fetchrow_hashref;
637 return $row->{counter};
640 =head2 GetOtherReserves
642 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
644 Check queued list of this document and check if this document must be transferred
646 =cut
648 sub GetOtherReserves {
649 my ($itemnumber) = @_;
650 my $messages;
651 my $nextreservinfo;
652 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
653 if ($checkreserves) {
654 my $iteminfo = GetItem($itemnumber);
655 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
656 $messages->{'transfert'} = $checkreserves->{'branchcode'};
657 #minus priorities of others reservs
658 ModReserveMinusPriority(
659 $itemnumber,
660 $checkreserves->{'reserve_id'},
663 #launch the subroutine dotransfer
664 C4::Items::ModItemTransfer(
665 $itemnumber,
666 $iteminfo->{'holdingbranch'},
667 $checkreserves->{'branchcode'}
672 #step 2b : case of a reservation on the same branch, set the waiting status
673 else {
674 $messages->{'waiting'} = 1;
675 ModReserveMinusPriority(
676 $itemnumber,
677 $checkreserves->{'reserve_id'},
679 ModReserveStatus($itemnumber,'W');
682 $nextreservinfo = $checkreserves->{'borrowernumber'};
685 return ( $messages, $nextreservinfo );
688 =head2 ChargeReserveFee
690 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
692 Charge the fee for a reserve (if $fee > 0)
694 =cut
696 sub ChargeReserveFee {
697 my ( $borrowernumber, $fee, $title ) = @_;
698 return if !$fee || $fee==0; # the last test is needed to include 0.00
699 my $accquery = qq{
700 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
702 my $dbh = C4::Context->dbh;
703 my $nextacctno = &getnextacctno( $borrowernumber );
704 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
707 =head2 GetReserveFee
709 $fee = GetReserveFee( $borrowernumber, $biblionumber );
711 Calculate the fee for a reserve (if applicable).
713 =cut
715 sub GetReserveFee {
716 my ( $borrowernumber, $biblionumber ) = @_;
717 my $borquery = qq{
718 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
720 my $issue_qry = qq{
721 SELECT COUNT(*) FROM items
722 LEFT JOIN issues USING (itemnumber)
723 WHERE items.biblionumber=? AND issues.issue_id IS NULL
725 my $holds_qry = qq{
726 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
729 my $dbh = C4::Context->dbh;
730 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
731 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
732 if( $fee and $fee > 0 and $hold_fee_mode ne 'always' ) {
733 # This is a reconstruction of the old code:
734 # Compare number of items with items issued, and optionally check holds
735 # If not all items are issued and there are no holds: charge no fee
736 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
737 my ( $notissued, $reserved );
738 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
739 ( $biblionumber ) );
740 if( $notissued ) {
741 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
742 ( $biblionumber, $borrowernumber ) );
743 $fee = 0 if $reserved == 0;
746 return $fee;
749 =head2 GetReservesToBranch
751 @transreserv = GetReservesToBranch( $frombranch );
753 Get reserve list for a given branch
755 =cut
757 sub GetReservesToBranch {
758 my ( $frombranch ) = @_;
759 my $dbh = C4::Context->dbh;
760 my $sth = $dbh->prepare(
761 "SELECT reserve_id,borrowernumber,reservedate,itemnumber,timestamp
762 FROM reserves
763 WHERE priority='0'
764 AND branchcode=?"
766 $sth->execute( $frombranch );
767 my @transreserv;
768 my $i = 0;
769 while ( my $data = $sth->fetchrow_hashref ) {
770 $transreserv[$i] = $data;
771 $i++;
773 return (@transreserv);
776 =head2 GetReservesForBranch
778 @transreserv = GetReservesForBranch($frombranch);
780 =cut
782 sub GetReservesForBranch {
783 my ($frombranch) = @_;
784 my $dbh = C4::Context->dbh;
786 my $query = "
787 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate
788 FROM reserves
789 WHERE priority='0'
790 AND found='W'
792 $query .= " AND branchcode=? " if ( $frombranch );
793 $query .= "ORDER BY waitingdate" ;
795 my $sth = $dbh->prepare($query);
796 if ($frombranch){
797 $sth->execute($frombranch);
798 } else {
799 $sth->execute();
802 my @transreserv;
803 my $i = 0;
804 while ( my $data = $sth->fetchrow_hashref ) {
805 $transreserv[$i] = $data;
806 $i++;
808 return (@transreserv);
811 =head2 GetReserveStatus
813 $reservestatus = GetReserveStatus($itemnumber);
815 Takes an itemnumber and returns the status of the reserve placed on it.
816 If several reserves exist, the reserve with the lower priority is given.
818 =cut
820 ## FIXME: I don't think this does what it thinks it does.
821 ## It only ever checks the first reserve result, even though
822 ## multiple reserves for that bib can have the itemnumber set
823 ## the sub is only used once in the codebase.
824 sub GetReserveStatus {
825 my ($itemnumber) = @_;
827 my $dbh = C4::Context->dbh;
829 my ($sth, $found, $priority);
830 if ( $itemnumber ) {
831 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
832 $sth->execute($itemnumber);
833 ($found, $priority) = $sth->fetchrow_array;
836 if(defined $found) {
837 return 'Waiting' if $found eq 'W' and $priority == 0;
838 return 'Finished' if $found eq 'F';
841 return 'Reserved' if $priority > 0;
843 return ''; # empty string here will remove need for checking undef, or less log lines
846 =head2 CheckReserves
848 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
849 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
850 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
852 Find a book in the reserves.
854 C<$itemnumber> is the book's item number.
855 C<$lookahead> is the number of days to look in advance for future reserves.
857 As I understand it, C<&CheckReserves> looks for the given item in the
858 reserves. If it is found, that's a match, and C<$status> is set to
859 C<Waiting>.
861 Otherwise, it finds the most important item in the reserves with the
862 same biblio number as this book (I'm not clear on this) and returns it
863 with C<$status> set to C<Reserved>.
865 C<&CheckReserves> returns a two-element list:
867 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
869 C<$reserve> is the reserve item that matched. It is a
870 reference-to-hash whose keys are mostly the fields of the reserves
871 table in the Koha database.
873 =cut
875 sub CheckReserves {
876 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
877 my $dbh = C4::Context->dbh;
878 my $sth;
879 my $select;
880 if (C4::Context->preference('item-level_itypes')){
881 $select = "
882 SELECT items.biblionumber,
883 items.biblioitemnumber,
884 itemtypes.notforloan,
885 items.notforloan AS itemnotforloan,
886 items.itemnumber,
887 items.damaged,
888 items.homebranch,
889 items.holdingbranch
890 FROM items
891 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
892 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
895 else {
896 $select = "
897 SELECT items.biblionumber,
898 items.biblioitemnumber,
899 itemtypes.notforloan,
900 items.notforloan AS itemnotforloan,
901 items.itemnumber,
902 items.damaged,
903 items.homebranch,
904 items.holdingbranch
905 FROM items
906 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
907 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
911 if ($item) {
912 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
913 $sth->execute($item);
915 else {
916 $sth = $dbh->prepare("$select WHERE barcode = ?");
917 $sth->execute($barcode);
919 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
920 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
922 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
924 return unless $itemnumber; # bail if we got nothing.
926 # if item is not for loan it cannot be reserved either.....
927 # except where items.notforloan < 0 : This indicates the item is holdable.
928 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
930 # Find this item in the reserves
931 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
933 # $priority and $highest are used to find the most important item
934 # in the list returned by &_Findgroupreserve. (The lower $priority,
935 # the more important the item.)
936 # $highest is the most important item we've seen so far.
937 my $highest;
938 if (scalar @reserves) {
939 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
940 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
941 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
943 my $priority = 10000000;
944 foreach my $res (@reserves) {
945 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
946 return ( "Waiting", $res, \@reserves ); # Found it
947 } else {
948 my $borrowerinfo;
949 my $iteminfo;
950 my $local_hold_match;
952 if ($LocalHoldsPriority) {
953 $borrowerinfo = C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
954 $iteminfo = C4::Items::GetItem($itemnumber);
956 my $local_holds_priority_item_branchcode =
957 $iteminfo->{$LocalHoldsPriorityItemControl};
958 my $local_holds_priority_patron_branchcode =
959 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
960 ? $res->{branchcode}
961 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
962 ? $borrowerinfo->{branchcode}
963 : undef;
964 $local_hold_match =
965 $local_holds_priority_item_branchcode eq
966 $local_holds_priority_patron_branchcode;
969 # See if this item is more important than what we've got so far
970 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
971 $iteminfo ||= C4::Items::GetItem($itemnumber);
972 next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
973 $borrowerinfo ||= C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
974 my $branch = GetReservesControlBranch( $iteminfo, $borrowerinfo );
975 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
976 next if ($branchitemrule->{'holdallowed'} == 0);
977 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $borrowerinfo->{'branchcode'}));
978 next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy} }) );
979 $priority = $res->{'priority'};
980 $highest = $res;
981 last if $local_hold_match;
987 # If we get this far, then no exact match was found.
988 # We return the most important (i.e. next) reservation.
989 if ($highest) {
990 $highest->{'itemnumber'} = $item;
991 return ( "Reserved", $highest, \@reserves );
994 return ( '' );
997 =head2 CancelExpiredReserves
999 CancelExpiredReserves();
1001 Cancels all reserves with an expiration date from before today.
1003 =cut
1005 sub CancelExpiredReserves {
1007 # Cancel reserves that have passed their expiration date.
1008 my $dbh = C4::Context->dbh;
1009 my $sth = $dbh->prepare( "
1010 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
1011 AND expirationdate IS NOT NULL
1012 AND found IS NULL
1013 " );
1014 $sth->execute();
1016 while ( my $res = $sth->fetchrow_hashref() ) {
1017 CancelReserve({ reserve_id => $res->{'reserve_id'} });
1020 # Cancel reserves that have been waiting too long
1021 if ( C4::Context->preference("ExpireReservesMaxPickUpDelay") ) {
1022 my $max_pickup_delay = C4::Context->preference("ReservesMaxPickUpDelay");
1023 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
1025 my $today = dt_from_string();
1027 my $query = "SELECT * FROM reserves WHERE TO_DAYS( NOW() ) - TO_DAYS( waitingdate ) > ? AND found = 'W' AND priority = 0";
1028 $sth = $dbh->prepare( $query );
1029 $sth->execute( $max_pickup_delay );
1031 while ( my $res = $sth->fetchrow_hashref ) {
1032 my $do_cancel = 1;
1033 unless ( $cancel_on_holidays ) {
1034 my $calendar = Koha::Calendar->new( branchcode => $res->{'branchcode'} );
1035 my $is_holiday = $calendar->is_holiday( $today );
1037 if ( $is_holiday ) {
1038 $do_cancel = 0;
1042 if ( $do_cancel ) {
1043 CancelReserve({ reserve_id => $res->{'reserve_id'}, charge_cancel_fee => 1 });
1050 =head2 AutoUnsuspendReserves
1052 AutoUnsuspendReserves();
1054 Unsuspends all suspended reserves with a suspend_until date from before today.
1056 =cut
1058 sub AutoUnsuspendReserves {
1059 my $today = dt_from_string();
1061 my @holds = Koha::Holds->search( { suspend_until => { '<' => $today->ymd() } } );
1063 map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
1066 =head2 CancelReserve
1068 CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber, ] [ charge_cancel_fee => 1 ] });
1070 Cancels a reserve. If C<charge_cancel_fee> is passed and the C<ExpireReservesMaxPickUpDelayCharge> syspref is set, charge that fee to the patron's account.
1072 =cut
1074 sub CancelReserve {
1075 my ( $params ) = @_;
1077 my $reserve_id = $params->{'reserve_id'};
1078 # Filter out only the desired keys; this will insert undefined values for elements missing in
1079 # \%params, but GetReserveId filters them out anyway.
1080 $reserve_id = GetReserveId( { biblionumber => $params->{'biblionumber'}, borrowernumber => $params->{'borrowernumber'}, itemnumber => $params->{'itemnumber'} } ) unless ( $reserve_id );
1082 return unless ( $reserve_id );
1084 my $dbh = C4::Context->dbh;
1086 my $reserve = GetReserve( $reserve_id );
1087 if ($reserve) {
1089 my $hold = Koha::Holds->find( $reserve_id );
1090 logaction( 'HOLDS', 'CANCEL', $hold->reserve_id, Dumper($hold->unblessed) )
1091 if C4::Context->preference('HoldsLog');
1093 my $query = "
1094 UPDATE reserves
1095 SET cancellationdate = now(),
1096 priority = 0
1097 WHERE reserve_id = ?
1099 my $sth = $dbh->prepare($query);
1100 $sth->execute( $reserve_id );
1102 $query = "
1103 INSERT INTO old_reserves
1104 SELECT * FROM reserves
1105 WHERE reserve_id = ?
1107 $sth = $dbh->prepare($query);
1108 $sth->execute( $reserve_id );
1110 $query = "
1111 DELETE FROM reserves
1112 WHERE reserve_id = ?
1114 $sth = $dbh->prepare($query);
1115 $sth->execute( $reserve_id );
1117 # now fix the priority on the others....
1118 _FixPriority({ biblionumber => $reserve->{biblionumber} });
1120 # and, if desired, charge a cancel fee
1121 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
1122 if ( $charge && $params->{'charge_cancel_fee'} ) {
1123 manualinvoice($reserve->{'borrowernumber'}, $reserve->{'itemnumber'}, '', 'HE', $charge);
1127 return $reserve;
1130 =head2 ModReserve
1132 ModReserve({ rank => $rank,
1133 reserve_id => $reserve_id,
1134 branchcode => $branchcode
1135 [, itemnumber => $itemnumber ]
1136 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1139 Change a hold request's priority or cancel it.
1141 C<$rank> specifies the effect of the change. If C<$rank>
1142 is 'W' or 'n', nothing happens. This corresponds to leaving a
1143 request alone when changing its priority in the holds queue
1144 for a bib.
1146 If C<$rank> is 'del', the hold request is cancelled.
1148 If C<$rank> is an integer greater than zero, the priority of
1149 the request is set to that value. Since priority != 0 means
1150 that the item is not waiting on the hold shelf, setting the
1151 priority to a non-zero value also sets the request's found
1152 status and waiting date to NULL.
1154 The optional C<$itemnumber> parameter is used only when
1155 C<$rank> is a non-zero integer; if supplied, the itemnumber
1156 of the hold request is set accordingly; if omitted, the itemnumber
1157 is cleared.
1159 B<FIXME:> Note that the forgoing can have the effect of causing
1160 item-level hold requests to turn into title-level requests. This
1161 will be fixed once reserves has separate columns for requested
1162 itemnumber and supplying itemnumber.
1164 =cut
1166 sub ModReserve {
1167 my ( $params ) = @_;
1169 my $rank = $params->{'rank'};
1170 my $reserve_id = $params->{'reserve_id'};
1171 my $branchcode = $params->{'branchcode'};
1172 my $itemnumber = $params->{'itemnumber'};
1173 my $suspend_until = $params->{'suspend_until'};
1174 my $borrowernumber = $params->{'borrowernumber'};
1175 my $biblionumber = $params->{'biblionumber'};
1177 return if $rank eq "W";
1178 return if $rank eq "n";
1180 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1181 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber }) unless ( $reserve_id );
1183 if ( $rank eq "del" ) {
1184 CancelReserve({ reserve_id => $reserve_id });
1186 elsif ($rank =~ /^\d+/ and $rank > 0) {
1187 my $hold = Koha::Holds->find($reserve_id);
1188 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1189 if C4::Context->preference('HoldsLog');
1191 $hold->set(
1193 priority => $rank,
1194 branchcode => $branchcode,
1195 itemnumber => $itemnumber,
1196 found => undef,
1197 waitingdate => undef
1199 )->store();
1201 if ( defined( $suspend_until ) ) {
1202 if ( $suspend_until ) {
1203 $suspend_until = eval { dt_from_string( $suspend_until ) };
1204 $hold->suspend_hold( $suspend_until );
1205 } else {
1206 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1207 # If the hold is not suspended, this does nothing.
1208 $hold->set( { suspend_until => undef } )->store();
1212 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1216 =head2 ModReserveFill
1218 &ModReserveFill($reserve);
1220 Fill a reserve. If I understand this correctly, this means that the
1221 reserved book has been found and given to the patron who reserved it.
1223 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1224 whose keys are fields from the reserves table in the Koha database.
1226 =cut
1228 sub ModReserveFill {
1229 my ($res) = @_;
1230 my $reserve_id = $res->{'reserve_id'};
1232 my $hold = Koha::Holds->find($reserve_id);
1234 # get the priority on this record....
1235 my $priority = $hold->priority;
1237 # update the hold statuses, no need to store it though, we will be deleting it anyway
1238 $hold->set(
1240 found => 'F',
1241 priority => 0,
1245 Koha::Old::Hold->new( $hold->unblessed() )->store();
1247 $hold->delete();
1249 # now fix the priority on the others (if the priority wasn't
1250 # already sorted!)....
1251 unless ( $priority == 0 ) {
1252 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1256 =head2 ModReserveStatus
1258 &ModReserveStatus($itemnumber, $newstatus);
1260 Update the reserve status for the active (priority=0) reserve.
1262 $itemnumber is the itemnumber the reserve is on
1264 $newstatus is the new status.
1266 =cut
1268 sub ModReserveStatus {
1270 #first : check if we have a reservation for this item .
1271 my ($itemnumber, $newstatus) = @_;
1272 my $dbh = C4::Context->dbh;
1274 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1275 my $sth_set = $dbh->prepare($query);
1276 $sth_set->execute( $newstatus, $itemnumber );
1278 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1279 CartToShelf( $itemnumber );
1283 =head2 ModReserveAffect
1285 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend);
1287 This function affect an item and a status for a given reserve
1288 The itemnumber parameter is used to find the biblionumber.
1289 with the biblionumber & the borrowernumber, we can affect the itemnumber
1290 to the correct reserve.
1292 if $transferToDo is not set, then the status is set to "Waiting" as well.
1293 otherwise, a transfer is on the way, and the end of the transfer will
1294 take care of the waiting status
1296 =cut
1298 sub ModReserveAffect {
1299 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1300 my $dbh = C4::Context->dbh;
1302 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1303 # attached to $itemnumber
1304 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1305 $sth->execute($itemnumber);
1306 my ($biblionumber) = $sth->fetchrow;
1308 # get request - need to find out if item is already
1309 # waiting in order to not send duplicate hold filled notifications
1311 my $hold;
1312 # Find hold by id if we have it
1313 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1314 # Find item level hold for this item if there is one
1315 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1316 # Find record level hold if there is no item level hold
1317 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1319 return unless $hold;
1321 $reserve_id = $hold->id();
1323 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1325 # If we affect a reserve that has to be transferred, don't set to Waiting
1326 my $query;
1327 if ($transferToDo) {
1328 $hold->set(
1330 priority => 0,
1331 itemnumber => $itemnumber,
1332 found => 'T',
1336 else {
1337 # affect the reserve to Waiting as well.
1338 $hold->set(
1340 priority => 0,
1341 itemnumber => $itemnumber,
1342 found => 'W',
1343 waitingdate => dt_from_string(),
1347 $hold->store();
1349 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber )
1350 if ( !$transferToDo && !$already_on_shelf );
1352 _FixPriority( { biblionumber => $biblionumber } );
1354 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1355 CartToShelf($itemnumber);
1358 return;
1361 =head2 ModReserveCancelAll
1363 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1365 function to cancel reserv,check other reserves, and transfer document if it's necessary
1367 =cut
1369 sub ModReserveCancelAll {
1370 my $messages;
1371 my $nextreservinfo;
1372 my ( $itemnumber, $borrowernumber ) = @_;
1374 #step 1 : cancel the reservation
1375 my $CancelReserve = CancelReserve({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1377 #step 2 launch the subroutine of the others reserves
1378 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1380 return ( $messages, $nextreservinfo );
1383 =head2 ModReserveMinusPriority
1385 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1387 Reduce the values of queued list
1389 =cut
1391 sub ModReserveMinusPriority {
1392 my ( $itemnumber, $reserve_id ) = @_;
1394 #first step update the value of the first person on reserv
1395 my $dbh = C4::Context->dbh;
1396 my $query = "
1397 UPDATE reserves
1398 SET priority = 0 , itemnumber = ?
1399 WHERE reserve_id = ?
1401 my $sth_upd = $dbh->prepare($query);
1402 $sth_upd->execute( $itemnumber, $reserve_id );
1403 # second step update all others reserves
1404 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1407 =head2 GetReserveInfo
1409 &GetReserveInfo($reserve_id);
1411 Get item and borrower details for a current hold.
1412 Current implementation this query should have a single result.
1414 =cut
1416 sub GetReserveInfo {
1417 my ( $reserve_id ) = @_;
1418 my $dbh = C4::Context->dbh;
1419 my $strsth="SELECT
1420 reserve_id,
1421 reservedate,
1422 reservenotes,
1423 reserves.borrowernumber,
1424 reserves.biblionumber,
1425 reserves.branchcode,
1426 reserves.waitingdate,
1427 notificationdate,
1428 reminderdate,
1429 priority,
1430 found,
1431 firstname,
1432 surname,
1433 phone,
1434 email,
1435 address,
1436 address2,
1437 cardnumber,
1438 city,
1439 zipcode,
1440 biblio.title,
1441 biblio.author,
1442 items.holdingbranch,
1443 items.itemcallnumber,
1444 items.itemnumber,
1445 items.location,
1446 barcode,
1447 notes
1448 FROM reserves
1449 LEFT JOIN items USING(itemnumber)
1450 LEFT JOIN borrowers USING(borrowernumber)
1451 LEFT JOIN biblio ON (reserves.biblionumber=biblio.biblionumber)
1452 WHERE reserves.reserve_id = ?";
1453 my $sth = $dbh->prepare($strsth);
1454 $sth->execute($reserve_id);
1456 my $data = $sth->fetchrow_hashref;
1457 return $data;
1460 =head2 IsAvailableForItemLevelRequest
1462 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1464 Checks whether a given item record is available for an
1465 item-level hold request. An item is available if
1467 * it is not lost AND
1468 * it is not damaged AND
1469 * it is not withdrawn AND
1470 * does not have a not for loan value > 0
1472 Need to check the issuingrules onshelfholds column,
1473 if this is set items on the shelf can be placed on hold
1475 Note that IsAvailableForItemLevelRequest() does not
1476 check if the staff operator is authorized to place
1477 a request on the item - in particular,
1478 this routine does not check IndependentBranches
1479 and canreservefromotherbranches.
1481 =cut
1483 sub IsAvailableForItemLevelRequest {
1484 my $item = shift;
1485 my $borrower = shift;
1487 my $dbh = C4::Context->dbh;
1488 # must check the notforloan setting of the itemtype
1489 # FIXME - a lot of places in the code do this
1490 # or something similar - need to be
1491 # consolidated
1492 my $itype = _get_itype($item);
1493 my $notforloan_per_itemtype
1494 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1495 undef, $itype);
1497 return 0 if
1498 $notforloan_per_itemtype ||
1499 $item->{itemlost} ||
1500 $item->{notforloan} > 0 ||
1501 $item->{withdrawn} ||
1502 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1504 my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1506 if ( $on_shelf_holds == 1 ) {
1507 return 1;
1508 } elsif ( $on_shelf_holds == 2 ) {
1509 my @items =
1510 Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1512 my $any_available = 0;
1514 foreach my $i (@items) {
1515 $any_available = 1
1516 unless $i->itemlost
1517 || $i->{notforloan} > 0
1518 || $i->withdrawn
1519 || $i->onloan
1520 || IsItemOnHoldAndFound( $i->id )
1521 || ( $i->damaged
1522 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1523 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan;
1526 return $any_available ? 0 : 1;
1529 return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
1532 =head2 OnShelfHoldsAllowed
1534 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1536 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1537 holds are allowed, returns true if so.
1539 =cut
1541 sub OnShelfHoldsAllowed {
1542 my ($item, $borrower) = @_;
1544 my $itype = _get_itype($item);
1545 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1548 sub _get_itype {
1549 my $item = shift;
1551 my $itype;
1552 if (C4::Context->preference('item-level_itypes')) {
1553 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1554 # When GetItem is fixed, we can remove this
1555 $itype = $item->{itype};
1557 else {
1558 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1559 # So if we already have a biblioitems join when calling this function,
1560 # we don't need to access the database again
1561 $itype = $item->{itemtype};
1563 unless ($itype) {
1564 my $dbh = C4::Context->dbh;
1565 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1566 my $sth = $dbh->prepare($query);
1567 $sth->execute($item->{biblioitemnumber});
1568 if (my $data = $sth->fetchrow_hashref()){
1569 $itype = $data->{itemtype};
1572 return $itype;
1575 sub _OnShelfHoldsAllowed {
1576 my ($itype,$borrowercategory,$branchcode) = @_;
1578 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
1579 return $issuing_rule ? $issuing_rule->onshelfholds : undef;
1582 =head2 AlterPriority
1584 AlterPriority( $where, $reserve_id );
1586 This function changes a reserve's priority up, down, to the top, or to the bottom.
1587 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1589 =cut
1591 sub AlterPriority {
1592 my ( $where, $reserve_id ) = @_;
1594 my $reserve = GetReserve( $reserve_id );
1596 if ( $reserve->{cancellationdate} ) {
1597 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (".$reserve->{cancellationdate}.')';
1598 return;
1601 if ( $where eq 'up' || $where eq 'down' ) {
1603 my $priority = $reserve->{'priority'};
1604 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1605 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1607 } elsif ( $where eq 'top' ) {
1609 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1611 } elsif ( $where eq 'bottom' ) {
1613 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1618 =head2 ToggleLowestPriority
1620 ToggleLowestPriority( $borrowernumber, $biblionumber );
1622 This function sets the lowestPriority field to true if is false, and false if it is true.
1624 =cut
1626 sub ToggleLowestPriority {
1627 my ( $reserve_id ) = @_;
1629 my $dbh = C4::Context->dbh;
1631 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1632 $sth->execute( $reserve_id );
1634 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1637 =head2 ToggleSuspend
1639 ToggleSuspend( $reserve_id );
1641 This function sets the suspend field to true if is false, and false if it is true.
1642 If the reserve is currently suspended with a suspend_until date, that date will
1643 be cleared when it is unsuspended.
1645 =cut
1647 sub ToggleSuspend {
1648 my ( $reserve_id, $suspend_until ) = @_;
1650 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1652 my $hold = Koha::Holds->find( $reserve_id );
1654 if ( $hold->is_suspended ) {
1655 $hold->resume()
1656 } else {
1657 $hold->suspend_hold( $suspend_until );
1661 =head2 SuspendAll
1663 SuspendAll(
1664 borrowernumber => $borrowernumber,
1665 [ biblionumber => $biblionumber, ]
1666 [ suspend_until => $suspend_until, ]
1667 [ suspend => $suspend ]
1670 This function accepts a set of hash keys as its parameters.
1671 It requires either borrowernumber or biblionumber, or both.
1673 suspend_until is wholly optional.
1675 =cut
1677 sub SuspendAll {
1678 my %params = @_;
1680 my $borrowernumber = $params{'borrowernumber'} || undef;
1681 my $biblionumber = $params{'biblionumber'} || undef;
1682 my $suspend_until = $params{'suspend_until'} || undef;
1683 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1685 $suspend_until = eval { dt_from_string($suspend_until) }
1686 if ( defined($suspend_until) );
1688 return unless ( $borrowernumber || $biblionumber );
1690 my $params;
1691 $params->{found} = undef;
1692 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1693 $params->{biblionumber} = $biblionumber if $biblionumber;
1695 my @holds = Koha::Holds->search($params);
1697 if ($suspend) {
1698 map { $_->suspend_hold($suspend_until) } @holds;
1700 else {
1701 map { $_->resume() } @holds;
1706 =head2 _FixPriority
1708 _FixPriority({
1709 reserve_id => $reserve_id,
1710 [rank => $rank,]
1711 [ignoreSetLowestRank => $ignoreSetLowestRank]
1716 _FixPriority({ biblionumber => $biblionumber});
1718 This routine adjusts the priority of a hold request and holds
1719 on the same bib.
1721 In the first form, where a reserve_id is passed, the priority of the
1722 hold is set to supplied rank, and other holds for that bib are adjusted
1723 accordingly. If the rank is "del", the hold is cancelled. If no rank
1724 is supplied, all of the holds on that bib have their priority adjusted
1725 as if the second form had been used.
1727 In the second form, where a biblionumber is passed, the holds on that
1728 bib (that are not captured) are sorted in order of increasing priority,
1729 then have reserves.priority set so that the first non-captured hold
1730 has its priority set to 1, the second non-captured hold has its priority
1731 set to 2, and so forth.
1733 In both cases, holds that have the lowestPriority flag on are have their
1734 priority adjusted to ensure that they remain at the end of the line.
1736 Note that the ignoreSetLowestRank parameter is meant to be used only
1737 when _FixPriority calls itself.
1739 =cut
1741 sub _FixPriority {
1742 my ( $params ) = @_;
1743 my $reserve_id = $params->{reserve_id};
1744 my $rank = $params->{rank} // '';
1745 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1746 my $biblionumber = $params->{biblionumber};
1748 my $dbh = C4::Context->dbh;
1750 unless ( $biblionumber ) {
1751 my $res = GetReserve( $reserve_id );
1752 $biblionumber = $res->{biblionumber};
1755 if ( $rank eq "del" ) {
1756 CancelReserve({ reserve_id => $reserve_id });
1758 elsif ( $rank eq "W" || $rank eq "0" ) {
1760 # make sure priority for waiting or in-transit items is 0
1761 my $query = "
1762 UPDATE reserves
1763 SET priority = 0
1764 WHERE reserve_id = ?
1765 AND found IN ('W', 'T')
1767 my $sth = $dbh->prepare($query);
1768 $sth->execute( $reserve_id );
1770 my @priority;
1772 # get whats left
1773 my $query = "
1774 SELECT reserve_id, borrowernumber, reservedate
1775 FROM reserves
1776 WHERE biblionumber = ?
1777 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1778 ORDER BY priority ASC
1780 my $sth = $dbh->prepare($query);
1781 $sth->execute( $biblionumber );
1782 while ( my $line = $sth->fetchrow_hashref ) {
1783 push( @priority, $line );
1786 # To find the matching index
1787 my $i;
1788 my $key = -1; # to allow for 0 to be a valid result
1789 for ( $i = 0 ; $i < @priority ; $i++ ) {
1790 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1791 $key = $i; # save the index
1792 last;
1796 # if index exists in array then move it to new position
1797 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1798 my $new_rank = $rank -
1799 1; # $new_rank is what you want the new index to be in the array
1800 my $moving_item = splice( @priority, $key, 1 );
1801 splice( @priority, $new_rank, 0, $moving_item );
1804 # now fix the priority on those that are left....
1805 $query = "
1806 UPDATE reserves
1807 SET priority = ?
1808 WHERE reserve_id = ?
1810 $sth = $dbh->prepare($query);
1811 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1812 $sth->execute(
1813 $j + 1,
1814 $priority[$j]->{'reserve_id'}
1818 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1819 $sth->execute();
1821 unless ( $ignoreSetLowestRank ) {
1822 while ( my $res = $sth->fetchrow_hashref() ) {
1823 _FixPriority({
1824 reserve_id => $res->{'reserve_id'},
1825 rank => '999999',
1826 ignoreSetLowestRank => 1
1832 =head2 _Findgroupreserve
1834 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1836 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1837 first match found. If neither, then we look for non-holds-queue based holds.
1838 Lookahead is the number of days to look in advance.
1840 C<&_Findgroupreserve> returns :
1841 C<@results> is an array of references-to-hash whose keys are mostly
1842 fields from the reserves table of the Koha database, plus
1843 C<biblioitemnumber>.
1845 =cut
1847 sub _Findgroupreserve {
1848 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1849 my $dbh = C4::Context->dbh;
1851 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1852 # check for exact targeted match
1853 my $item_level_target_query = qq{
1854 SELECT reserves.biblionumber AS biblionumber,
1855 reserves.borrowernumber AS borrowernumber,
1856 reserves.reservedate AS reservedate,
1857 reserves.branchcode AS branchcode,
1858 reserves.cancellationdate AS cancellationdate,
1859 reserves.found AS found,
1860 reserves.reservenotes AS reservenotes,
1861 reserves.priority AS priority,
1862 reserves.timestamp AS timestamp,
1863 biblioitems.biblioitemnumber AS biblioitemnumber,
1864 reserves.itemnumber AS itemnumber,
1865 reserves.reserve_id AS reserve_id,
1866 reserves.itemtype AS itemtype
1867 FROM reserves
1868 JOIN biblioitems USING (biblionumber)
1869 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1870 WHERE found IS NULL
1871 AND priority > 0
1872 AND item_level_request = 1
1873 AND itemnumber = ?
1874 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1875 AND suspend = 0
1876 ORDER BY priority
1878 my $sth = $dbh->prepare($item_level_target_query);
1879 $sth->execute($itemnumber, $lookahead||0);
1880 my @results;
1881 if ( my $data = $sth->fetchrow_hashref ) {
1882 push( @results, $data )
1883 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1885 return @results if @results;
1887 # check for title-level targeted match
1888 my $title_level_target_query = qq{
1889 SELECT reserves.biblionumber AS biblionumber,
1890 reserves.borrowernumber AS borrowernumber,
1891 reserves.reservedate AS reservedate,
1892 reserves.branchcode AS branchcode,
1893 reserves.cancellationdate AS cancellationdate,
1894 reserves.found AS found,
1895 reserves.reservenotes AS reservenotes,
1896 reserves.priority AS priority,
1897 reserves.timestamp AS timestamp,
1898 biblioitems.biblioitemnumber AS biblioitemnumber,
1899 reserves.itemnumber AS itemnumber,
1900 reserves.reserve_id AS reserve_id,
1901 reserves.itemtype AS itemtype
1902 FROM reserves
1903 JOIN biblioitems USING (biblionumber)
1904 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1905 WHERE found IS NULL
1906 AND priority > 0
1907 AND item_level_request = 0
1908 AND hold_fill_targets.itemnumber = ?
1909 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1910 AND suspend = 0
1911 ORDER BY priority
1913 $sth = $dbh->prepare($title_level_target_query);
1914 $sth->execute($itemnumber, $lookahead||0);
1915 @results = ();
1916 if ( my $data = $sth->fetchrow_hashref ) {
1917 push( @results, $data )
1918 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1920 return @results if @results;
1922 my $query = qq{
1923 SELECT reserves.biblionumber AS biblionumber,
1924 reserves.borrowernumber AS borrowernumber,
1925 reserves.reservedate AS reservedate,
1926 reserves.waitingdate AS waitingdate,
1927 reserves.branchcode AS branchcode,
1928 reserves.cancellationdate AS cancellationdate,
1929 reserves.found AS found,
1930 reserves.reservenotes AS reservenotes,
1931 reserves.priority AS priority,
1932 reserves.timestamp AS timestamp,
1933 reserves.itemnumber AS itemnumber,
1934 reserves.reserve_id AS reserve_id,
1935 reserves.itemtype AS itemtype
1936 FROM reserves
1937 WHERE reserves.biblionumber = ?
1938 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1939 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1940 AND suspend = 0
1941 ORDER BY priority
1943 $sth = $dbh->prepare($query);
1944 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1945 @results = ();
1946 while ( my $data = $sth->fetchrow_hashref ) {
1947 push( @results, $data )
1948 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1950 return @results;
1953 =head2 _koha_notify_reserve
1955 _koha_notify_reserve( $itemnumber, $borrowernumber, $biblionumber );
1957 Sends a notification to the patron that their hold has been filled (through
1958 ModReserveAffect, _not_ ModReserveFill)
1960 The letter code for this notice may be found using the following query:
1962 select distinct letter_code
1963 from message_transports
1964 inner join message_attributes using (message_attribute_id)
1965 where message_name = 'Hold_Filled'
1967 This will probably sipmly be 'HOLD', but because it is defined in the database,
1968 it is subject to addition or change.
1970 The following tables are availalbe witin the notice:
1972 branches
1973 borrowers
1974 biblio
1975 biblioitems
1976 reserves
1977 items
1979 =cut
1981 sub _koha_notify_reserve {
1982 my ($itemnumber, $borrowernumber, $biblionumber) = @_;
1984 my $dbh = C4::Context->dbh;
1985 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
1987 # Try to get the borrower's email address
1988 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1990 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1991 borrowernumber => $borrowernumber,
1992 message_name => 'Hold_Filled'
1993 } );
1995 my $sth = $dbh->prepare("
1996 SELECT *
1997 FROM reserves
1998 WHERE borrowernumber = ?
1999 AND biblionumber = ?
2001 $sth->execute( $borrowernumber, $biblionumber );
2002 my $reserve = $sth->fetchrow_hashref;
2003 my $library = Koha::Libraries->find( $reserve->{branchcode} )->unblessed;
2005 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
2007 my %letter_params = (
2008 module => 'reserves',
2009 branchcode => $reserve->{branchcode},
2010 tables => {
2011 'branches' => $library,
2012 'borrowers' => $borrower,
2013 'biblio' => $biblionumber,
2014 'biblioitems' => $biblionumber,
2015 'reserves' => $reserve,
2016 'items' => $reserve->{'itemnumber'},
2018 substitute => { today => output_pref( { dt => dt_from_string, dateonly => 1 } ) },
2021 my $notification_sent = 0; #Keeping track if a Hold_filled message is sent. If no message can be sent, then default to a print message.
2022 my $send_notification = sub {
2023 my ( $mtt, $letter_code ) = (@_);
2024 return unless defined $letter_code;
2025 $letter_params{letter_code} = $letter_code;
2026 $letter_params{message_transport_type} = $mtt;
2027 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
2028 unless ($letter) {
2029 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
2030 return;
2033 C4::Letters::EnqueueLetter( {
2034 letter => $letter,
2035 borrowernumber => $borrowernumber,
2036 from_address => $admin_email_address,
2037 message_transport_type => $mtt,
2038 } );
2041 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
2042 next if (
2043 ( $mtt eq 'email' and not $to_address ) # No email address
2044 or ( $mtt eq 'sms' and not $borrower->{smsalertnumber} ) # No SMS number
2045 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
2048 &$send_notification($mtt, $letter_code);
2049 $notification_sent++;
2051 #Making sure that a print notification is sent if no other transport types can be utilized.
2052 if (! $notification_sent) {
2053 &$send_notification('print', 'HOLD');
2058 =head2 _ShiftPriorityByDateAndPriority
2060 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
2062 This increments the priority of all reserves after the one
2063 with either the lowest date after C<$reservedate>
2064 or the lowest priority after C<$priority>.
2066 It effectively makes room for a new reserve to be inserted with a certain
2067 priority, which is returned.
2069 This is most useful when the reservedate can be set by the user. It allows
2070 the new reserve to be placed before other reserves that have a later
2071 reservedate. Since priority also is set by the form in reserves/request.pl
2072 the sub accounts for that too.
2074 =cut
2076 sub _ShiftPriorityByDateAndPriority {
2077 my ( $biblio, $resdate, $new_priority ) = @_;
2079 my $dbh = C4::Context->dbh;
2080 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
2081 my $sth = $dbh->prepare( $query );
2082 $sth->execute( $biblio, $resdate, $new_priority );
2083 my $min_priority = $sth->fetchrow;
2084 # if no such matches are found, $new_priority remains as original value
2085 $new_priority = $min_priority if ( $min_priority );
2087 # Shift the priority up by one; works in conjunction with the next SQL statement
2088 $query = "UPDATE reserves
2089 SET priority = priority+1
2090 WHERE biblionumber = ?
2091 AND borrowernumber = ?
2092 AND reservedate = ?
2093 AND found IS NULL";
2094 my $sth_update = $dbh->prepare( $query );
2096 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
2097 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
2098 $sth = $dbh->prepare( $query );
2099 $sth->execute( $new_priority, $biblio );
2100 while ( my $row = $sth->fetchrow_hashref ) {
2101 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
2104 return $new_priority; # so the caller knows what priority they wind up receiving
2107 =head2 OPACItemHoldsAllowed
2109 OPACItemHoldsAllowed($item_record,$borrower_record);
2111 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
2112 if specific item holds are allowed, returns true if so.
2114 =cut
2116 sub OPACItemHoldsAllowed {
2117 my ($item,$borrower) = @_;
2119 my $branchcode = $item->{homebranch} or die "No homebranch";
2120 my $itype;
2121 my $dbh = C4::Context->dbh;
2122 if (C4::Context->preference('item-level_itypes')) {
2123 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
2124 # When GetItem is fixed, we can remove this
2125 $itype = $item->{itype};
2127 else {
2128 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
2129 my $sth = $dbh->prepare($query);
2130 $sth->execute($item->{biblioitemnumber});
2131 if (my $data = $sth->fetchrow_hashref()){
2132 $itype = $data->{itemtype};
2136 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
2137 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
2139 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
2141 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
2142 ORDER BY
2143 issuingrules.categorycode desc,
2144 issuingrules.itemtype desc,
2145 issuingrules.branchcode desc
2146 LIMIT 1";
2147 my $sth = $dbh->prepare($query);
2148 $sth->execute($borrower->{categorycode},$itype,$branchcode);
2149 my $data = $sth->fetchrow_hashref;
2150 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
2151 return '' if $opacitemholds eq 'N';
2152 return $opacitemholds;
2155 =head2 MoveReserve
2157 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2159 Use when checking out an item to handle reserves
2160 If $cancelreserve boolean is set to true, it will remove existing reserve
2162 =cut
2164 sub MoveReserve {
2165 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2167 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2168 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
2169 return unless $res;
2171 my $biblionumber = $res->{biblionumber};
2173 if ($res->{borrowernumber} == $borrowernumber) {
2174 ModReserveFill($res);
2176 else {
2177 # warn "Reserved";
2178 # The item is reserved by someone else.
2179 # Find this item in the reserves
2181 my $borr_res;
2182 foreach (@$all_reserves) {
2183 $_->{'borrowernumber'} == $borrowernumber or next;
2184 $_->{'biblionumber'} == $biblionumber or next;
2186 $borr_res = $_;
2187 last;
2190 if ( $borr_res ) {
2191 # The item is reserved by the current patron
2192 ModReserveFill($borr_res);
2195 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2196 RevertWaitingStatus({ itemnumber => $itemnumber });
2198 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2199 CancelReserve( { reserve_id => $res->{'reserve_id'} } );
2204 =head2 MergeHolds
2206 MergeHolds($dbh,$to_biblio, $from_biblio);
2208 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2210 =cut
2212 sub MergeHolds {
2213 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2214 my $sth = $dbh->prepare(
2215 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2217 $sth->execute($from_biblio);
2218 if ( my $data = $sth->fetchrow_hashref() ) {
2220 # holds exist on old record, if not we don't need to do anything
2221 $sth = $dbh->prepare(
2222 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2223 $sth->execute( $to_biblio, $from_biblio );
2225 # Reorder by date
2226 # don't reorder those already waiting
2228 $sth = $dbh->prepare(
2229 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
2231 my $upd_sth = $dbh->prepare(
2232 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2233 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2235 $sth->execute( $to_biblio, 'W', 'T' );
2236 my $priority = 1;
2237 while ( my $reserve = $sth->fetchrow_hashref() ) {
2238 $upd_sth->execute(
2239 $priority, $to_biblio,
2240 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2241 $reserve->{'itemnumber'}
2243 $priority++;
2248 =head2 RevertWaitingStatus
2250 RevertWaitingStatus({ itemnumber => $itemnumber });
2252 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2254 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2255 item level hold, even if it was only a bibliolevel hold to
2256 begin with. This is because we can no longer know if a hold
2257 was item-level or bib-level after a hold has been set to
2258 waiting status.
2260 =cut
2262 sub RevertWaitingStatus {
2263 my ( $params ) = @_;
2264 my $itemnumber = $params->{'itemnumber'};
2266 return unless ( $itemnumber );
2268 my $dbh = C4::Context->dbh;
2270 ## Get the waiting reserve we want to revert
2271 my $query = "
2272 SELECT * FROM reserves
2273 WHERE itemnumber = ?
2274 AND found IS NOT NULL
2276 my $sth = $dbh->prepare( $query );
2277 $sth->execute( $itemnumber );
2278 my $reserve = $sth->fetchrow_hashref();
2280 ## Increment the priority of all other non-waiting
2281 ## reserves for this bib record
2282 $query = "
2283 UPDATE reserves
2285 priority = priority + 1
2286 WHERE
2287 biblionumber = ?
2289 priority > 0
2291 $sth = $dbh->prepare( $query );
2292 $sth->execute( $reserve->{'biblionumber'} );
2294 ## Fix up the currently waiting reserve
2295 $query = "
2296 UPDATE reserves
2298 priority = 1,
2299 found = NULL,
2300 waitingdate = NULL
2301 WHERE
2302 reserve_id = ?
2304 $sth = $dbh->prepare( $query );
2305 $sth->execute( $reserve->{'reserve_id'} );
2306 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2309 =head2 GetReserveId
2311 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber [, itemnumber => $itemnumber ] });
2313 Returnes the first reserve id that matches the given criteria
2315 =cut
2317 sub GetReserveId {
2318 my ( $params ) = @_;
2320 return unless ( ( $params->{'biblionumber'} || $params->{'itemnumber'} ) && $params->{'borrowernumber'} );
2322 foreach my $key ( keys %$params ) {
2323 delete $params->{$key} unless defined( $params->{$key} );
2326 my $hold = Koha::Holds->search( $params )->next();
2328 return unless $hold;
2330 return $hold->id();
2333 =head2 ReserveSlip
2335 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2337 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2339 The letter code will be HOLD_SLIP, and the following tables are
2340 available within the slip:
2342 reserves
2343 branches
2344 borrowers
2345 biblio
2346 biblioitems
2347 items
2349 =cut
2351 sub ReserveSlip {
2352 my ($branch, $borrowernumber, $biblionumber) = @_;
2354 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2356 my $reserve_id = GetReserveId({
2357 biblionumber => $biblionumber,
2358 borrowernumber => $borrowernumber
2359 }) or return;
2360 my $reserve = GetReserveInfo($reserve_id) or return;
2362 return C4::Letters::GetPreparedLetter (
2363 module => 'circulation',
2364 letter_code => 'HOLD_SLIP',
2365 branchcode => $branch,
2366 tables => {
2367 'reserves' => $reserve,
2368 'branches' => $reserve->{branchcode},
2369 'borrowers' => $reserve->{borrowernumber},
2370 'biblio' => $reserve->{biblionumber},
2371 'biblioitems' => $reserve->{biblionumber},
2372 'items' => $reserve->{itemnumber},
2377 =head2 GetReservesControlBranch
2379 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2381 Return the branchcode to be used to determine which reserves
2382 policy applies to a transaction.
2384 C<$item> is a hashref for an item. Only 'homebranch' is used.
2386 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2388 =cut
2390 sub GetReservesControlBranch {
2391 my ( $item, $borrower ) = @_;
2393 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2395 my $branchcode =
2396 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2397 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2398 : undef;
2400 return $branchcode;
2403 =head2 CalculatePriority
2405 my $p = CalculatePriority($biblionumber, $resdate);
2407 Calculate priority for a new reserve on biblionumber, placing it at
2408 the end of the line of all holds whose start date falls before
2409 the current system time and that are neither on the hold shelf
2410 or in transit.
2412 The reserve date parameter is optional; if it is supplied, the
2413 priority is based on the set of holds whose start date falls before
2414 the parameter value.
2416 After calculation of this priority, it is recommended to call
2417 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2418 AddReserves.
2420 =cut
2422 sub CalculatePriority {
2423 my ( $biblionumber, $resdate ) = @_;
2425 my $sql = q{
2426 SELECT COUNT(*) FROM reserves
2427 WHERE biblionumber = ?
2428 AND priority > 0
2429 AND (found IS NULL OR found = '')
2431 #skip found==W or found==T (waiting or transit holds)
2432 if( $resdate ) {
2433 $sql.= ' AND ( reservedate <= ? )';
2435 else {
2436 $sql.= ' AND ( reservedate < NOW() )';
2438 my $dbh = C4::Context->dbh();
2439 my @row = $dbh->selectrow_array(
2440 $sql,
2441 undef,
2442 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2445 return @row ? $row[0]+1 : 1;
2448 =head2 IsItemOnHoldAndFound
2450 my $bool = IsItemFoundHold( $itemnumber );
2452 Returns true if the item is currently on hold
2453 and that hold has a non-null found status ( W, T, etc. )
2455 =cut
2457 sub IsItemOnHoldAndFound {
2458 my ($itemnumber) = @_;
2460 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2462 my $found = $rs->count(
2464 itemnumber => $itemnumber,
2465 found => { '!=' => undef }
2469 return $found;
2472 =head2 GetMaxPatronHoldsForRecord
2474 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2476 For multiple holds on a given record for a given patron, the max
2477 number of record level holds that a patron can be placed is the highest
2478 value of the holds_per_record rule for each item if the record for that
2479 patron. This subroutine finds and returns the highest holds_per_record
2480 rule value for a given patron id and record id.
2482 =cut
2484 sub GetMaxPatronHoldsForRecord {
2485 my ( $borrowernumber, $biblionumber ) = @_;
2487 my $patron = Koha::Patrons->find($borrowernumber);
2488 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2490 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2492 my $categorycode = $patron->categorycode;
2493 my $branchcode;
2494 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2496 my $max = 0;
2497 foreach my $item (@items) {
2498 my $itemtype = $item->effective_itemtype();
2500 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2502 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2503 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2504 $max = $holds_per_record if $holds_per_record > $max;
2507 return $max;
2510 =head2 GetHoldRule
2512 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2514 Returns the matching hold related issuingrule fields for a given
2515 patron category, itemtype, and library.
2517 =cut
2519 sub GetHoldRule {
2520 my ( $categorycode, $itemtype, $branchcode ) = @_;
2522 my $dbh = C4::Context->dbh;
2524 my $sth = $dbh->prepare(
2526 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record
2527 FROM issuingrules
2528 WHERE (categorycode in (?,'*') )
2529 AND (itemtype IN (?,'*'))
2530 AND (branchcode IN (?,'*'))
2531 ORDER BY categorycode DESC,
2532 itemtype DESC,
2533 branchcode DESC
2537 $sth->execute( $categorycode, $itemtype, $branchcode );
2539 return $sth->fetchrow_hashref();
2542 =head1 AUTHOR
2544 Koha Development Team <http://koha-community.org/>
2546 =cut