3 # Copyright 2000-2002 Katipo Communications
4 # 2006 SAN Ouest Provence
5 # 2007-2010 BibLibre Paul POULAIN
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>.
25 #use warnings; FIXME - Bug 2505
33 # for _koha_notify_reserve
34 use C4
::Members
::Messaging
;
47 use Koha
::IssuingRules
;
51 use Koha
::CirculationRules
;
53 use List
::MoreUtils
qw( firstidx any );
57 use vars
qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
61 C4::Reserves - Koha functions for dealing with reservation.
69 This modules provides somes functions to deal with reservations.
71 Reserves are stored in reserves table.
72 The following columns contains important values :
73 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
74 =0 : then the reserve is being dealed
75 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
76 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
77 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
78 F(inished) : the reserve has been completed, and is done
79 - itemnumber : empty : the reserve is still unaffected to an item
80 filled: the reserve is attached to an item
81 The complete workflow is :
82 ==== 1st use case ====
83 patron request a document, 1st available : P >0, F=NULL, I=NULL
84 a library having it run "transfertodo", and clic on the list
85 if there is no transfer to do, the reserve waiting
86 patron can pick it up P =0, F=W, I=filled
87 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
88 The pickup library receive the book, it check in P =0, F=W, I=filled
89 The patron borrow the book P =0, F=F, I=filled
91 ==== 2nd use case ====
92 patron requests a document, a given item,
93 If pickup is holding branch P =0, F=W, I=filled
94 If transfer needed, write in branchtransfer P =0, F=T, I=filled
95 The pickup library receive the book, it checks it in P =0, F=W, I=filled
96 The patron borrow the book P =0, F=F, I=filled
117 &ModReserveMinusPriority
123 &CanReserveBeCanceledFromOpac
124 &CancelExpiredReserves
126 &AutoUnsuspendReserves
128 &IsAvailableForItemLevelRequest
131 &ToggleLowestPriority
137 &GetReservesControlBranch
141 GetMaxPatronHoldsForRecord
143 @EXPORT_OK = qw( MergeHolds );
148 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
150 Adds reserve and generates HOLDPLACED message.
152 The following tables are available witin the HOLDPLACED message:
165 $branch, $borrowernumber, $biblionumber, $bibitems,
166 $priority, $resdate, $expdate, $notes,
167 $title, $checkitem, $found, $itemtype
170 $resdate = output_pref
( { str
=> dt_from_string
( $resdate ), dateonly
=> 1, dateformat
=> 'iso' })
171 or output_pref
({ dt
=> dt_from_string
, dateonly
=> 1, dateformat
=> 'iso' });
173 $expdate = output_pref
({ str
=> $expdate, dateonly
=> 1, dateformat
=> 'iso' });
175 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
176 # of the document, we force the value $priority and $found .
177 if ( $checkitem and not C4
::Context
->preference('ReservesNeedReturns') ) {
179 my $item = Koha
::Items
->find( $checkitem ); # FIXME Prevent bad calls
180 if ( $item->holdingbranch eq $branch ) {
185 if ( C4
::Context
->preference('AllowHoldDateInFuture') ) {
187 # Make room in reserves for this before those of a later reserve date
188 $priority = _ShiftPriorityByDateAndPriority
( $biblionumber, $resdate, $priority );
193 # If the reserv had the waiting status, we had the value of the resdate
194 if ( $found eq 'W' ) {
195 $waitingdate = $resdate;
198 # Don't add itemtype limit if specific item is selected
199 $itemtype = undef if $checkitem;
201 # updates take place here
202 my $hold = Koha
::Hold
->new(
204 borrowernumber
=> $borrowernumber,
205 biblionumber
=> $biblionumber,
206 reservedate
=> $resdate,
207 branchcode
=> $branch,
208 priority
=> $priority,
209 reservenotes
=> $notes,
210 itemnumber
=> $checkitem,
212 waitingdate
=> $waitingdate,
213 expirationdate
=> $expdate,
214 itemtype
=> $itemtype,
217 $hold->set_waiting() if $found eq 'W';
219 logaction
( 'HOLDS', 'CREATE', $hold->id, Dumper
($hold->unblessed) )
220 if C4
::Context
->preference('HoldsLog');
222 my $reserve_id = $hold->id();
224 # add a reserve fee if needed
225 if ( C4
::Context
->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
226 my $reserve_fee = GetReserveFee
( $borrowernumber, $biblionumber );
227 ChargeReserveFee
( $borrowernumber, $reserve_fee, $title );
230 _FixPriority
({ biblionumber
=> $biblionumber});
232 # Send e-mail to librarian if syspref is active
233 if(C4
::Context
->preference("emailLibrarianWhenHoldIsPlaced")){
234 my $patron = Koha
::Patrons
->find( $borrowernumber );
235 my $library = $patron->library;
236 if ( my $letter = C4
::Letters
::GetPreparedLetter
(
237 module
=> 'reserves',
238 letter_code
=> 'HOLDPLACED',
239 branchcode
=> $branch,
240 lang
=> $patron->lang,
242 'branches' => $library->unblessed,
243 'borrowers' => $patron->unblessed,
244 'biblio' => $biblionumber,
245 'biblioitems' => $biblionumber,
246 'items' => $checkitem,
247 'reserves' => $hold->unblessed,
251 my $admin_email_address = $library->branchemail || C4
::Context
->preference('KohaAdminEmailAddress');
253 C4
::Letters
::EnqueueLetter
(
255 borrowernumber
=> $borrowernumber,
256 message_transport_type
=> 'email',
257 from_address
=> $admin_email_address,
258 to_address
=> $admin_email_address,
267 =head2 CanBookBeReserved
269 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode)
270 if ($canReserve eq 'OK') { #We can reserve this Item! }
272 See CanItemBeReserved() for possible return values.
276 sub CanBookBeReserved
{
277 my ($borrowernumber, $biblionumber, $pickup_branchcode) = @_;
279 my @itemnumbers = Koha
::Items
->search({ biblionumber
=> $biblionumber})->get_column("itemnumber");
280 #get items linked via host records
281 my @hostitems = get_hostitemnumbers_of
($biblionumber);
283 push (@itemnumbers, @hostitems);
287 foreach my $itemnumber (@itemnumbers) {
288 $canReserve = CanItemBeReserved
( $borrowernumber, $itemnumber, $pickup_branchcode );
289 return { status
=> 'OK' } if $canReserve->{status
} eq 'OK';
294 =head2 CanItemBeReserved
296 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode)
297 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
299 @RETURNS { status => OK }, if the Item can be reserved.
300 { status => ageRestricted }, if the Item is age restricted for this borrower.
301 { status => damaged }, if the Item is damaged.
302 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
303 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
304 { status => notReservable }, if holds on this item are not allowed
305 { status => libraryNotFound }, if given branchcode is not an existing library
306 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
307 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
311 sub CanItemBeReserved
{
312 my ( $borrowernumber, $itemnumber, $pickup_branchcode ) = @_;
314 my $dbh = C4
::Context
->dbh;
315 my $ruleitemtype; # itemtype of the matching issuing rule
316 my $allowedreserves = 0; # Total number of holds allowed across all records
317 my $holds_per_record = 1; # Total number of holds allowed for this one given record
318 my $holds_per_day; # Default to unlimited
320 # we retrieve borrowers and items informations #
321 # item->{itype} will come for biblioitems if necessery
322 my $item = C4
::Items
::GetItem
($itemnumber);
323 my $biblio = Koha
::Biblios
->find( $item->{biblionumber
} );
324 my $patron = Koha
::Patrons
->find( $borrowernumber );
325 my $borrower = $patron->unblessed;
327 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
328 return { status
=>'damaged' }
329 if ( $item->{damaged
}
330 && !C4
::Context
->preference('AllowHoldsOnDamagedItems') );
332 # Check for the age restriction
333 my ( $ageRestriction, $daysToAgeRestriction ) =
334 C4
::Circulation
::GetAgeRestriction
( $biblio->biblioitem->agerestriction, $borrower );
335 return { status
=> 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
337 # Check that the patron doesn't have an item level hold on this item already
338 return { status
=>'itemAlreadyOnHold' }
339 if Koha
::Holds
->search( { borrowernumber
=> $borrowernumber, itemnumber
=> $itemnumber } )->count();
341 my $controlbranch = C4
::Context
->preference('ReservesControlBranch');
344 SELECT count(*) AS count
346 LEFT JOIN items USING (itemnumber)
347 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
348 LEFT JOIN borrowers USING (borrowernumber)
349 WHERE borrowernumber = ?
353 my $branchfield = "reserves.branchcode";
355 if ( $controlbranch eq "ItemHomeLibrary" ) {
356 $branchfield = "items.homebranch";
357 $branchcode = $item->{homebranch
};
359 elsif ( $controlbranch eq "PatronLibrary" ) {
360 $branchfield = "borrowers.branchcode";
361 $branchcode = $borrower->{branchcode
};
365 if ( my $rights = GetHoldRule
( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
366 $ruleitemtype = $rights->{itemtype
};
367 $allowedreserves = $rights->{reservesallowed
};
368 $holds_per_record = $rights->{holds_per_record
};
369 $holds_per_day = $rights->{holds_per_day
};
375 $item = Koha
::Items
->find( $itemnumber );
376 my $holds = Koha
::Holds
->search(
378 borrowernumber
=> $borrowernumber,
379 biblionumber
=> $item->biblionumber,
380 found
=> undef, # Found holds don't count against a patron's holds limit
383 if ( $holds->count() >= $holds_per_record ) {
384 return { status
=> "tooManyHoldsForThisRecord", limit
=> $holds_per_record };
387 my $today_holds = Koha
::Holds
->search({
388 borrowernumber
=> $borrowernumber,
389 reservedate
=> dt_from_string
->date
392 if ( defined $holds_per_day &&
393 ( ( $holds_per_day > 0 && $today_holds->count() >= $holds_per_day )
394 or ( $holds_per_day == 0 ) )
396 return { status
=> 'tooManyReservesToday', limit
=> $holds_per_day };
401 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
403 # If using item-level itypes, fall back to the record
404 # level itemtype if the hold has no associated item
406 C4
::Context
->preference('item-level_itypes')
407 ?
" AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
408 : " AND biblioitems.itemtype = ?"
409 if ( $ruleitemtype ne "*" );
411 my $sthcount = $dbh->prepare($querycount);
413 if ( $ruleitemtype eq "*" ) {
414 $sthcount->execute( $borrowernumber, $branchcode );
417 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
420 my $reservecount = "0";
421 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
422 $reservecount = $rowcount->{count
};
425 # we check if it's ok or not
426 if ( $reservecount >= $allowedreserves ) {
427 return { status
=> 'tooManyReserves', limit
=> $allowedreserves };
430 # Now we need to check hold limits by patron category
431 my $rule = Koha
::CirculationRules
->get_effective_rule(
433 categorycode
=> $borrower->{categorycode
},
434 branchcode
=> $branchcode,
435 rule_name
=> 'max_holds',
438 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
439 my $total_holds_count = Koha
::Holds
->search(
441 borrowernumber
=> $borrower->{borrowernumber
}
445 return { status
=> 'tooManyReserves', limit
=> $rule->rule_value} if $total_holds_count >= $rule->rule_value;
448 my $circ_control_branch =
449 C4
::Circulation
::_GetCircControlBranch
( $item->unblessed(), $borrower );
451 C4
::Circulation
::GetBranchItemRule
( $circ_control_branch, $item->itype );
453 if ( $branchitemrule->{holdallowed
} == 0 ) {
454 return { status
=> 'notReservable' };
457 if ( $branchitemrule->{holdallowed
} == 1
458 && $borrower->{branchcode
} ne $item->homebranch )
460 return { status
=> 'cannotReserveFromOtherBranches' };
463 # If reservecount is ok, we check item branch if IndependentBranches is ON
464 # and canreservefromotherbranches is OFF
465 if ( C4
::Context
->preference('IndependentBranches')
466 and !C4
::Context
->preference('canreservefromotherbranches') )
468 my $itembranch = $item->homebranch;
469 if ( $itembranch ne $borrower->{branchcode
} ) {
470 return { status
=> 'cannotReserveFromOtherBranches' };
474 if ($pickup_branchcode) {
475 my $destination = Koha
::Libraries
->find({
476 branchcode
=> $pickup_branchcode,
479 unless ($destination) {
480 return { status
=> 'libraryNotFound' };
482 unless ($destination->pickup_location) {
483 return { status
=> 'libraryNotPickupLocation' };
485 unless ($item->can_be_transferred({ to
=> $destination })) {
486 return 'cannotBeTransferred';
490 return { status
=> 'OK' };
493 =head2 CanReserveBeCanceledFromOpac
495 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
497 returns 1 if reserve can be cancelled by user from OPAC.
498 First check if reserve belongs to user, next checks if reserve is not in
499 transfer or waiting status
503 sub CanReserveBeCanceledFromOpac
{
504 my ($reserve_id, $borrowernumber) = @_;
506 return unless $reserve_id and $borrowernumber;
507 my $reserve = Koha
::Holds
->find($reserve_id);
509 return 0 unless $reserve->borrowernumber == $borrowernumber;
510 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
516 =head2 GetOtherReserves
518 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
520 Check queued list of this document and check if this document must be transferred
524 sub GetOtherReserves
{
525 my ($itemnumber) = @_;
528 my ( undef, $checkreserves, undef ) = CheckReserves
($itemnumber);
529 if ($checkreserves) {
530 my $iteminfo = GetItem
($itemnumber);
531 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
532 $messages->{'transfert'} = $checkreserves->{'branchcode'};
533 #minus priorities of others reservs
534 ModReserveMinusPriority
(
536 $checkreserves->{'reserve_id'},
539 #launch the subroutine dotransfer
540 C4
::Items
::ModItemTransfer
(
542 $iteminfo->{'holdingbranch'},
543 $checkreserves->{'branchcode'}
548 #step 2b : case of a reservation on the same branch, set the waiting status
550 $messages->{'waiting'} = 1;
551 ModReserveMinusPriority
(
553 $checkreserves->{'reserve_id'},
555 ModReserveStatus
($itemnumber,'W');
558 $nextreservinfo = $checkreserves->{'borrowernumber'};
561 return ( $messages, $nextreservinfo );
564 =head2 ChargeReserveFee
566 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
568 Charge the fee for a reserve (if $fee > 0)
572 sub ChargeReserveFee
{
573 my ( $borrowernumber, $fee, $title ) = @_;
574 return if !$fee || $fee==0; # the last test is needed to include 0.00
576 INSERT INTO accountlines
( borrowernumber
, accountno
, date
, amount
, description
, accounttype
, amountoutstanding
) VALUES
(?
, ?
, NOW
(), ?
, ?
, 'Res', ?
)
578 my $dbh = C4
::Context
->dbh;
579 my $nextacctno = C4
::Accounts
::getnextacctno
( $borrowernumber );
580 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
585 $fee = GetReserveFee( $borrowernumber, $biblionumber );
587 Calculate the fee for a reserve (if applicable).
592 my ( $borrowernumber, $biblionumber ) = @_;
594 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers
.categorycode
= categories
.categorycode WHERE borrowernumber
= ?
597 SELECT COUNT
(*) FROM items
598 LEFT JOIN issues USING
(itemnumber
)
599 WHERE items
.biblionumber
=? AND issues
.issue_id IS NULL
602 SELECT COUNT
(*) FROM reserves WHERE biblionumber
=? AND borrowernumber
<>?
605 my $dbh = C4
::Context
->dbh;
606 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
607 my $hold_fee_mode = C4
::Context
->preference('HoldFeeMode') || 'not_always';
608 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
609 # This is a reconstruction of the old code:
610 # Compare number of items with items issued, and optionally check holds
611 # If not all items are issued and there are no holds: charge no fee
612 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
613 my ( $notissued, $reserved );
614 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
617 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
618 ( $biblionumber, $borrowernumber ) );
619 $fee = 0 if $reserved == 0;
625 =head2 GetReserveStatus
627 $reservestatus = GetReserveStatus($itemnumber);
629 Takes an itemnumber and returns the status of the reserve placed on it.
630 If several reserves exist, the reserve with the lower priority is given.
634 ## FIXME: I don't think this does what it thinks it does.
635 ## It only ever checks the first reserve result, even though
636 ## multiple reserves for that bib can have the itemnumber set
637 ## the sub is only used once in the codebase.
638 sub GetReserveStatus
{
639 my ($itemnumber) = @_;
641 my $dbh = C4
::Context
->dbh;
643 my ($sth, $found, $priority);
645 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
646 $sth->execute($itemnumber);
647 ($found, $priority) = $sth->fetchrow_array;
651 return 'Waiting' if $found eq 'W' and $priority == 0;
652 return 'Finished' if $found eq 'F';
655 return 'Reserved' if $priority > 0;
657 return ''; # empty string here will remove need for checking undef, or less log lines
662 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
663 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
664 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
666 Find a book in the reserves.
668 C<$itemnumber> is the book's item number.
669 C<$lookahead> is the number of days to look in advance for future reserves.
671 As I understand it, C<&CheckReserves> looks for the given item in the
672 reserves. If it is found, that's a match, and C<$status> is set to
675 Otherwise, it finds the most important item in the reserves with the
676 same biblio number as this book (I'm not clear on this) and returns it
677 with C<$status> set to C<Reserved>.
679 C<&CheckReserves> returns a two-element list:
681 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
683 C<$reserve> is the reserve item that matched. It is a
684 reference-to-hash whose keys are mostly the fields of the reserves
685 table in the Koha database.
690 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
691 my $dbh = C4
::Context
->dbh;
694 if (C4
::Context
->preference('item-level_itypes')){
696 SELECT items.biblionumber,
697 items.biblioitemnumber,
698 itemtypes.notforloan,
699 items.notforloan AS itemnotforloan,
705 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
706 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
711 SELECT items.biblionumber,
712 items.biblioitemnumber,
713 itemtypes.notforloan,
714 items.notforloan AS itemnotforloan,
720 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
721 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
726 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
727 $sth->execute($item);
730 $sth = $dbh->prepare("$select WHERE barcode = ?");
731 $sth->execute($barcode);
733 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
734 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
736 return if ( $damaged && !C4
::Context
->preference('AllowHoldsOnDamagedItems') );
738 return unless $itemnumber; # bail if we got nothing.
740 # if item is not for loan it cannot be reserved either.....
741 # except where items.notforloan < 0 : This indicates the item is holdable.
742 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
744 # Find this item in the reserves
745 my @reserves = _Findgroupreserve
( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
747 # $priority and $highest are used to find the most important item
748 # in the list returned by &_Findgroupreserve. (The lower $priority,
749 # the more important the item.)
750 # $highest is the most important item we've seen so far.
752 if (scalar @reserves) {
753 my $LocalHoldsPriority = C4
::Context
->preference('LocalHoldsPriority');
754 my $LocalHoldsPriorityPatronControl = C4
::Context
->preference('LocalHoldsPriorityPatronControl');
755 my $LocalHoldsPriorityItemControl = C4
::Context
->preference('LocalHoldsPriorityItemControl');
757 my $priority = 10000000;
758 foreach my $res (@reserves) {
759 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
760 if ($res->{'found'} eq 'W') {
761 return ( "Waiting", $res, \
@reserves ); # Found it, it is waiting
763 return ( "Reserved", $res, \
@reserves ); # Found determinated hold, e. g. the tranferred one
768 my $local_hold_match;
770 if ($LocalHoldsPriority) {
771 $patron = Koha
::Patrons
->find( $res->{borrowernumber
} );
772 $iteminfo = C4
::Items
::GetItem
($itemnumber);
774 my $local_holds_priority_item_branchcode =
775 $iteminfo->{$LocalHoldsPriorityItemControl};
776 my $local_holds_priority_patron_branchcode =
777 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
779 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
780 ?
$patron->branchcode
783 $local_holds_priority_item_branchcode eq
784 $local_holds_priority_patron_branchcode;
787 # See if this item is more important than what we've got so far
788 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
789 $iteminfo ||= C4
::Items
::GetItem
($itemnumber);
790 next if $res->{itemtype
} && $res->{itemtype
} ne _get_itype
( $iteminfo );
791 $patron ||= Koha
::Patrons
->find( $res->{borrowernumber
} );
792 my $branch = GetReservesControlBranch
( $iteminfo, $patron->unblessed );
793 my $branchitemrule = C4
::Circulation
::GetBranchItemRule
($branch,$iteminfo->{'itype'});
794 next if ($branchitemrule->{'holdallowed'} == 0);
795 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
796 next if ( ($branchitemrule->{hold_fulfillment_policy
} ne 'any') && ($res->{branchcode
} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy
} }) );
797 $priority = $res->{'priority'};
799 last if $local_hold_match;
805 # If we get this far, then no exact match was found.
806 # We return the most important (i.e. next) reservation.
808 $highest->{'itemnumber'} = $item;
809 return ( "Reserved", $highest, \
@reserves );
815 =head2 CancelExpiredReserves
817 CancelExpiredReserves();
819 Cancels all reserves with an expiration date from before today.
823 sub CancelExpiredReserves
{
824 my $today = dt_from_string
();
825 my $cancel_on_holidays = C4
::Context
->preference('ExpireReservesOnHolidays');
826 my $expireWaiting = C4
::Context
->preference('ExpireReservesMaxPickUpDelay');
828 my $dtf = Koha
::Database
->new->schema->storage->datetime_parser;
829 my $params = { expirationdate
=> { '<', $dtf->format_date($today) } };
830 $params->{found
} = undef unless $expireWaiting;
832 # FIXME To move to Koha::Holds->search_expired (?)
833 my $holds = Koha
::Holds
->search( $params );
835 while ( my $hold = $holds->next ) {
836 my $calendar = Koha
::Calendar
->new( branchcode
=> $hold->branchcode );
838 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
840 my $cancel_params = {};
841 if ( $hold->found eq 'W' ) {
842 $cancel_params->{charge_cancel_fee
} = 1;
844 $hold->cancel( $cancel_params );
848 =head2 AutoUnsuspendReserves
850 AutoUnsuspendReserves();
852 Unsuspends all suspended reserves with a suspend_until date from before today.
856 sub AutoUnsuspendReserves
{
857 my $today = dt_from_string
();
859 my @holds = Koha
::Holds
->search( { suspend_until
=> { '<=' => $today->ymd() } } );
861 map { $_->resume() } @holds;
866 ModReserve({ rank => $rank,
867 reserve_id => $reserve_id,
868 branchcode => $branchcode
869 [, itemnumber => $itemnumber ]
870 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
873 Change a hold request's priority or cancel it.
875 C<$rank> specifies the effect of the change. If C<$rank>
876 is 'W' or 'n', nothing happens. This corresponds to leaving a
877 request alone when changing its priority in the holds queue
880 If C<$rank> is 'del', the hold request is cancelled.
882 If C<$rank> is an integer greater than zero, the priority of
883 the request is set to that value. Since priority != 0 means
884 that the item is not waiting on the hold shelf, setting the
885 priority to a non-zero value also sets the request's found
886 status and waiting date to NULL.
888 The optional C<$itemnumber> parameter is used only when
889 C<$rank> is a non-zero integer; if supplied, the itemnumber
890 of the hold request is set accordingly; if omitted, the itemnumber
893 B<FIXME:> Note that the forgoing can have the effect of causing
894 item-level hold requests to turn into title-level requests. This
895 will be fixed once reserves has separate columns for requested
896 itemnumber and supplying itemnumber.
903 my $rank = $params->{'rank'};
904 my $reserve_id = $params->{'reserve_id'};
905 my $branchcode = $params->{'branchcode'};
906 my $itemnumber = $params->{'itemnumber'};
907 my $suspend_until = $params->{'suspend_until'};
908 my $borrowernumber = $params->{'borrowernumber'};
909 my $biblionumber = $params->{'biblionumber'};
911 return if $rank eq "W";
912 return if $rank eq "n";
914 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
917 unless ( $reserve_id ) {
918 my $holds = Koha
::Holds
->search({ biblionumber
=> $biblionumber, borrowernumber
=> $borrowernumber, itemnumber
=> $itemnumber });
919 return unless $holds->count; # FIXME Should raise an exception
920 $hold = $holds->next;
921 $reserve_id = $hold->reserve_id;
924 $hold ||= Koha
::Holds
->find($reserve_id);
926 if ( $rank eq "del" ) {
929 elsif ($rank =~ /^\d+/ and $rank > 0) {
930 logaction
( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper
($hold->unblessed) )
931 if C4
::Context
->preference('HoldsLog');
936 branchcode
=> $branchcode,
937 itemnumber
=> $itemnumber,
943 if ( defined( $suspend_until ) ) {
944 if ( $suspend_until ) {
945 $suspend_until = eval { dt_from_string
( $suspend_until ) };
946 $hold->suspend_hold( $suspend_until );
948 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
949 # If the hold is not suspended, this does nothing.
950 $hold->set( { suspend_until
=> undef } )->store();
954 _FixPriority
({ reserve_id
=> $reserve_id, rank
=>$rank });
958 =head2 ModReserveFill
960 &ModReserveFill($reserve);
962 Fill a reserve. If I understand this correctly, this means that the
963 reserved book has been found and given to the patron who reserved it.
965 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
966 whose keys are fields from the reserves table in the Koha database.
972 my $reserve_id = $res->{'reserve_id'};
974 my $hold = Koha
::Holds
->find($reserve_id);
976 # get the priority on this record....
977 my $priority = $hold->priority;
979 # update the hold statuses, no need to store it though, we will be deleting it anyway
987 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
988 Koha
::Old
::Hold
->new( $hold->unblessed() )->store();
992 if ( C4
::Context
->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
993 my $reserve_fee = GetReserveFee
( $hold->borrowernumber, $hold->biblionumber );
994 ChargeReserveFee
( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
997 # now fix the priority on the others (if the priority wasn't
998 # already sorted!)....
999 unless ( $priority == 0 ) {
1000 _FixPriority
( { reserve_id
=> $reserve_id, biblionumber
=> $hold->biblionumber } );
1004 =head2 ModReserveStatus
1006 &ModReserveStatus($itemnumber, $newstatus);
1008 Update the reserve status for the active (priority=0) reserve.
1010 $itemnumber is the itemnumber the reserve is on
1012 $newstatus is the new status.
1016 sub ModReserveStatus
{
1018 #first : check if we have a reservation for this item .
1019 my ($itemnumber, $newstatus) = @_;
1020 my $dbh = C4
::Context
->dbh;
1022 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1023 my $sth_set = $dbh->prepare($query);
1024 $sth_set->execute( $newstatus, $itemnumber );
1026 if ( C4
::Context
->preference("ReturnToShelvingCart") && $newstatus ) {
1027 CartToShelf
( $itemnumber );
1031 =head2 ModReserveAffect
1033 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1035 This function affect an item and a status for a given reserve, either fetched directly
1036 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1037 is given, only first reserve returned is affected, which is ok for anything but
1040 if $transferToDo is not set, then the status is set to "Waiting" as well.
1041 otherwise, a transfer is on the way, and the end of the transfer will
1042 take care of the waiting status
1046 sub ModReserveAffect
{
1047 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1048 my $dbh = C4
::Context
->dbh;
1050 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1051 # attached to $itemnumber
1052 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1053 $sth->execute($itemnumber);
1054 my ($biblionumber) = $sth->fetchrow;
1056 # get request - need to find out if item is already
1057 # waiting in order to not send duplicate hold filled notifications
1060 # Find hold by id if we have it
1061 $hold = Koha
::Holds
->find( $reserve_id ) if $reserve_id;
1062 # Find item level hold for this item if there is one
1063 $hold ||= Koha
::Holds
->search( { borrowernumber
=> $borrowernumber, itemnumber
=> $itemnumber } )->next();
1064 # Find record level hold if there is no item level hold
1065 $hold ||= Koha
::Holds
->search( { borrowernumber
=> $borrowernumber, biblionumber
=> $biblionumber } )->next();
1067 return unless $hold;
1069 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1071 $hold->itemnumber($itemnumber);
1072 $hold->set_waiting($transferToDo);
1074 _koha_notify_reserve
( $hold->reserve_id )
1075 if ( !$transferToDo && !$already_on_shelf );
1077 _FixPriority
( { biblionumber
=> $biblionumber } );
1079 if ( C4
::Context
->preference("ReturnToShelvingCart") ) {
1080 CartToShelf
($itemnumber);
1086 =head2 ModReserveCancelAll
1088 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1090 function to cancel reserv,check other reserves, and transfer document if it's necessary
1094 sub ModReserveCancelAll
{
1097 my ( $itemnumber, $borrowernumber ) = @_;
1099 #step 1 : cancel the reservation
1100 my $holds = Koha
::Holds
->search({ itemnumber
=> $itemnumber, borrowernumber
=> $borrowernumber });
1101 return unless $holds->count;
1102 $holds->next->cancel;
1104 #step 2 launch the subroutine of the others reserves
1105 ( $messages, $nextreservinfo ) = GetOtherReserves
($itemnumber);
1107 return ( $messages, $nextreservinfo );
1110 =head2 ModReserveMinusPriority
1112 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1114 Reduce the values of queued list
1118 sub ModReserveMinusPriority
{
1119 my ( $itemnumber, $reserve_id ) = @_;
1121 #first step update the value of the first person on reserv
1122 my $dbh = C4
::Context
->dbh;
1125 SET priority = 0 , itemnumber = ?
1126 WHERE reserve_id = ?
1128 my $sth_upd = $dbh->prepare($query);
1129 $sth_upd->execute( $itemnumber, $reserve_id );
1130 # second step update all others reserves
1131 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> '0' });
1134 =head2 IsAvailableForItemLevelRequest
1136 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1138 Checks whether a given item record is available for an
1139 item-level hold request. An item is available if
1141 * it is not lost AND
1142 * it is not damaged AND
1143 * it is not withdrawn AND
1144 * a waiting or in transit reserve is placed on
1145 * does not have a not for loan value > 0
1147 Need to check the issuingrules onshelfholds column,
1148 if this is set items on the shelf can be placed on hold
1150 Note that IsAvailableForItemLevelRequest() does not
1151 check if the staff operator is authorized to place
1152 a request on the item - in particular,
1153 this routine does not check IndependentBranches
1154 and canreservefromotherbranches.
1158 sub IsAvailableForItemLevelRequest
{
1160 my $borrower = shift;
1162 my $dbh = C4
::Context
->dbh;
1163 # must check the notforloan setting of the itemtype
1164 # FIXME - a lot of places in the code do this
1165 # or something similar - need to be
1167 my $patron = Koha
::Patrons
->find( $borrower->{borrowernumber
} );
1168 my $item_object = Koha
::Items
->find( $item->{itemnumber
} );
1169 my $itemtype = $item_object->effective_itemtype;
1170 my $notforloan_per_itemtype
1171 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1175 $notforloan_per_itemtype ||
1176 $item->{itemlost
} ||
1177 $item->{notforloan
} > 0 ||
1178 $item->{withdrawn
} ||
1179 ($item->{damaged
} && !C4
::Context
->preference('AllowHoldsOnDamagedItems'));
1181 my $on_shelf_holds = Koha
::IssuingRules
->get_onshelfholds_policy( { item
=> $item_object, patron
=> $patron } );
1183 if ( $on_shelf_holds == 1 ) {
1185 } elsif ( $on_shelf_holds == 2 ) {
1187 Koha
::Items
->search( { biblionumber
=> $item->{biblionumber
} } );
1189 my $any_available = 0;
1191 foreach my $i (@items) {
1193 my $circ_control_branch = C4
::Circulation
::_GetCircControlBranch
( $i->unblessed(), $borrower );
1194 my $branchitemrule = C4
::Circulation
::GetBranchItemRule
( $circ_control_branch, $i->itype );
1198 || $i->notforloan > 0
1201 || IsItemOnHoldAndFound
( $i->id )
1203 && !C4
::Context
->preference('AllowHoldsOnDamagedItems') )
1204 || Koha
::ItemTypes
->find( $i->effective_itemtype() )->notforloan
1205 || $branchitemrule->{holdallowed
} == 1 && $borrower->{branchcode
} ne $i->homebranch;
1208 return $any_available ?
0 : 1;
1209 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1210 return $item->{onloan
} || IsItemOnHoldAndFound
( $item->{itemnumber
} );
1218 if (C4
::Context
->preference('item-level_itypes')) {
1219 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1220 # When GetItem is fixed, we can remove this
1221 $itype = $item->{itype
};
1224 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1225 # So if we already have a biblioitems join when calling this function,
1226 # we don't need to access the database again
1227 $itype = $item->{itemtype
};
1230 my $dbh = C4
::Context
->dbh;
1231 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1232 my $sth = $dbh->prepare($query);
1233 $sth->execute($item->{biblioitemnumber
});
1234 if (my $data = $sth->fetchrow_hashref()){
1235 $itype = $data->{itemtype
};
1241 =head2 AlterPriority
1243 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1245 This function changes a reserve's priority up, down, to the top, or to the bottom.
1246 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1251 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1253 my $hold = Koha
::Holds
->find( $reserve_id );
1254 return unless $hold;
1256 if ( $hold->cancellationdate ) {
1257 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1261 if ( $where eq 'up' ) {
1262 return unless $prev_priority;
1263 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> $prev_priority })
1264 } elsif ( $where eq 'down' ) {
1265 return unless $next_priority;
1266 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> $next_priority })
1267 } elsif ( $where eq 'top' ) {
1268 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> $first_priority })
1269 } elsif ( $where eq 'bottom' ) {
1270 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> $last_priority });
1273 # FIXME Should return the new priority
1276 =head2 ToggleLowestPriority
1278 ToggleLowestPriority( $borrowernumber, $biblionumber );
1280 This function sets the lowestPriority field to true if is false, and false if it is true.
1284 sub ToggleLowestPriority
{
1285 my ( $reserve_id ) = @_;
1287 my $dbh = C4
::Context
->dbh;
1289 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1290 $sth->execute( $reserve_id );
1292 _FixPriority
({ reserve_id
=> $reserve_id, rank
=> '999999' });
1295 =head2 ToggleSuspend
1297 ToggleSuspend( $reserve_id );
1299 This function sets the suspend field to true if is false, and false if it is true.
1300 If the reserve is currently suspended with a suspend_until date, that date will
1301 be cleared when it is unsuspended.
1306 my ( $reserve_id, $suspend_until ) = @_;
1308 $suspend_until = dt_from_string
($suspend_until) if ($suspend_until);
1310 my $hold = Koha
::Holds
->find( $reserve_id );
1312 if ( $hold->is_suspended ) {
1315 $hold->suspend_hold( $suspend_until );
1322 borrowernumber => $borrowernumber,
1323 [ biblionumber => $biblionumber, ]
1324 [ suspend_until => $suspend_until, ]
1325 [ suspend => $suspend ]
1328 This function accepts a set of hash keys as its parameters.
1329 It requires either borrowernumber or biblionumber, or both.
1331 suspend_until is wholly optional.
1338 my $borrowernumber = $params{'borrowernumber'} || undef;
1339 my $biblionumber = $params{'biblionumber'} || undef;
1340 my $suspend_until = $params{'suspend_until'} || undef;
1341 my $suspend = defined( $params{'suspend'} ) ?
$params{'suspend'} : 1;
1343 $suspend_until = eval { dt_from_string
($suspend_until) }
1344 if ( defined($suspend_until) );
1346 return unless ( $borrowernumber || $biblionumber );
1349 $params->{found
} = undef;
1350 $params->{borrowernumber
} = $borrowernumber if $borrowernumber;
1351 $params->{biblionumber
} = $biblionumber if $biblionumber;
1353 my @holds = Koha
::Holds
->search($params);
1356 map { $_->suspend_hold($suspend_until) } @holds;
1359 map { $_->resume() } @holds;
1367 reserve_id => $reserve_id,
1369 [ignoreSetLowestRank => $ignoreSetLowestRank]
1374 _FixPriority({ biblionumber => $biblionumber});
1376 This routine adjusts the priority of a hold request and holds
1379 In the first form, where a reserve_id is passed, the priority of the
1380 hold is set to supplied rank, and other holds for that bib are adjusted
1381 accordingly. If the rank is "del", the hold is cancelled. If no rank
1382 is supplied, all of the holds on that bib have their priority adjusted
1383 as if the second form had been used.
1385 In the second form, where a biblionumber is passed, the holds on that
1386 bib (that are not captured) are sorted in order of increasing priority,
1387 then have reserves.priority set so that the first non-captured hold
1388 has its priority set to 1, the second non-captured hold has its priority
1389 set to 2, and so forth.
1391 In both cases, holds that have the lowestPriority flag on are have their
1392 priority adjusted to ensure that they remain at the end of the line.
1394 Note that the ignoreSetLowestRank parameter is meant to be used only
1395 when _FixPriority calls itself.
1400 my ( $params ) = @_;
1401 my $reserve_id = $params->{reserve_id
};
1402 my $rank = $params->{rank
} // '';
1403 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank
};
1404 my $biblionumber = $params->{biblionumber
};
1406 my $dbh = C4
::Context
->dbh;
1409 if ( $reserve_id ) {
1410 $hold = Koha
::Holds
->find( $reserve_id );
1411 return unless $hold;
1414 unless ( $biblionumber ) { # FIXME This is a very weird API
1415 $biblionumber = $hold->biblionumber;
1418 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1421 elsif ( $rank eq "W" || $rank eq "0" ) {
1423 # make sure priority for waiting or in-transit items is 0
1427 WHERE reserve_id = ?
1428 AND found IN ('W', 'T')
1430 my $sth = $dbh->prepare($query);
1431 $sth->execute( $reserve_id );
1437 SELECT reserve_id, borrowernumber, reservedate
1439 WHERE biblionumber = ?
1440 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1441 ORDER BY priority ASC
1443 my $sth = $dbh->prepare($query);
1444 $sth->execute( $biblionumber );
1445 while ( my $line = $sth->fetchrow_hashref ) {
1446 push( @priority, $line );
1449 # To find the matching index
1451 my $key = -1; # to allow for 0 to be a valid result
1452 for ( $i = 0 ; $i < @priority ; $i++ ) {
1453 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1454 $key = $i; # save the index
1459 # if index exists in array then move it to new position
1460 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1461 my $new_rank = $rank -
1462 1; # $new_rank is what you want the new index to be in the array
1463 my $moving_item = splice( @priority, $key, 1 );
1464 splice( @priority, $new_rank, 0, $moving_item );
1467 # now fix the priority on those that are left....
1471 WHERE reserve_id = ?
1473 $sth = $dbh->prepare($query);
1474 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1477 $priority[$j]->{'reserve_id'}
1481 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1484 unless ( $ignoreSetLowestRank ) {
1485 while ( my $res = $sth->fetchrow_hashref() ) {
1487 reserve_id
=> $res->{'reserve_id'},
1489 ignoreSetLowestRank
=> 1
1495 =head2 _Findgroupreserve
1497 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1499 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1500 first match found. If neither, then we look for non-holds-queue based holds.
1501 Lookahead is the number of days to look in advance.
1503 C<&_Findgroupreserve> returns :
1504 C<@results> is an array of references-to-hash whose keys are mostly
1505 fields from the reserves table of the Koha database, plus
1506 C<biblioitemnumber>.
1510 sub _Findgroupreserve
{
1511 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1512 my $dbh = C4
::Context
->dbh;
1514 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1515 # check for exact targeted match
1516 my $item_level_target_query = qq{
1517 SELECT reserves
.biblionumber AS biblionumber
,
1518 reserves
.borrowernumber AS borrowernumber
,
1519 reserves
.reservedate AS reservedate
,
1520 reserves
.branchcode AS branchcode
,
1521 reserves
.cancellationdate AS cancellationdate
,
1522 reserves
.found AS found
,
1523 reserves
.reservenotes AS reservenotes
,
1524 reserves
.priority AS priority
,
1525 reserves
.timestamp AS timestamp
,
1526 biblioitems
.biblioitemnumber AS biblioitemnumber
,
1527 reserves
.itemnumber AS itemnumber
,
1528 reserves
.reserve_id AS reserve_id
,
1529 reserves
.itemtype AS itemtype
1531 JOIN biblioitems USING
(biblionumber
)
1532 JOIN hold_fill_targets USING
(biblionumber
, borrowernumber
, itemnumber
)
1535 AND item_level_request
= 1
1537 AND reservedate
<= DATE_ADD
(NOW
(),INTERVAL ? DAY
)
1541 my $sth = $dbh->prepare($item_level_target_query);
1542 $sth->execute($itemnumber, $lookahead||0);
1544 if ( my $data = $sth->fetchrow_hashref ) {
1545 push( @results, $data )
1546 unless any
{ $data->{borrowernumber
} eq $_ } @
$ignore_borrowers ;
1548 return @results if @results;
1550 # check for title-level targeted match
1551 my $title_level_target_query = qq{
1552 SELECT reserves
.biblionumber AS biblionumber
,
1553 reserves
.borrowernumber AS borrowernumber
,
1554 reserves
.reservedate AS reservedate
,
1555 reserves
.branchcode AS branchcode
,
1556 reserves
.cancellationdate AS cancellationdate
,
1557 reserves
.found AS found
,
1558 reserves
.reservenotes AS reservenotes
,
1559 reserves
.priority AS priority
,
1560 reserves
.timestamp AS timestamp
,
1561 biblioitems
.biblioitemnumber AS biblioitemnumber
,
1562 reserves
.itemnumber AS itemnumber
,
1563 reserves
.reserve_id AS reserve_id
,
1564 reserves
.itemtype AS itemtype
1566 JOIN biblioitems USING
(biblionumber
)
1567 JOIN hold_fill_targets USING
(biblionumber
, borrowernumber
)
1570 AND item_level_request
= 0
1571 AND hold_fill_targets
.itemnumber
= ?
1572 AND reservedate
<= DATE_ADD
(NOW
(),INTERVAL ? DAY
)
1576 $sth = $dbh->prepare($title_level_target_query);
1577 $sth->execute($itemnumber, $lookahead||0);
1579 if ( my $data = $sth->fetchrow_hashref ) {
1580 push( @results, $data )
1581 unless any
{ $data->{borrowernumber
} eq $_ } @
$ignore_borrowers ;
1583 return @results if @results;
1586 SELECT reserves
.biblionumber AS biblionumber
,
1587 reserves
.borrowernumber AS borrowernumber
,
1588 reserves
.reservedate AS reservedate
,
1589 reserves
.waitingdate AS waitingdate
,
1590 reserves
.branchcode AS branchcode
,
1591 reserves
.cancellationdate AS cancellationdate
,
1592 reserves
.found AS found
,
1593 reserves
.reservenotes AS reservenotes
,
1594 reserves
.priority AS priority
,
1595 reserves
.timestamp AS timestamp
,
1596 reserves
.itemnumber AS itemnumber
,
1597 reserves
.reserve_id AS reserve_id
,
1598 reserves
.itemtype AS itemtype
1600 WHERE reserves
.biblionumber
= ?
1601 AND
(reserves
.itemnumber IS NULL OR reserves
.itemnumber
= ?
)
1602 AND reserves
.reservedate
<= DATE_ADD
(NOW
(),INTERVAL ? DAY
)
1606 $sth = $dbh->prepare($query);
1607 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1609 while ( my $data = $sth->fetchrow_hashref ) {
1610 push( @results, $data )
1611 unless any
{ $data->{borrowernumber
} eq $_ } @
$ignore_borrowers ;
1616 =head2 _koha_notify_reserve
1618 _koha_notify_reserve( $hold->reserve_id );
1620 Sends a notification to the patron that their hold has been filled (through
1621 ModReserveAffect, _not_ ModReserveFill)
1623 The letter code for this notice may be found using the following query:
1625 select distinct letter_code
1626 from message_transports
1627 inner join message_attributes using (message_attribute_id)
1628 where message_name = 'Hold_Filled'
1630 This will probably sipmly be 'HOLD', but because it is defined in the database,
1631 it is subject to addition or change.
1633 The following tables are availalbe witin the notice:
1644 sub _koha_notify_reserve
{
1645 my $reserve_id = shift;
1646 my $hold = Koha
::Holds
->find($reserve_id);
1647 my $borrowernumber = $hold->borrowernumber;
1649 my $patron = Koha
::Patrons
->find( $borrowernumber );
1651 # Try to get the borrower's email address
1652 my $to_address = $patron->notice_email_address;
1654 my $messagingprefs = C4
::Members
::Messaging
::GetMessagingPreferences
( {
1655 borrowernumber
=> $borrowernumber,
1656 message_name
=> 'Hold_Filled'
1659 my $library = Koha
::Libraries
->find( $hold->branchcode )->unblessed;
1661 my $admin_email_address = $library->{branchemail
} || C4
::Context
->preference('KohaAdminEmailAddress');
1663 my %letter_params = (
1664 module
=> 'reserves',
1665 branchcode
=> $hold->branchcode,
1666 lang
=> $patron->lang,
1668 'branches' => $library,
1669 'borrowers' => $patron->unblessed,
1670 'biblio' => $hold->biblionumber,
1671 'biblioitems' => $hold->biblionumber,
1672 'reserves' => $hold->unblessed,
1673 'items' => $hold->itemnumber,
1677 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.
1678 my $send_notification = sub {
1679 my ( $mtt, $letter_code ) = (@_);
1680 return unless defined $letter_code;
1681 $letter_params{letter_code
} = $letter_code;
1682 $letter_params{message_transport_type
} = $mtt;
1683 my $letter = C4
::Letters
::GetPreparedLetter
( %letter_params );
1685 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1689 C4
::Letters
::EnqueueLetter
( {
1691 borrowernumber
=> $borrowernumber,
1692 from_address
=> $admin_email_address,
1693 message_transport_type
=> $mtt,
1697 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports
} } ) {
1699 ( $mtt eq 'email' and not $to_address ) # No email address
1700 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1701 or ( $mtt eq 'phone' and C4
::Context
->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1704 &$send_notification($mtt, $letter_code);
1705 $notification_sent++;
1707 #Making sure that a print notification is sent if no other transport types can be utilized.
1708 if (! $notification_sent) {
1709 &$send_notification('print', 'HOLD');
1714 =head2 _ShiftPriorityByDateAndPriority
1716 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1718 This increments the priority of all reserves after the one
1719 with either the lowest date after C<$reservedate>
1720 or the lowest priority after C<$priority>.
1722 It effectively makes room for a new reserve to be inserted with a certain
1723 priority, which is returned.
1725 This is most useful when the reservedate can be set by the user. It allows
1726 the new reserve to be placed before other reserves that have a later
1727 reservedate. Since priority also is set by the form in reserves/request.pl
1728 the sub accounts for that too.
1732 sub _ShiftPriorityByDateAndPriority
{
1733 my ( $biblio, $resdate, $new_priority ) = @_;
1735 my $dbh = C4
::Context
->dbh;
1736 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1737 my $sth = $dbh->prepare( $query );
1738 $sth->execute( $biblio, $resdate, $new_priority );
1739 my $min_priority = $sth->fetchrow;
1740 # if no such matches are found, $new_priority remains as original value
1741 $new_priority = $min_priority if ( $min_priority );
1743 # Shift the priority up by one; works in conjunction with the next SQL statement
1744 $query = "UPDATE reserves
1745 SET priority = priority+1
1746 WHERE biblionumber = ?
1747 AND borrowernumber = ?
1750 my $sth_update = $dbh->prepare( $query );
1752 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1753 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1754 $sth = $dbh->prepare( $query );
1755 $sth->execute( $new_priority, $biblio );
1756 while ( my $row = $sth->fetchrow_hashref ) {
1757 $sth_update->execute( $biblio, $row->{borrowernumber
}, $row->{reservedate
} );
1760 return $new_priority; # so the caller knows what priority they wind up receiving
1765 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1767 Use when checking out an item to handle reserves
1768 If $cancelreserve boolean is set to true, it will remove existing reserve
1773 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1775 my $lookahead = C4
::Context
->preference('ConfirmFutureHolds'); #number of days to look for future holds
1776 my ( $restype, $res, $all_reserves ) = CheckReserves
( $itemnumber, undef, $lookahead );
1779 my $biblionumber = $res->{biblionumber
};
1781 if ($res->{borrowernumber
} == $borrowernumber) {
1782 ModReserveFill
($res);
1786 # The item is reserved by someone else.
1787 # Find this item in the reserves
1790 foreach (@
$all_reserves) {
1791 $_->{'borrowernumber'} == $borrowernumber or next;
1792 $_->{'biblionumber'} == $biblionumber or next;
1799 # The item is reserved by the current patron
1800 ModReserveFill
($borr_res);
1803 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1804 RevertWaitingStatus
({ itemnumber
=> $itemnumber });
1806 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1807 my $hold = Koha
::Holds
->find( $res->{reserve_id
} );
1815 MergeHolds($dbh,$to_biblio, $from_biblio);
1817 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1822 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1823 my $sth = $dbh->prepare(
1824 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1826 $sth->execute($from_biblio);
1827 if ( my $data = $sth->fetchrow_hashref() ) {
1829 # holds exist on old record, if not we don't need to do anything
1830 $sth = $dbh->prepare(
1831 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1832 $sth->execute( $to_biblio, $from_biblio );
1835 # don't reorder those already waiting
1837 $sth = $dbh->prepare(
1838 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1840 my $upd_sth = $dbh->prepare(
1841 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1842 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1844 $sth->execute( $to_biblio, 'W', 'T' );
1846 while ( my $reserve = $sth->fetchrow_hashref() ) {
1848 $priority, $to_biblio,
1849 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1850 $reserve->{'itemnumber'}
1857 =head2 RevertWaitingStatus
1859 RevertWaitingStatus({ itemnumber => $itemnumber });
1861 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1863 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1864 item level hold, even if it was only a bibliolevel hold to
1865 begin with. This is because we can no longer know if a hold
1866 was item-level or bib-level after a hold has been set to
1871 sub RevertWaitingStatus
{
1872 my ( $params ) = @_;
1873 my $itemnumber = $params->{'itemnumber'};
1875 return unless ( $itemnumber );
1877 my $dbh = C4
::Context
->dbh;
1879 ## Get the waiting reserve we want to revert
1881 SELECT * FROM reserves
1882 WHERE itemnumber = ?
1883 AND found IS NOT NULL
1885 my $sth = $dbh->prepare( $query );
1886 $sth->execute( $itemnumber );
1887 my $reserve = $sth->fetchrow_hashref();
1889 ## Increment the priority of all other non-waiting
1890 ## reserves for this bib record
1894 priority = priority + 1
1900 $sth = $dbh->prepare( $query );
1901 $sth->execute( $reserve->{'biblionumber'} );
1903 ## Fix up the currently waiting reserve
1913 $sth = $dbh->prepare( $query );
1914 $sth->execute( $reserve->{'reserve_id'} );
1915 _FixPriority
( { biblionumber
=> $reserve->{biblionumber
} } );
1922 branchcode => $branchcode,
1923 borrowernumber => $borrowernumber,
1924 biblionumber => $biblionumber,
1925 [ itemnumber => $itemnumber, ]
1926 [ barcode => $barcode, ]
1930 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1932 The letter code will be HOLD_SLIP, and the following tables are
1933 available within the slip:
1946 my $branchcode = $args->{branchcode
};
1947 my $borrowernumber = $args->{borrowernumber
};
1948 my $biblionumber = $args->{biblionumber
};
1949 my $itemnumber = $args->{itemnumber
};
1950 my $barcode = $args->{barcode
};
1953 my $patron = Koha
::Patrons
->find($borrowernumber);
1956 if ($itemnumber || $barcode ) {
1957 $itemnumber ||= Koha
::Items
->find( { barcode
=> $barcode } )->itemnumber;
1959 $hold = Koha
::Holds
->search(
1961 biblionumber
=> $biblionumber,
1962 borrowernumber
=> $borrowernumber,
1963 itemnumber
=> $itemnumber
1968 $hold = Koha
::Holds
->search(
1970 biblionumber
=> $biblionumber,
1971 borrowernumber
=> $borrowernumber
1976 return unless $hold;
1977 my $reserve = $hold->unblessed;
1979 return C4
::Letters
::GetPreparedLetter
(
1980 module
=> 'circulation',
1981 letter_code
=> 'HOLD_SLIP',
1982 branchcode
=> $branchcode,
1983 lang
=> $patron->lang,
1985 'reserves' => $reserve,
1986 'branches' => $reserve->{branchcode
},
1987 'borrowers' => $reserve->{borrowernumber
},
1988 'biblio' => $reserve->{biblionumber
},
1989 'biblioitems' => $reserve->{biblionumber
},
1990 'items' => $reserve->{itemnumber
},
1995 =head2 GetReservesControlBranch
1997 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
1999 Return the branchcode to be used to determine which reserves
2000 policy applies to a transaction.
2002 C<$item> is a hashref for an item. Only 'homebranch' is used.
2004 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2008 sub GetReservesControlBranch
{
2009 my ( $item, $borrower ) = @_;
2011 my $reserves_control = C4
::Context
->preference('ReservesControlBranch');
2014 ( $reserves_control eq 'ItemHomeLibrary' ) ?
$item->{'homebranch'}
2015 : ( $reserves_control eq 'PatronLibrary' ) ?
$borrower->{'branchcode'}
2021 =head2 CalculatePriority
2023 my $p = CalculatePriority($biblionumber, $resdate);
2025 Calculate priority for a new reserve on biblionumber, placing it at
2026 the end of the line of all holds whose start date falls before
2027 the current system time and that are neither on the hold shelf
2030 The reserve date parameter is optional; if it is supplied, the
2031 priority is based on the set of holds whose start date falls before
2032 the parameter value.
2034 After calculation of this priority, it is recommended to call
2035 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2040 sub CalculatePriority
{
2041 my ( $biblionumber, $resdate ) = @_;
2044 SELECT COUNT(*) FROM reserves
2045 WHERE biblionumber = ?
2047 AND (found IS NULL OR found = '')
2049 #skip found==W or found==T (waiting or transit holds)
2051 $sql.= ' AND ( reservedate <= ? )';
2054 $sql.= ' AND ( reservedate < NOW() )';
2056 my $dbh = C4
::Context
->dbh();
2057 my @row = $dbh->selectrow_array(
2060 $resdate ?
($biblionumber, $resdate) : ($biblionumber)
2063 return @row ?
$row[0]+1 : 1;
2066 =head2 IsItemOnHoldAndFound
2068 my $bool = IsItemFoundHold( $itemnumber );
2070 Returns true if the item is currently on hold
2071 and that hold has a non-null found status ( W, T, etc. )
2075 sub IsItemOnHoldAndFound
{
2076 my ($itemnumber) = @_;
2078 my $rs = Koha
::Database
->new()->schema()->resultset('Reserve');
2080 my $found = $rs->count(
2082 itemnumber
=> $itemnumber,
2083 found
=> { '!=' => undef }
2090 =head2 GetMaxPatronHoldsForRecord
2092 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2094 For multiple holds on a given record for a given patron, the max
2095 number of record level holds that a patron can be placed is the highest
2096 value of the holds_per_record rule for each item if the record for that
2097 patron. This subroutine finds and returns the highest holds_per_record
2098 rule value for a given patron id and record id.
2102 sub GetMaxPatronHoldsForRecord
{
2103 my ( $borrowernumber, $biblionumber ) = @_;
2105 my $patron = Koha
::Patrons
->find($borrowernumber);
2106 my @items = Koha
::Items
->search( { biblionumber
=> $biblionumber } );
2108 my $controlbranch = C4
::Context
->preference('ReservesControlBranch');
2110 my $categorycode = $patron->categorycode;
2112 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2115 foreach my $item (@items) {
2116 my $itemtype = $item->effective_itemtype();
2118 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2120 my $rule = GetHoldRule
( $categorycode, $itemtype, $branchcode );
2121 my $holds_per_record = $rule ?
$rule->{holds_per_record
} : 0;
2122 $max = $holds_per_record if $holds_per_record > $max;
2130 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2132 Returns the matching hold related issuingrule fields for a given
2133 patron category, itemtype, and library.
2138 my ( $categorycode, $itemtype, $branchcode ) = @_;
2140 my $dbh = C4
::Context
->dbh;
2142 my $sth = $dbh->prepare(
2144 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record, holds_per_day
2146 WHERE (categorycode in (?,'*') )
2147 AND (itemtype IN (?,'*'))
2148 AND (branchcode IN (?,'*'))
2149 ORDER BY categorycode DESC,
2155 $sth->execute( $categorycode, $itemtype, $branchcode );
2157 return $sth->fetchrow_hashref();
2162 Koha Development Team <http://koha-community.org/>