Bug 18370: Use splice instead of splice
[koha.git] / C4 / Reserves.pm
blob552095445323a8c8ba4014bb54a3f30704ba41a2
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 &GetReservesFromBorrowernumber
108 &GetReservesForBranch
109 &GetReservesToBranch
110 &GetReserveCount
111 &GetReserveInfo
112 &GetReserveStatus
114 &GetOtherReserves
116 &ModReserveFill
117 &ModReserveAffect
118 &ModReserve
119 &ModReserveStatus
120 &ModReserveCancelAll
121 &ModReserveMinusPriority
122 &MoveReserve
124 &CheckReserves
125 &CanBookBeReserved
126 &CanItemBeReserved
127 &CanReserveBeCanceledFromOpac
128 &CancelReserve
129 &CancelExpiredReserves
131 &AutoUnsuspendReserves
133 &IsAvailableForItemLevelRequest
135 &OPACItemHoldsAllowed
137 &AlterPriority
138 &ToggleLowestPriority
140 &ReserveSlip
141 &ToggleSuspend
142 &SuspendAll
144 &GetReservesControlBranch
146 IsItemOnHoldAndFound
148 GetMaxPatronHoldsForRecord
150 @EXPORT_OK = qw( MergeHolds );
153 =head2 AddReserve
155 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
157 Adds reserve and generates HOLDPLACED message.
159 The following tables are available witin the HOLDPLACED message:
161 branches
162 borrowers
163 biblio
164 biblioitems
165 items
166 reserves
168 =cut
170 sub AddReserve {
171 my (
172 $branch, $borrowernumber, $biblionumber, $bibitems,
173 $priority, $resdate, $expdate, $notes,
174 $title, $checkitem, $found, $itemtype
175 ) = @_;
177 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
178 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
180 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
182 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
184 # Make room in reserves for this before those of a later reserve date
185 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
188 my $waitingdate;
190 # If the reserv had the waiting status, we had the value of the resdate
191 if ( $found eq 'W' ) {
192 $waitingdate = $resdate;
195 # Don't add itemtype limit if specific item is selected
196 $itemtype = undef if $checkitem;
198 # updates take place here
199 my $hold = Koha::Hold->new(
201 borrowernumber => $borrowernumber,
202 biblionumber => $biblionumber,
203 reservedate => $resdate,
204 branchcode => $branch,
205 priority => $priority,
206 reservenotes => $notes,
207 itemnumber => $checkitem,
208 found => $found,
209 waitingdate => $waitingdate,
210 expirationdate => $expdate,
211 itemtype => $itemtype,
213 )->store();
215 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
216 if C4::Context->preference('HoldsLog');
218 my $reserve_id = $hold->id();
220 # add a reserve fee if needed
221 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
222 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
223 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
226 _FixPriority({ biblionumber => $biblionumber});
228 # Send e-mail to librarian if syspref is active
229 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
230 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
231 my $library = Koha::Libraries->find($borrower->{branchcode})->unblessed;
232 if ( my $letter = C4::Letters::GetPreparedLetter (
233 module => 'reserves',
234 letter_code => 'HOLDPLACED',
235 branchcode => $branch,
236 tables => {
237 'branches' => $library,
238 'borrowers' => $borrower,
239 'biblio' => $biblionumber,
240 'biblioitems' => $biblionumber,
241 'items' => $checkitem,
242 'reserves' => $hold->unblessed,
244 ) ) {
246 my $admin_email_address = $library->{'branchemail'} || C4::Context->preference('KohaAdminEmailAddress');
248 C4::Letters::EnqueueLetter(
249 { letter => $letter,
250 borrowernumber => $borrowernumber,
251 message_transport_type => 'email',
252 from_address => $admin_email_address,
253 to_address => $admin_email_address,
259 return $reserve_id;
262 =head2 GetReserve
264 $res = GetReserve( $reserve_id );
266 Return the current reserve.
268 =cut
270 sub GetReserve {
271 my ($reserve_id) = @_;
273 my $dbh = C4::Context->dbh;
275 my $query = "SELECT * FROM reserves WHERE reserve_id = ?";
276 my $sth = $dbh->prepare( $query );
277 $sth->execute( $reserve_id );
278 return $sth->fetchrow_hashref();
281 =head2 GetReservesFromBorrowernumber
283 $borrowerreserv = GetReservesFromBorrowernumber($borrowernumber,$tatus);
285 TODO :: Descritpion
287 =cut
289 sub GetReservesFromBorrowernumber {
290 my ( $borrowernumber, $status ) = @_;
291 my $dbh = C4::Context->dbh;
292 my $sth;
293 if ($status) {
294 $sth = $dbh->prepare("
295 SELECT *
296 FROM reserves
297 WHERE borrowernumber=?
298 AND found =?
299 ORDER BY reservedate
301 $sth->execute($borrowernumber,$status);
302 } else {
303 $sth = $dbh->prepare("
304 SELECT *
305 FROM reserves
306 WHERE borrowernumber=?
307 ORDER BY reservedate
309 $sth->execute($borrowernumber);
311 my $data = $sth->fetchall_arrayref({});
312 return @$data;
315 =head2 CanBookBeReserved
317 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
318 if ($canReserve eq 'OK') { #We can reserve this Item! }
320 See CanItemBeReserved() for possible return values.
322 =cut
324 sub CanBookBeReserved{
325 my ($borrowernumber, $biblionumber) = @_;
327 my $items = GetItemnumbersForBiblio($biblionumber);
328 #get items linked via host records
329 my @hostitems = get_hostitemnumbers_of($biblionumber);
330 if (@hostitems){
331 push (@$items,@hostitems);
334 my $canReserve;
335 foreach my $item (@$items) {
336 $canReserve = CanItemBeReserved( $borrowernumber, $item );
337 return 'OK' if $canReserve eq 'OK';
339 return $canReserve;
342 =head2 CanItemBeReserved
344 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
345 if ($canReserve eq 'OK') { #We can reserve this Item! }
347 @RETURNS OK, if the Item can be reserved.
348 ageRestricted, if the Item is age restricted for this borrower.
349 damaged, if the Item is damaged.
350 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
351 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
352 notReservable, if holds on this item are not allowed
354 =cut
356 sub CanItemBeReserved {
357 my ( $borrowernumber, $itemnumber ) = @_;
359 my $dbh = C4::Context->dbh;
360 my $ruleitemtype; # itemtype of the matching issuing rule
361 my $allowedreserves = 0; # Total number of holds allowed across all records
362 my $holds_per_record = 1; # Total number of holds allowed for this one given record
364 # we retrieve borrowers and items informations #
365 # item->{itype} will come for biblioitems if necessery
366 my $item = GetItem($itemnumber);
367 my $biblioData = C4::Biblio::GetBiblioData( $item->{biblionumber} );
368 my $borrower = C4::Members::GetMember( 'borrowernumber' => $borrowernumber );
370 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
371 return 'damaged'
372 if ( $item->{damaged}
373 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
375 # Check for the age restriction
376 my ( $ageRestriction, $daysToAgeRestriction ) =
377 C4::Circulation::GetAgeRestriction( $biblioData->{agerestriction}, $borrower );
378 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
380 # Check that the patron doesn't have an item level hold on this item already
381 return 'itemAlreadyOnHold'
382 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
384 my $controlbranch = C4::Context->preference('ReservesControlBranch');
386 my $querycount = q{
387 SELECT count(*) AS count
388 FROM reserves
389 LEFT JOIN items USING (itemnumber)
390 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
391 LEFT JOIN borrowers USING (borrowernumber)
392 WHERE borrowernumber = ?
395 my $branchcode = "";
396 my $branchfield = "reserves.branchcode";
398 if ( $controlbranch eq "ItemHomeLibrary" ) {
399 $branchfield = "items.homebranch";
400 $branchcode = $item->{homebranch};
402 elsif ( $controlbranch eq "PatronLibrary" ) {
403 $branchfield = "borrowers.branchcode";
404 $branchcode = $borrower->{branchcode};
407 # we retrieve rights
408 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
409 $ruleitemtype = $rights->{itemtype};
410 $allowedreserves = $rights->{reservesallowed};
411 $holds_per_record = $rights->{holds_per_record};
413 else {
414 $ruleitemtype = '*';
417 $item = Koha::Items->find( $itemnumber );
418 my $holds = Koha::Holds->search(
420 borrowernumber => $borrowernumber,
421 biblionumber => $item->biblionumber,
422 found => undef, # Found holds don't count against a patron's holds limit
425 if ( $holds->count() >= $holds_per_record ) {
426 return "tooManyHoldsForThisRecord";
429 # we retrieve count
431 $querycount .= "AND $branchfield = ?";
433 # If using item-level itypes, fall back to the record
434 # level itemtype if the hold has no associated item
435 $querycount .=
436 C4::Context->preference('item-level_itypes')
437 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
438 : " AND biblioitems.itemtype = ?"
439 if ( $ruleitemtype ne "*" );
441 my $sthcount = $dbh->prepare($querycount);
443 if ( $ruleitemtype eq "*" ) {
444 $sthcount->execute( $borrowernumber, $branchcode );
446 else {
447 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
450 my $reservecount = "0";
451 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
452 $reservecount = $rowcount->{count};
455 # we check if it's ok or not
456 if ( $reservecount >= $allowedreserves ) {
457 return 'tooManyReserves';
460 my $circ_control_branch =
461 C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
462 my $branchitemrule =
463 C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype );
465 if ( $branchitemrule->{holdallowed} == 0 ) {
466 return 'notReservable';
469 if ( $branchitemrule->{holdallowed} == 1
470 && $borrower->{branchcode} ne $item->homebranch )
472 return 'cannotReserveFromOtherBranches';
475 # If reservecount is ok, we check item branch if IndependentBranches is ON
476 # and canreservefromotherbranches is OFF
477 if ( C4::Context->preference('IndependentBranches')
478 and !C4::Context->preference('canreservefromotherbranches') )
480 my $itembranch = $item->homebranch;
481 if ( $itembranch ne $borrower->{branchcode} ) {
482 return 'cannotReserveFromOtherBranches';
486 return 'OK';
489 =head2 CanReserveBeCanceledFromOpac
491 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
493 returns 1 if reserve can be cancelled by user from OPAC.
494 First check if reserve belongs to user, next checks if reserve is not in
495 transfer or waiting status
497 =cut
499 sub CanReserveBeCanceledFromOpac {
500 my ($reserve_id, $borrowernumber) = @_;
502 return unless $reserve_id and $borrowernumber;
503 my $reserve = GetReserve($reserve_id);
505 return 0 unless $reserve->{borrowernumber} == $borrowernumber;
506 return 0 if ( $reserve->{found} eq 'W' ) or ( $reserve->{found} eq 'T' );
508 return 1;
512 =head2 GetReserveCount
514 $number = &GetReserveCount($borrowernumber);
516 this function returns the number of reservation for a borrower given on input arg.
518 =cut
520 sub GetReserveCount {
521 my ($borrowernumber) = @_;
523 my $dbh = C4::Context->dbh;
525 my $query = "
526 SELECT COUNT(*) AS counter
527 FROM reserves
528 WHERE borrowernumber = ?
530 my $sth = $dbh->prepare($query);
531 $sth->execute($borrowernumber);
532 my $row = $sth->fetchrow_hashref;
533 return $row->{counter};
536 =head2 GetOtherReserves
538 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
540 Check queued list of this document and check if this document must be transferred
542 =cut
544 sub GetOtherReserves {
545 my ($itemnumber) = @_;
546 my $messages;
547 my $nextreservinfo;
548 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
549 if ($checkreserves) {
550 my $iteminfo = GetItem($itemnumber);
551 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
552 $messages->{'transfert'} = $checkreserves->{'branchcode'};
553 #minus priorities of others reservs
554 ModReserveMinusPriority(
555 $itemnumber,
556 $checkreserves->{'reserve_id'},
559 #launch the subroutine dotransfer
560 C4::Items::ModItemTransfer(
561 $itemnumber,
562 $iteminfo->{'holdingbranch'},
563 $checkreserves->{'branchcode'}
568 #step 2b : case of a reservation on the same branch, set the waiting status
569 else {
570 $messages->{'waiting'} = 1;
571 ModReserveMinusPriority(
572 $itemnumber,
573 $checkreserves->{'reserve_id'},
575 ModReserveStatus($itemnumber,'W');
578 $nextreservinfo = $checkreserves->{'borrowernumber'};
581 return ( $messages, $nextreservinfo );
584 =head2 ChargeReserveFee
586 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
588 Charge the fee for a reserve (if $fee > 0)
590 =cut
592 sub ChargeReserveFee {
593 my ( $borrowernumber, $fee, $title ) = @_;
594 return if !$fee || $fee==0; # the last test is needed to include 0.00
595 my $accquery = qq{
596 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
598 my $dbh = C4::Context->dbh;
599 my $nextacctno = &getnextacctno( $borrowernumber );
600 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
603 =head2 GetReserveFee
605 $fee = GetReserveFee( $borrowernumber, $biblionumber );
607 Calculate the fee for a reserve (if applicable).
609 =cut
611 sub GetReserveFee {
612 my ( $borrowernumber, $biblionumber ) = @_;
613 my $borquery = qq{
614 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
616 my $issue_qry = qq{
617 SELECT COUNT(*) FROM items
618 LEFT JOIN issues USING (itemnumber)
619 WHERE items.biblionumber=? AND issues.issue_id IS NULL
621 my $holds_qry = qq{
622 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
625 my $dbh = C4::Context->dbh;
626 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
627 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
628 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
629 # This is a reconstruction of the old code:
630 # Compare number of items with items issued, and optionally check holds
631 # If not all items are issued and there are no holds: charge no fee
632 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
633 my ( $notissued, $reserved );
634 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
635 ( $biblionumber ) );
636 if( $notissued ) {
637 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
638 ( $biblionumber, $borrowernumber ) );
639 $fee = 0 if $reserved == 0;
642 return $fee;
645 =head2 GetReservesToBranch
647 @transreserv = GetReservesToBranch( $frombranch );
649 Get reserve list for a given branch
651 =cut
653 sub GetReservesToBranch {
654 my ( $frombranch ) = @_;
655 my $dbh = C4::Context->dbh;
656 my $sth = $dbh->prepare(
657 "SELECT reserve_id,borrowernumber,reservedate,itemnumber,timestamp
658 FROM reserves
659 WHERE priority='0'
660 AND branchcode=?"
662 $sth->execute( $frombranch );
663 my @transreserv;
664 my $i = 0;
665 while ( my $data = $sth->fetchrow_hashref ) {
666 $transreserv[$i] = $data;
667 $i++;
669 return (@transreserv);
672 =head2 GetReservesForBranch
674 @transreserv = GetReservesForBranch($frombranch);
676 =cut
678 sub GetReservesForBranch {
679 my ($frombranch) = @_;
680 my $dbh = C4::Context->dbh;
682 my $query = "
683 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate, expirationdate
684 FROM reserves
685 WHERE priority='0'
686 AND found='W'
688 $query .= " AND branchcode=? " if ( $frombranch );
689 $query .= "ORDER BY waitingdate" ;
691 my $sth = $dbh->prepare($query);
692 if ($frombranch){
693 $sth->execute($frombranch);
694 } else {
695 $sth->execute();
698 my @transreserv;
699 my $i = 0;
700 while ( my $data = $sth->fetchrow_hashref ) {
701 $transreserv[$i] = $data;
702 $i++;
704 return (@transreserv);
707 =head2 GetReserveStatus
709 $reservestatus = GetReserveStatus($itemnumber);
711 Takes an itemnumber and returns the status of the reserve placed on it.
712 If several reserves exist, the reserve with the lower priority is given.
714 =cut
716 ## FIXME: I don't think this does what it thinks it does.
717 ## It only ever checks the first reserve result, even though
718 ## multiple reserves for that bib can have the itemnumber set
719 ## the sub is only used once in the codebase.
720 sub GetReserveStatus {
721 my ($itemnumber) = @_;
723 my $dbh = C4::Context->dbh;
725 my ($sth, $found, $priority);
726 if ( $itemnumber ) {
727 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
728 $sth->execute($itemnumber);
729 ($found, $priority) = $sth->fetchrow_array;
732 if(defined $found) {
733 return 'Waiting' if $found eq 'W' and $priority == 0;
734 return 'Finished' if $found eq 'F';
737 return 'Reserved' if $priority > 0;
739 return ''; # empty string here will remove need for checking undef, or less log lines
742 =head2 CheckReserves
744 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
745 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
746 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
748 Find a book in the reserves.
750 C<$itemnumber> is the book's item number.
751 C<$lookahead> is the number of days to look in advance for future reserves.
753 As I understand it, C<&CheckReserves> looks for the given item in the
754 reserves. If it is found, that's a match, and C<$status> is set to
755 C<Waiting>.
757 Otherwise, it finds the most important item in the reserves with the
758 same biblio number as this book (I'm not clear on this) and returns it
759 with C<$status> set to C<Reserved>.
761 C<&CheckReserves> returns a two-element list:
763 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
765 C<$reserve> is the reserve item that matched. It is a
766 reference-to-hash whose keys are mostly the fields of the reserves
767 table in the Koha database.
769 =cut
771 sub CheckReserves {
772 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
773 my $dbh = C4::Context->dbh;
774 my $sth;
775 my $select;
776 if (C4::Context->preference('item-level_itypes')){
777 $select = "
778 SELECT items.biblionumber,
779 items.biblioitemnumber,
780 itemtypes.notforloan,
781 items.notforloan AS itemnotforloan,
782 items.itemnumber,
783 items.damaged,
784 items.homebranch,
785 items.holdingbranch
786 FROM items
787 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
788 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
791 else {
792 $select = "
793 SELECT items.biblionumber,
794 items.biblioitemnumber,
795 itemtypes.notforloan,
796 items.notforloan AS itemnotforloan,
797 items.itemnumber,
798 items.damaged,
799 items.homebranch,
800 items.holdingbranch
801 FROM items
802 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
803 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
807 if ($item) {
808 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
809 $sth->execute($item);
811 else {
812 $sth = $dbh->prepare("$select WHERE barcode = ?");
813 $sth->execute($barcode);
815 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
816 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
818 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
820 return unless $itemnumber; # bail if we got nothing.
822 # if item is not for loan it cannot be reserved either.....
823 # except where items.notforloan < 0 : This indicates the item is holdable.
824 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
826 # Find this item in the reserves
827 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
829 # $priority and $highest are used to find the most important item
830 # in the list returned by &_Findgroupreserve. (The lower $priority,
831 # the more important the item.)
832 # $highest is the most important item we've seen so far.
833 my $highest;
834 if (scalar @reserves) {
835 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
836 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
837 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
839 my $priority = 10000000;
840 foreach my $res (@reserves) {
841 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
842 return ( "Waiting", $res, \@reserves ); # Found it
843 } else {
844 my $borrowerinfo;
845 my $iteminfo;
846 my $local_hold_match;
848 if ($LocalHoldsPriority) {
849 $borrowerinfo = C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
850 $iteminfo = C4::Items::GetItem($itemnumber);
852 my $local_holds_priority_item_branchcode =
853 $iteminfo->{$LocalHoldsPriorityItemControl};
854 my $local_holds_priority_patron_branchcode =
855 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
856 ? $res->{branchcode}
857 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
858 ? $borrowerinfo->{branchcode}
859 : undef;
860 $local_hold_match =
861 $local_holds_priority_item_branchcode eq
862 $local_holds_priority_patron_branchcode;
865 # See if this item is more important than what we've got so far
866 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
867 $iteminfo ||= C4::Items::GetItem($itemnumber);
868 next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
869 $borrowerinfo ||= C4::Members::GetMember( borrowernumber => $res->{'borrowernumber'} );
870 my $branch = GetReservesControlBranch( $iteminfo, $borrowerinfo );
871 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
872 next if ($branchitemrule->{'holdallowed'} == 0);
873 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $borrowerinfo->{'branchcode'}));
874 next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy} }) );
875 $priority = $res->{'priority'};
876 $highest = $res;
877 last if $local_hold_match;
883 # If we get this far, then no exact match was found.
884 # We return the most important (i.e. next) reservation.
885 if ($highest) {
886 $highest->{'itemnumber'} = $item;
887 return ( "Reserved", $highest, \@reserves );
890 return ( '' );
893 =head2 CancelExpiredReserves
895 CancelExpiredReserves();
897 Cancels all reserves with an expiration date from before today.
899 =cut
901 sub CancelExpiredReserves {
903 my $today = dt_from_string();
904 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
906 my $dbh = C4::Context->dbh;
907 my $sth = $dbh->prepare( "
908 SELECT * FROM reserves WHERE DATE(expirationdate) < DATE( CURDATE() )
909 AND expirationdate IS NOT NULL
910 " );
911 $sth->execute();
913 while ( my $res = $sth->fetchrow_hashref() ) {
914 my $calendar = Koha::Calendar->new( branchcode => $res->{'branchcode'} );
915 my $cancel_params = { reserve_id => $res->{'reserve_id'} };
917 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
919 if ( $res->{found} eq 'W' ) {
920 $cancel_params->{charge_cancel_fee} = 1;
923 CancelReserve($cancel_params);
927 =head2 AutoUnsuspendReserves
929 AutoUnsuspendReserves();
931 Unsuspends all suspended reserves with a suspend_until date from before today.
933 =cut
935 sub AutoUnsuspendReserves {
936 my $today = dt_from_string();
938 my @holds = Koha::Holds->search( { suspend_until => { '<' => $today->ymd() } } );
940 map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
943 =head2 CancelReserve
945 CancelReserve({ reserve_id => $reserve_id, [ biblionumber => $biblionumber, borrowernumber => $borrrowernumber, itemnumber => $itemnumber, ] [ charge_cancel_fee => 1 ] });
947 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.
949 =cut
951 sub CancelReserve {
952 my ( $params ) = @_;
954 my $reserve_id = $params->{'reserve_id'};
955 # Filter out only the desired keys; this will insert undefined values for elements missing in
956 # \%params, but GetReserveId filters them out anyway.
957 $reserve_id = GetReserveId( { biblionumber => $params->{'biblionumber'}, borrowernumber => $params->{'borrowernumber'}, itemnumber => $params->{'itemnumber'} } ) unless ( $reserve_id );
959 return unless ( $reserve_id );
961 my $dbh = C4::Context->dbh;
963 my $reserve = GetReserve( $reserve_id );
964 if ($reserve) {
966 my $hold = Koha::Holds->find( $reserve_id );
967 logaction( 'HOLDS', 'CANCEL', $hold->reserve_id, Dumper($hold->unblessed) )
968 if C4::Context->preference('HoldsLog');
970 my $query = "
971 UPDATE reserves
972 SET cancellationdate = now(),
973 priority = 0
974 WHERE reserve_id = ?
976 my $sth = $dbh->prepare($query);
977 $sth->execute( $reserve_id );
979 $query = "
980 INSERT INTO old_reserves
981 SELECT * FROM reserves
982 WHERE reserve_id = ?
984 $sth = $dbh->prepare($query);
985 $sth->execute( $reserve_id );
987 $query = "
988 DELETE FROM reserves
989 WHERE reserve_id = ?
991 $sth = $dbh->prepare($query);
992 $sth->execute( $reserve_id );
994 # now fix the priority on the others....
995 _FixPriority({ biblionumber => $reserve->{biblionumber} });
997 # and, if desired, charge a cancel fee
998 my $charge = C4::Context->preference("ExpireReservesMaxPickUpDelayCharge");
999 if ( $charge && $params->{'charge_cancel_fee'} ) {
1000 manualinvoice($reserve->{'borrowernumber'}, $reserve->{'itemnumber'}, '', 'HE', $charge);
1004 return $reserve;
1007 =head2 ModReserve
1009 ModReserve({ rank => $rank,
1010 reserve_id => $reserve_id,
1011 branchcode => $branchcode
1012 [, itemnumber => $itemnumber ]
1013 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
1016 Change a hold request's priority or cancel it.
1018 C<$rank> specifies the effect of the change. If C<$rank>
1019 is 'W' or 'n', nothing happens. This corresponds to leaving a
1020 request alone when changing its priority in the holds queue
1021 for a bib.
1023 If C<$rank> is 'del', the hold request is cancelled.
1025 If C<$rank> is an integer greater than zero, the priority of
1026 the request is set to that value. Since priority != 0 means
1027 that the item is not waiting on the hold shelf, setting the
1028 priority to a non-zero value also sets the request's found
1029 status and waiting date to NULL.
1031 The optional C<$itemnumber> parameter is used only when
1032 C<$rank> is a non-zero integer; if supplied, the itemnumber
1033 of the hold request is set accordingly; if omitted, the itemnumber
1034 is cleared.
1036 B<FIXME:> Note that the forgoing can have the effect of causing
1037 item-level hold requests to turn into title-level requests. This
1038 will be fixed once reserves has separate columns for requested
1039 itemnumber and supplying itemnumber.
1041 =cut
1043 sub ModReserve {
1044 my ( $params ) = @_;
1046 my $rank = $params->{'rank'};
1047 my $reserve_id = $params->{'reserve_id'};
1048 my $branchcode = $params->{'branchcode'};
1049 my $itemnumber = $params->{'itemnumber'};
1050 my $suspend_until = $params->{'suspend_until'};
1051 my $borrowernumber = $params->{'borrowernumber'};
1052 my $biblionumber = $params->{'biblionumber'};
1054 return if $rank eq "W";
1055 return if $rank eq "n";
1057 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
1058 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber }) unless ( $reserve_id );
1060 if ( $rank eq "del" ) {
1061 CancelReserve({ reserve_id => $reserve_id });
1063 elsif ($rank =~ /^\d+/ and $rank > 0) {
1064 my $hold = Koha::Holds->find($reserve_id);
1065 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
1066 if C4::Context->preference('HoldsLog');
1068 $hold->set(
1070 priority => $rank,
1071 branchcode => $branchcode,
1072 itemnumber => $itemnumber,
1073 found => undef,
1074 waitingdate => undef
1076 )->store();
1078 if ( defined( $suspend_until ) ) {
1079 if ( $suspend_until ) {
1080 $suspend_until = eval { dt_from_string( $suspend_until ) };
1081 $hold->suspend_hold( $suspend_until );
1082 } else {
1083 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
1084 # If the hold is not suspended, this does nothing.
1085 $hold->set( { suspend_until => undef } )->store();
1089 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1093 =head2 ModReserveFill
1095 &ModReserveFill($reserve);
1097 Fill a reserve. If I understand this correctly, this means that the
1098 reserved book has been found and given to the patron who reserved it.
1100 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1101 whose keys are fields from the reserves table in the Koha database.
1103 =cut
1105 sub ModReserveFill {
1106 my ($res) = @_;
1107 my $reserve_id = $res->{'reserve_id'};
1109 my $hold = Koha::Holds->find($reserve_id);
1111 # get the priority on this record....
1112 my $priority = $hold->priority;
1114 # update the hold statuses, no need to store it though, we will be deleting it anyway
1115 $hold->set(
1117 found => 'F',
1118 priority => 0,
1122 Koha::Old::Hold->new( $hold->unblessed() )->store();
1124 $hold->delete();
1126 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1127 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1128 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1131 # now fix the priority on the others (if the priority wasn't
1132 # already sorted!)....
1133 unless ( $priority == 0 ) {
1134 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1138 =head2 ModReserveStatus
1140 &ModReserveStatus($itemnumber, $newstatus);
1142 Update the reserve status for the active (priority=0) reserve.
1144 $itemnumber is the itemnumber the reserve is on
1146 $newstatus is the new status.
1148 =cut
1150 sub ModReserveStatus {
1152 #first : check if we have a reservation for this item .
1153 my ($itemnumber, $newstatus) = @_;
1154 my $dbh = C4::Context->dbh;
1156 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1157 my $sth_set = $dbh->prepare($query);
1158 $sth_set->execute( $newstatus, $itemnumber );
1160 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1161 CartToShelf( $itemnumber );
1165 =head2 ModReserveAffect
1167 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1169 This function affect an item and a status for a given reserve, either fetched directly
1170 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1171 is given, only first reserve returned is affected, which is ok for anything but
1172 multi-item holds.
1174 if $transferToDo is not set, then the status is set to "Waiting" as well.
1175 otherwise, a transfer is on the way, and the end of the transfer will
1176 take care of the waiting status
1178 =cut
1180 sub ModReserveAffect {
1181 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1182 my $dbh = C4::Context->dbh;
1184 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1185 # attached to $itemnumber
1186 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1187 $sth->execute($itemnumber);
1188 my ($biblionumber) = $sth->fetchrow;
1190 # get request - need to find out if item is already
1191 # waiting in order to not send duplicate hold filled notifications
1193 my $hold;
1194 # Find hold by id if we have it
1195 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1196 # Find item level hold for this item if there is one
1197 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1198 # Find record level hold if there is no item level hold
1199 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1201 return unless $hold;
1203 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1205 $hold->itemnumber($itemnumber);
1206 $hold->set_waiting($transferToDo);
1208 _koha_notify_reserve( $hold->reserve_id )
1209 if ( !$transferToDo && !$already_on_shelf );
1211 _FixPriority( { biblionumber => $biblionumber } );
1213 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1214 CartToShelf($itemnumber);
1217 return;
1220 =head2 ModReserveCancelAll
1222 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1224 function to cancel reserv,check other reserves, and transfer document if it's necessary
1226 =cut
1228 sub ModReserveCancelAll {
1229 my $messages;
1230 my $nextreservinfo;
1231 my ( $itemnumber, $borrowernumber ) = @_;
1233 #step 1 : cancel the reservation
1234 my $CancelReserve = CancelReserve({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1236 #step 2 launch the subroutine of the others reserves
1237 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1239 return ( $messages, $nextreservinfo );
1242 =head2 ModReserveMinusPriority
1244 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1246 Reduce the values of queued list
1248 =cut
1250 sub ModReserveMinusPriority {
1251 my ( $itemnumber, $reserve_id ) = @_;
1253 #first step update the value of the first person on reserv
1254 my $dbh = C4::Context->dbh;
1255 my $query = "
1256 UPDATE reserves
1257 SET priority = 0 , itemnumber = ?
1258 WHERE reserve_id = ?
1260 my $sth_upd = $dbh->prepare($query);
1261 $sth_upd->execute( $itemnumber, $reserve_id );
1262 # second step update all others reserves
1263 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1266 =head2 GetReserveInfo
1268 &GetReserveInfo($reserve_id);
1270 Get item and borrower details for a current hold.
1271 Current implementation this query should have a single result.
1273 =cut
1275 sub GetReserveInfo {
1276 my ( $reserve_id ) = @_;
1277 my $dbh = C4::Context->dbh;
1278 my $strsth="SELECT
1279 reserve_id,
1280 reservedate,
1281 reservenotes,
1282 reserves.borrowernumber,
1283 reserves.biblionumber,
1284 reserves.branchcode,
1285 reserves.waitingdate,
1286 notificationdate,
1287 reminderdate,
1288 priority,
1289 found,
1290 firstname,
1291 surname,
1292 phone,
1293 email,
1294 address,
1295 address2,
1296 cardnumber,
1297 city,
1298 zipcode,
1299 biblio.title,
1300 biblio.author,
1301 items.holdingbranch,
1302 items.itemcallnumber,
1303 items.itemnumber,
1304 items.location,
1305 barcode,
1306 notes
1307 FROM reserves
1308 LEFT JOIN items USING(itemnumber)
1309 LEFT JOIN borrowers USING(borrowernumber)
1310 LEFT JOIN biblio ON (reserves.biblionumber=biblio.biblionumber)
1311 WHERE reserves.reserve_id = ?";
1312 my $sth = $dbh->prepare($strsth);
1313 $sth->execute($reserve_id);
1315 my $data = $sth->fetchrow_hashref;
1316 return $data;
1319 =head2 IsAvailableForItemLevelRequest
1321 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1323 Checks whether a given item record is available for an
1324 item-level hold request. An item is available if
1326 * it is not lost AND
1327 * it is not damaged AND
1328 * it is not withdrawn AND
1329 * does not have a not for loan value > 0
1331 Need to check the issuingrules onshelfholds column,
1332 if this is set items on the shelf can be placed on hold
1334 Note that IsAvailableForItemLevelRequest() does not
1335 check if the staff operator is authorized to place
1336 a request on the item - in particular,
1337 this routine does not check IndependentBranches
1338 and canreservefromotherbranches.
1340 =cut
1342 sub IsAvailableForItemLevelRequest {
1343 my $item = shift;
1344 my $borrower = shift;
1346 my $dbh = C4::Context->dbh;
1347 # must check the notforloan setting of the itemtype
1348 # FIXME - a lot of places in the code do this
1349 # or something similar - need to be
1350 # consolidated
1351 my $itype = _get_itype($item);
1352 my $notforloan_per_itemtype
1353 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1354 undef, $itype);
1356 return 0 if
1357 $notforloan_per_itemtype ||
1358 $item->{itemlost} ||
1359 $item->{notforloan} > 0 ||
1360 $item->{withdrawn} ||
1361 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1363 my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1365 if ( $on_shelf_holds == 1 ) {
1366 return 1;
1367 } elsif ( $on_shelf_holds == 2 ) {
1368 my @items =
1369 Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1371 my $any_available = 0;
1373 foreach my $i (@items) {
1374 $any_available = 1
1375 unless $i->itemlost
1376 || $i->notforloan > 0
1377 || $i->withdrawn
1378 || $i->onloan
1379 || IsItemOnHoldAndFound( $i->id )
1380 || ( $i->damaged
1381 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1382 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan;
1385 return $any_available ? 0 : 1;
1388 return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
1391 =head2 OnShelfHoldsAllowed
1393 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1395 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1396 holds are allowed, returns true if so.
1398 =cut
1400 sub OnShelfHoldsAllowed {
1401 my ($item, $borrower) = @_;
1403 my $itype = _get_itype($item);
1404 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1407 sub _get_itype {
1408 my $item = shift;
1410 my $itype;
1411 if (C4::Context->preference('item-level_itypes')) {
1412 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1413 # When GetItem is fixed, we can remove this
1414 $itype = $item->{itype};
1416 else {
1417 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1418 # So if we already have a biblioitems join when calling this function,
1419 # we don't need to access the database again
1420 $itype = $item->{itemtype};
1422 unless ($itype) {
1423 my $dbh = C4::Context->dbh;
1424 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1425 my $sth = $dbh->prepare($query);
1426 $sth->execute($item->{biblioitemnumber});
1427 if (my $data = $sth->fetchrow_hashref()){
1428 $itype = $data->{itemtype};
1431 return $itype;
1434 sub _OnShelfHoldsAllowed {
1435 my ($itype,$borrowercategory,$branchcode) = @_;
1437 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
1438 return $issuing_rule ? $issuing_rule->onshelfholds : undef;
1441 =head2 AlterPriority
1443 AlterPriority( $where, $reserve_id );
1445 This function changes a reserve's priority up, down, to the top, or to the bottom.
1446 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1448 =cut
1450 sub AlterPriority {
1451 my ( $where, $reserve_id ) = @_;
1453 my $reserve = GetReserve( $reserve_id );
1455 if ( $reserve->{cancellationdate} ) {
1456 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (".$reserve->{cancellationdate}.')';
1457 return;
1460 if ( $where eq 'up' || $where eq 'down' ) {
1462 my $priority = $reserve->{'priority'};
1463 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1464 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1466 } elsif ( $where eq 'top' ) {
1468 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1470 } elsif ( $where eq 'bottom' ) {
1472 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1477 =head2 ToggleLowestPriority
1479 ToggleLowestPriority( $borrowernumber, $biblionumber );
1481 This function sets the lowestPriority field to true if is false, and false if it is true.
1483 =cut
1485 sub ToggleLowestPriority {
1486 my ( $reserve_id ) = @_;
1488 my $dbh = C4::Context->dbh;
1490 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1491 $sth->execute( $reserve_id );
1493 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1496 =head2 ToggleSuspend
1498 ToggleSuspend( $reserve_id );
1500 This function sets the suspend field to true if is false, and false if it is true.
1501 If the reserve is currently suspended with a suspend_until date, that date will
1502 be cleared when it is unsuspended.
1504 =cut
1506 sub ToggleSuspend {
1507 my ( $reserve_id, $suspend_until ) = @_;
1509 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1511 my $hold = Koha::Holds->find( $reserve_id );
1513 if ( $hold->is_suspended ) {
1514 $hold->resume()
1515 } else {
1516 $hold->suspend_hold( $suspend_until );
1520 =head2 SuspendAll
1522 SuspendAll(
1523 borrowernumber => $borrowernumber,
1524 [ biblionumber => $biblionumber, ]
1525 [ suspend_until => $suspend_until, ]
1526 [ suspend => $suspend ]
1529 This function accepts a set of hash keys as its parameters.
1530 It requires either borrowernumber or biblionumber, or both.
1532 suspend_until is wholly optional.
1534 =cut
1536 sub SuspendAll {
1537 my %params = @_;
1539 my $borrowernumber = $params{'borrowernumber'} || undef;
1540 my $biblionumber = $params{'biblionumber'} || undef;
1541 my $suspend_until = $params{'suspend_until'} || undef;
1542 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1544 $suspend_until = eval { dt_from_string($suspend_until) }
1545 if ( defined($suspend_until) );
1547 return unless ( $borrowernumber || $biblionumber );
1549 my $params;
1550 $params->{found} = undef;
1551 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1552 $params->{biblionumber} = $biblionumber if $biblionumber;
1554 my @holds = Koha::Holds->search($params);
1556 if ($suspend) {
1557 map { $_->suspend_hold($suspend_until) } @holds;
1559 else {
1560 map { $_->resume() } @holds;
1565 =head2 _FixPriority
1567 _FixPriority({
1568 reserve_id => $reserve_id,
1569 [rank => $rank,]
1570 [ignoreSetLowestRank => $ignoreSetLowestRank]
1575 _FixPriority({ biblionumber => $biblionumber});
1577 This routine adjusts the priority of a hold request and holds
1578 on the same bib.
1580 In the first form, where a reserve_id is passed, the priority of the
1581 hold is set to supplied rank, and other holds for that bib are adjusted
1582 accordingly. If the rank is "del", the hold is cancelled. If no rank
1583 is supplied, all of the holds on that bib have their priority adjusted
1584 as if the second form had been used.
1586 In the second form, where a biblionumber is passed, the holds on that
1587 bib (that are not captured) are sorted in order of increasing priority,
1588 then have reserves.priority set so that the first non-captured hold
1589 has its priority set to 1, the second non-captured hold has its priority
1590 set to 2, and so forth.
1592 In both cases, holds that have the lowestPriority flag on are have their
1593 priority adjusted to ensure that they remain at the end of the line.
1595 Note that the ignoreSetLowestRank parameter is meant to be used only
1596 when _FixPriority calls itself.
1598 =cut
1600 sub _FixPriority {
1601 my ( $params ) = @_;
1602 my $reserve_id = $params->{reserve_id};
1603 my $rank = $params->{rank} // '';
1604 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1605 my $biblionumber = $params->{biblionumber};
1607 my $dbh = C4::Context->dbh;
1609 unless ( $biblionumber ) {
1610 my $res = GetReserve( $reserve_id );
1611 $biblionumber = $res->{biblionumber};
1614 if ( $rank eq "del" ) {
1615 CancelReserve({ reserve_id => $reserve_id });
1617 elsif ( $rank eq "W" || $rank eq "0" ) {
1619 # make sure priority for waiting or in-transit items is 0
1620 my $query = "
1621 UPDATE reserves
1622 SET priority = 0
1623 WHERE reserve_id = ?
1624 AND found IN ('W', 'T')
1626 my $sth = $dbh->prepare($query);
1627 $sth->execute( $reserve_id );
1629 my @priority;
1631 # get whats left
1632 my $query = "
1633 SELECT reserve_id, borrowernumber, reservedate
1634 FROM reserves
1635 WHERE biblionumber = ?
1636 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1637 ORDER BY priority ASC
1639 my $sth = $dbh->prepare($query);
1640 $sth->execute( $biblionumber );
1641 while ( my $line = $sth->fetchrow_hashref ) {
1642 push( @priority, $line );
1645 # To find the matching index
1646 my $i;
1647 my $key = -1; # to allow for 0 to be a valid result
1648 for ( $i = 0 ; $i < @priority ; $i++ ) {
1649 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1650 $key = $i; # save the index
1651 last;
1655 # if index exists in array then move it to new position
1656 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1657 my $new_rank = $rank -
1658 1; # $new_rank is what you want the new index to be in the array
1659 my $moving_item = splice( @priority, $key, 1 );
1660 splice( @priority, $new_rank, 0, $moving_item );
1663 # now fix the priority on those that are left....
1664 $query = "
1665 UPDATE reserves
1666 SET priority = ?
1667 WHERE reserve_id = ?
1669 $sth = $dbh->prepare($query);
1670 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1671 $sth->execute(
1672 $j + 1,
1673 $priority[$j]->{'reserve_id'}
1677 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1678 $sth->execute();
1680 unless ( $ignoreSetLowestRank ) {
1681 while ( my $res = $sth->fetchrow_hashref() ) {
1682 _FixPriority({
1683 reserve_id => $res->{'reserve_id'},
1684 rank => '999999',
1685 ignoreSetLowestRank => 1
1691 =head2 _Findgroupreserve
1693 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1695 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1696 first match found. If neither, then we look for non-holds-queue based holds.
1697 Lookahead is the number of days to look in advance.
1699 C<&_Findgroupreserve> returns :
1700 C<@results> is an array of references-to-hash whose keys are mostly
1701 fields from the reserves table of the Koha database, plus
1702 C<biblioitemnumber>.
1704 =cut
1706 sub _Findgroupreserve {
1707 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1708 my $dbh = C4::Context->dbh;
1710 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1711 # check for exact targeted match
1712 my $item_level_target_query = qq{
1713 SELECT reserves.biblionumber AS biblionumber,
1714 reserves.borrowernumber AS borrowernumber,
1715 reserves.reservedate AS reservedate,
1716 reserves.branchcode AS branchcode,
1717 reserves.cancellationdate AS cancellationdate,
1718 reserves.found AS found,
1719 reserves.reservenotes AS reservenotes,
1720 reserves.priority AS priority,
1721 reserves.timestamp AS timestamp,
1722 biblioitems.biblioitemnumber AS biblioitemnumber,
1723 reserves.itemnumber AS itemnumber,
1724 reserves.reserve_id AS reserve_id,
1725 reserves.itemtype AS itemtype
1726 FROM reserves
1727 JOIN biblioitems USING (biblionumber)
1728 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1729 WHERE found IS NULL
1730 AND priority > 0
1731 AND item_level_request = 1
1732 AND itemnumber = ?
1733 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1734 AND suspend = 0
1735 ORDER BY priority
1737 my $sth = $dbh->prepare($item_level_target_query);
1738 $sth->execute($itemnumber, $lookahead||0);
1739 my @results;
1740 if ( my $data = $sth->fetchrow_hashref ) {
1741 push( @results, $data )
1742 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1744 return @results if @results;
1746 # check for title-level targeted match
1747 my $title_level_target_query = qq{
1748 SELECT reserves.biblionumber AS biblionumber,
1749 reserves.borrowernumber AS borrowernumber,
1750 reserves.reservedate AS reservedate,
1751 reserves.branchcode AS branchcode,
1752 reserves.cancellationdate AS cancellationdate,
1753 reserves.found AS found,
1754 reserves.reservenotes AS reservenotes,
1755 reserves.priority AS priority,
1756 reserves.timestamp AS timestamp,
1757 biblioitems.biblioitemnumber AS biblioitemnumber,
1758 reserves.itemnumber AS itemnumber,
1759 reserves.reserve_id AS reserve_id,
1760 reserves.itemtype AS itemtype
1761 FROM reserves
1762 JOIN biblioitems USING (biblionumber)
1763 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1764 WHERE found IS NULL
1765 AND priority > 0
1766 AND item_level_request = 0
1767 AND hold_fill_targets.itemnumber = ?
1768 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1769 AND suspend = 0
1770 ORDER BY priority
1772 $sth = $dbh->prepare($title_level_target_query);
1773 $sth->execute($itemnumber, $lookahead||0);
1774 @results = ();
1775 if ( my $data = $sth->fetchrow_hashref ) {
1776 push( @results, $data )
1777 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1779 return @results if @results;
1781 my $query = qq{
1782 SELECT reserves.biblionumber AS biblionumber,
1783 reserves.borrowernumber AS borrowernumber,
1784 reserves.reservedate AS reservedate,
1785 reserves.waitingdate AS waitingdate,
1786 reserves.branchcode AS branchcode,
1787 reserves.cancellationdate AS cancellationdate,
1788 reserves.found AS found,
1789 reserves.reservenotes AS reservenotes,
1790 reserves.priority AS priority,
1791 reserves.timestamp AS timestamp,
1792 reserves.itemnumber AS itemnumber,
1793 reserves.reserve_id AS reserve_id,
1794 reserves.itemtype AS itemtype
1795 FROM reserves
1796 WHERE reserves.biblionumber = ?
1797 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1798 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1799 AND suspend = 0
1800 ORDER BY priority
1802 $sth = $dbh->prepare($query);
1803 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1804 @results = ();
1805 while ( my $data = $sth->fetchrow_hashref ) {
1806 push( @results, $data )
1807 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1809 return @results;
1812 =head2 _koha_notify_reserve
1814 _koha_notify_reserve( $hold->reserve_id );
1816 Sends a notification to the patron that their hold has been filled (through
1817 ModReserveAffect, _not_ ModReserveFill)
1819 The letter code for this notice may be found using the following query:
1821 select distinct letter_code
1822 from message_transports
1823 inner join message_attributes using (message_attribute_id)
1824 where message_name = 'Hold_Filled'
1826 This will probably sipmly be 'HOLD', but because it is defined in the database,
1827 it is subject to addition or change.
1829 The following tables are availalbe witin the notice:
1831 branches
1832 borrowers
1833 biblio
1834 biblioitems
1835 reserves
1836 items
1838 =cut
1840 sub _koha_notify_reserve {
1841 my $reserve_id = shift;
1842 my $hold = Koha::Holds->find($reserve_id);
1843 my $borrowernumber = $hold->borrowernumber;
1845 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
1847 # Try to get the borrower's email address
1848 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1850 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1851 borrowernumber => $borrowernumber,
1852 message_name => 'Hold_Filled'
1853 } );
1855 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1857 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1859 my %letter_params = (
1860 module => 'reserves',
1861 branchcode => $hold->branchcode,
1862 tables => {
1863 'branches' => $library,
1864 'borrowers' => $borrower,
1865 'biblio' => $hold->biblionumber,
1866 'biblioitems' => $hold->biblionumber,
1867 'reserves' => $hold->unblessed,
1868 'items' => $hold->itemnumber,
1870 substitute => { today => output_pref( { dt => dt_from_string, dateonly => 1 } ) },
1873 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.
1874 my $send_notification = sub {
1875 my ( $mtt, $letter_code ) = (@_);
1876 return unless defined $letter_code;
1877 $letter_params{letter_code} = $letter_code;
1878 $letter_params{message_transport_type} = $mtt;
1879 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1880 unless ($letter) {
1881 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1882 return;
1885 C4::Letters::EnqueueLetter( {
1886 letter => $letter,
1887 borrowernumber => $borrowernumber,
1888 from_address => $admin_email_address,
1889 message_transport_type => $mtt,
1890 } );
1893 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1894 next if (
1895 ( $mtt eq 'email' and not $to_address ) # No email address
1896 or ( $mtt eq 'sms' and not $borrower->{smsalertnumber} ) # No SMS number
1897 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1900 &$send_notification($mtt, $letter_code);
1901 $notification_sent++;
1903 #Making sure that a print notification is sent if no other transport types can be utilized.
1904 if (! $notification_sent) {
1905 &$send_notification('print', 'HOLD');
1910 =head2 _ShiftPriorityByDateAndPriority
1912 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1914 This increments the priority of all reserves after the one
1915 with either the lowest date after C<$reservedate>
1916 or the lowest priority after C<$priority>.
1918 It effectively makes room for a new reserve to be inserted with a certain
1919 priority, which is returned.
1921 This is most useful when the reservedate can be set by the user. It allows
1922 the new reserve to be placed before other reserves that have a later
1923 reservedate. Since priority also is set by the form in reserves/request.pl
1924 the sub accounts for that too.
1926 =cut
1928 sub _ShiftPriorityByDateAndPriority {
1929 my ( $biblio, $resdate, $new_priority ) = @_;
1931 my $dbh = C4::Context->dbh;
1932 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1933 my $sth = $dbh->prepare( $query );
1934 $sth->execute( $biblio, $resdate, $new_priority );
1935 my $min_priority = $sth->fetchrow;
1936 # if no such matches are found, $new_priority remains as original value
1937 $new_priority = $min_priority if ( $min_priority );
1939 # Shift the priority up by one; works in conjunction with the next SQL statement
1940 $query = "UPDATE reserves
1941 SET priority = priority+1
1942 WHERE biblionumber = ?
1943 AND borrowernumber = ?
1944 AND reservedate = ?
1945 AND found IS NULL";
1946 my $sth_update = $dbh->prepare( $query );
1948 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1949 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1950 $sth = $dbh->prepare( $query );
1951 $sth->execute( $new_priority, $biblio );
1952 while ( my $row = $sth->fetchrow_hashref ) {
1953 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1956 return $new_priority; # so the caller knows what priority they wind up receiving
1959 =head2 OPACItemHoldsAllowed
1961 OPACItemHoldsAllowed($item_record,$borrower_record);
1963 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
1964 if specific item holds are allowed, returns true if so.
1966 =cut
1968 sub OPACItemHoldsAllowed {
1969 my ($item,$borrower) = @_;
1971 my $branchcode = $item->{homebranch} or die "No homebranch";
1972 my $itype;
1973 my $dbh = C4::Context->dbh;
1974 if (C4::Context->preference('item-level_itypes')) {
1975 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1976 # When GetItem is fixed, we can remove this
1977 $itype = $item->{itype};
1979 else {
1980 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1981 my $sth = $dbh->prepare($query);
1982 $sth->execute($item->{biblioitemnumber});
1983 if (my $data = $sth->fetchrow_hashref()){
1984 $itype = $data->{itemtype};
1988 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
1989 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
1991 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
1993 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
1994 ORDER BY
1995 issuingrules.categorycode desc,
1996 issuingrules.itemtype desc,
1997 issuingrules.branchcode desc
1998 LIMIT 1";
1999 my $sth = $dbh->prepare($query);
2000 $sth->execute($borrower->{categorycode},$itype,$branchcode);
2001 my $data = $sth->fetchrow_hashref;
2002 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
2003 return '' if $opacitemholds eq 'N';
2004 return $opacitemholds;
2007 =head2 MoveReserve
2009 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
2011 Use when checking out an item to handle reserves
2012 If $cancelreserve boolean is set to true, it will remove existing reserve
2014 =cut
2016 sub MoveReserve {
2017 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
2019 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
2020 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
2021 return unless $res;
2023 my $biblionumber = $res->{biblionumber};
2025 if ($res->{borrowernumber} == $borrowernumber) {
2026 ModReserveFill($res);
2028 else {
2029 # warn "Reserved";
2030 # The item is reserved by someone else.
2031 # Find this item in the reserves
2033 my $borr_res;
2034 foreach (@$all_reserves) {
2035 $_->{'borrowernumber'} == $borrowernumber or next;
2036 $_->{'biblionumber'} == $biblionumber or next;
2038 $borr_res = $_;
2039 last;
2042 if ( $borr_res ) {
2043 # The item is reserved by the current patron
2044 ModReserveFill($borr_res);
2047 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
2048 RevertWaitingStatus({ itemnumber => $itemnumber });
2050 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
2051 CancelReserve( { reserve_id => $res->{'reserve_id'} } );
2056 =head2 MergeHolds
2058 MergeHolds($dbh,$to_biblio, $from_biblio);
2060 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
2062 =cut
2064 sub MergeHolds {
2065 my ( $dbh, $to_biblio, $from_biblio ) = @_;
2066 my $sth = $dbh->prepare(
2067 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
2069 $sth->execute($from_biblio);
2070 if ( my $data = $sth->fetchrow_hashref() ) {
2072 # holds exist on old record, if not we don't need to do anything
2073 $sth = $dbh->prepare(
2074 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
2075 $sth->execute( $to_biblio, $from_biblio );
2077 # Reorder by date
2078 # don't reorder those already waiting
2080 $sth = $dbh->prepare(
2081 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
2083 my $upd_sth = $dbh->prepare(
2084 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
2085 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
2087 $sth->execute( $to_biblio, 'W', 'T' );
2088 my $priority = 1;
2089 while ( my $reserve = $sth->fetchrow_hashref() ) {
2090 $upd_sth->execute(
2091 $priority, $to_biblio,
2092 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
2093 $reserve->{'itemnumber'}
2095 $priority++;
2100 =head2 RevertWaitingStatus
2102 RevertWaitingStatus({ itemnumber => $itemnumber });
2104 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
2106 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
2107 item level hold, even if it was only a bibliolevel hold to
2108 begin with. This is because we can no longer know if a hold
2109 was item-level or bib-level after a hold has been set to
2110 waiting status.
2112 =cut
2114 sub RevertWaitingStatus {
2115 my ( $params ) = @_;
2116 my $itemnumber = $params->{'itemnumber'};
2118 return unless ( $itemnumber );
2120 my $dbh = C4::Context->dbh;
2122 ## Get the waiting reserve we want to revert
2123 my $query = "
2124 SELECT * FROM reserves
2125 WHERE itemnumber = ?
2126 AND found IS NOT NULL
2128 my $sth = $dbh->prepare( $query );
2129 $sth->execute( $itemnumber );
2130 my $reserve = $sth->fetchrow_hashref();
2132 ## Increment the priority of all other non-waiting
2133 ## reserves for this bib record
2134 $query = "
2135 UPDATE reserves
2137 priority = priority + 1
2138 WHERE
2139 biblionumber = ?
2141 priority > 0
2143 $sth = $dbh->prepare( $query );
2144 $sth->execute( $reserve->{'biblionumber'} );
2146 ## Fix up the currently waiting reserve
2147 $query = "
2148 UPDATE reserves
2150 priority = 1,
2151 found = NULL,
2152 waitingdate = NULL
2153 WHERE
2154 reserve_id = ?
2156 $sth = $dbh->prepare( $query );
2157 $sth->execute( $reserve->{'reserve_id'} );
2158 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
2161 =head2 GetReserveId
2163 $reserve_id = GetReserveId({ biblionumber => $biblionumber, borrowernumber => $borrowernumber [, itemnumber => $itemnumber ] });
2165 Returnes the first reserve id that matches the given criteria
2167 =cut
2169 sub GetReserveId {
2170 my ( $params ) = @_;
2172 return unless ( ( $params->{'biblionumber'} || $params->{'itemnumber'} ) && $params->{'borrowernumber'} );
2174 foreach my $key ( keys %$params ) {
2175 delete $params->{$key} unless defined( $params->{$key} );
2178 my $hold = Koha::Holds->search( $params )->next();
2180 return unless $hold;
2182 return $hold->id();
2185 =head2 ReserveSlip
2187 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
2189 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2191 The letter code will be HOLD_SLIP, and the following tables are
2192 available within the slip:
2194 reserves
2195 branches
2196 borrowers
2197 biblio
2198 biblioitems
2199 items
2201 =cut
2203 sub ReserveSlip {
2204 my ($branch, $borrowernumber, $biblionumber) = @_;
2206 # return unless ( C4::Context->boolean_preference('printreserveslips') );
2208 my $reserve_id = GetReserveId({
2209 biblionumber => $biblionumber,
2210 borrowernumber => $borrowernumber
2211 }) or return;
2212 my $reserve = GetReserveInfo($reserve_id) or return;
2214 return C4::Letters::GetPreparedLetter (
2215 module => 'circulation',
2216 letter_code => 'HOLD_SLIP',
2217 branchcode => $branch,
2218 tables => {
2219 'reserves' => $reserve,
2220 'branches' => $reserve->{branchcode},
2221 'borrowers' => $reserve->{borrowernumber},
2222 'biblio' => $reserve->{biblionumber},
2223 'biblioitems' => $reserve->{biblionumber},
2224 'items' => $reserve->{itemnumber},
2229 =head2 GetReservesControlBranch
2231 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2233 Return the branchcode to be used to determine which reserves
2234 policy applies to a transaction.
2236 C<$item> is a hashref for an item. Only 'homebranch' is used.
2238 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2240 =cut
2242 sub GetReservesControlBranch {
2243 my ( $item, $borrower ) = @_;
2245 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2247 my $branchcode =
2248 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2249 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2250 : undef;
2252 return $branchcode;
2255 =head2 CalculatePriority
2257 my $p = CalculatePriority($biblionumber, $resdate);
2259 Calculate priority for a new reserve on biblionumber, placing it at
2260 the end of the line of all holds whose start date falls before
2261 the current system time and that are neither on the hold shelf
2262 or in transit.
2264 The reserve date parameter is optional; if it is supplied, the
2265 priority is based on the set of holds whose start date falls before
2266 the parameter value.
2268 After calculation of this priority, it is recommended to call
2269 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2270 AddReserves.
2272 =cut
2274 sub CalculatePriority {
2275 my ( $biblionumber, $resdate ) = @_;
2277 my $sql = q{
2278 SELECT COUNT(*) FROM reserves
2279 WHERE biblionumber = ?
2280 AND priority > 0
2281 AND (found IS NULL OR found = '')
2283 #skip found==W or found==T (waiting or transit holds)
2284 if( $resdate ) {
2285 $sql.= ' AND ( reservedate <= ? )';
2287 else {
2288 $sql.= ' AND ( reservedate < NOW() )';
2290 my $dbh = C4::Context->dbh();
2291 my @row = $dbh->selectrow_array(
2292 $sql,
2293 undef,
2294 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2297 return @row ? $row[0]+1 : 1;
2300 =head2 IsItemOnHoldAndFound
2302 my $bool = IsItemFoundHold( $itemnumber );
2304 Returns true if the item is currently on hold
2305 and that hold has a non-null found status ( W, T, etc. )
2307 =cut
2309 sub IsItemOnHoldAndFound {
2310 my ($itemnumber) = @_;
2312 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2314 my $found = $rs->count(
2316 itemnumber => $itemnumber,
2317 found => { '!=' => undef }
2321 return $found;
2324 =head2 GetMaxPatronHoldsForRecord
2326 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2328 For multiple holds on a given record for a given patron, the max
2329 number of record level holds that a patron can be placed is the highest
2330 value of the holds_per_record rule for each item if the record for that
2331 patron. This subroutine finds and returns the highest holds_per_record
2332 rule value for a given patron id and record id.
2334 =cut
2336 sub GetMaxPatronHoldsForRecord {
2337 my ( $borrowernumber, $biblionumber ) = @_;
2339 my $patron = Koha::Patrons->find($borrowernumber);
2340 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2342 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2344 my $categorycode = $patron->categorycode;
2345 my $branchcode;
2346 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2348 my $max = 0;
2349 foreach my $item (@items) {
2350 my $itemtype = $item->effective_itemtype();
2352 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2354 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2355 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2356 $max = $holds_per_record if $holds_per_record > $max;
2359 return $max;
2362 =head2 GetHoldRule
2364 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2366 Returns the matching hold related issuingrule fields for a given
2367 patron category, itemtype, and library.
2369 =cut
2371 sub GetHoldRule {
2372 my ( $categorycode, $itemtype, $branchcode ) = @_;
2374 my $dbh = C4::Context->dbh;
2376 my $sth = $dbh->prepare(
2378 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record
2379 FROM issuingrules
2380 WHERE (categorycode in (?,'*') )
2381 AND (itemtype IN (?,'*'))
2382 AND (branchcode IN (?,'*'))
2383 ORDER BY categorycode DESC,
2384 itemtype DESC,
2385 branchcode DESC
2389 $sth->execute( $categorycode, $itemtype, $branchcode );
2391 return $sth->fetchrow_hashref();
2394 =head1 AUTHOR
2396 Koha Development Team <http://koha-community.org/>
2398 =cut