Bug 21959: Add sponsor details
[koha.git] / C4 / Reserves.pm
blob503771e914e9786779956d4215ad4f2741fa7f9a
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 Modern::Perl;
26 use C4::Accounts;
27 use C4::Biblio;
28 use C4::Circulation;
29 use C4::Context;
30 use C4::Items;
31 use C4::Letters;
32 use C4::Log;
33 use C4::Members::Messaging;
34 use C4::Members;
35 use Koha::Account::Lines;
36 use Koha::Biblios;
37 use Koha::Calendar;
38 use Koha::CirculationRules;
39 use Koha::Database;
40 use Koha::DateUtils;
41 use Koha::Hold;
42 use Koha::Holds;
43 use Koha::IssuingRules;
44 use Koha::ItemTypes;
45 use Koha::Items;
46 use Koha::Libraries;
47 use Koha::Old::Hold;
48 use Koha::Patrons;
50 use Carp;
51 use Data::Dumper;
52 use List::MoreUtils qw( firstidx any );
54 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
56 =head1 NAME
58 C4::Reserves - Koha functions for dealing with reservation.
60 =head1 SYNOPSIS
62 use C4::Reserves;
64 =head1 DESCRIPTION
66 This modules provides somes functions to deal with reservations.
68 Reserves are stored in reserves table.
69 The following columns contains important values :
70 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
71 =0 : then the reserve is being dealed
72 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
73 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
74 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
75 F(inished) : the reserve has been completed, and is done
76 - itemnumber : empty : the reserve is still unaffected to an item
77 filled: the reserve is attached to an item
78 The complete workflow is :
79 ==== 1st use case ====
80 patron request a document, 1st available : P >0, F=NULL, I=NULL
81 a library having it run "transfertodo", and clic on the list
82 if there is no transfer to do, the reserve waiting
83 patron can pick it up P =0, F=W, I=filled
84 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
85 The pickup library receive the book, it check in P =0, F=W, I=filled
86 The patron borrow the book P =0, F=F, I=filled
88 ==== 2nd use case ====
89 patron requests a document, a given item,
90 If pickup is holding branch P =0, F=W, I=filled
91 If transfer needed, write in branchtransfer P =0, F=T, I=filled
92 The pickup library receive the book, it checks it in P =0, F=W, I=filled
93 The patron borrow the book P =0, F=F, I=filled
95 =head1 FUNCTIONS
97 =cut
99 BEGIN {
100 require Exporter;
101 @ISA = qw(Exporter);
102 @EXPORT = qw(
103 &AddReserve
105 &GetReserveStatus
107 &GetOtherReserves
109 &ModReserveFill
110 &ModReserveAffect
111 &ModReserve
112 &ModReserveStatus
113 &ModReserveCancelAll
114 &ModReserveMinusPriority
115 &MoveReserve
117 &CheckReserves
118 &CanBookBeReserved
119 &CanItemBeReserved
120 &CanReserveBeCanceledFromOpac
121 &CancelExpiredReserves
123 &AutoUnsuspendReserves
125 &IsAvailableForItemLevelRequest
127 &AlterPriority
128 &ToggleLowestPriority
130 &ReserveSlip
131 &ToggleSuspend
132 &SuspendAll
134 &GetReservesControlBranch
136 IsItemOnHoldAndFound
138 GetMaxPatronHoldsForRecord
140 @EXPORT_OK = qw( MergeHolds );
143 =head2 AddReserve
145 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
147 Adds reserve and generates HOLDPLACED message.
149 The following tables are available witin the HOLDPLACED message:
151 branches
152 borrowers
153 biblio
154 biblioitems
155 items
156 reserves
158 =cut
160 sub AddReserve {
161 my (
162 $branch, $borrowernumber, $biblionumber, $bibitems,
163 $priority, $resdate, $expdate, $notes,
164 $title, $checkitem, $found, $itemtype
165 ) = @_;
167 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
168 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
170 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
172 # if we have an item selectionned, and the pickup branch is the same as the holdingbranch
173 # of the document, we force the value $priority and $found .
174 if ( $checkitem and not C4::Context->preference('ReservesNeedReturns') ) {
175 my $item = Koha::Items->find( $checkitem ); # FIXME Prevent bad calls
177 if (
178 # If item is already checked out, it cannot be set waiting
179 !$item->onloan
181 # The item can't be waiting if it needs a transfer
182 && $item->holdingbranch eq $branch
184 # Similarly, if in transit it can't be waiting
185 && !$item->get_transfer
187 # If we can't hold damaged items, and it is damaged, it can't be waiting
188 && ( $item->damaged && C4::Context->preference('AllowHoldsOnDamagedItems') || !$item->damaged )
190 # Lastly, if this already has holds, we shouldn't make it waiting for the new hold
191 && !$item->current_holds->count )
193 $priority = 0;
194 $found = 'W';
198 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
200 # Make room in reserves for this before those of a later reserve date
201 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
204 my $waitingdate;
206 # If the reserv had the waiting status, we had the value of the resdate
207 if ( $found && $found eq 'W' ) {
208 $waitingdate = $resdate;
211 # Don't add itemtype limit if specific item is selected
212 $itemtype = undef if $checkitem;
214 # updates take place here
215 my $hold = Koha::Hold->new(
217 borrowernumber => $borrowernumber,
218 biblionumber => $biblionumber,
219 reservedate => $resdate,
220 branchcode => $branch,
221 priority => $priority,
222 reservenotes => $notes,
223 itemnumber => $checkitem,
224 found => $found,
225 waitingdate => $waitingdate,
226 expirationdate => $expdate,
227 itemtype => $itemtype,
228 item_level_hold => $checkitem ? 1 : 0,
230 )->store();
231 $hold->set_waiting() if $found && $found eq 'W';
233 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
234 if C4::Context->preference('HoldsLog');
236 my $reserve_id = $hold->id();
238 # add a reserve fee if needed
239 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
240 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
241 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
244 _FixPriority({ biblionumber => $biblionumber});
246 # Send e-mail to librarian if syspref is active
247 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
248 my $patron = Koha::Patrons->find( $borrowernumber );
249 my $library = $patron->library;
250 if ( my $letter = C4::Letters::GetPreparedLetter (
251 module => 'reserves',
252 letter_code => 'HOLDPLACED',
253 branchcode => $branch,
254 lang => $patron->lang,
255 tables => {
256 'branches' => $library->unblessed,
257 'borrowers' => $patron->unblessed,
258 'biblio' => $biblionumber,
259 'biblioitems' => $biblionumber,
260 'items' => $checkitem,
261 'reserves' => $hold->unblessed,
263 ) ) {
265 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
267 C4::Letters::EnqueueLetter(
268 { letter => $letter,
269 borrowernumber => $borrowernumber,
270 message_transport_type => 'email',
271 from_address => $admin_email_address,
272 to_address => $admin_email_address,
278 return $reserve_id;
281 =head2 CanBookBeReserved
283 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber, $branchcode)
284 if ($canReserve eq 'OK') { #We can reserve this Item! }
286 See CanItemBeReserved() for possible return values.
288 =cut
290 sub CanBookBeReserved{
291 my ($borrowernumber, $biblionumber, $pickup_branchcode) = @_;
293 my @itemnumbers = Koha::Items->search({ biblionumber => $biblionumber})->get_column("itemnumber");
294 #get items linked via host records
295 my @hostitems = get_hostitemnumbers_of($biblionumber);
296 if (@hostitems){
297 push (@itemnumbers, @hostitems);
300 my $canReserve = { status => '' };
301 foreach my $itemnumber (@itemnumbers) {
302 $canReserve = CanItemBeReserved( $borrowernumber, $itemnumber, $pickup_branchcode );
303 return { status => 'OK' } if $canReserve->{status} eq 'OK';
305 return $canReserve;
308 =head2 CanItemBeReserved
310 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber, $branchcode)
311 if ($canReserve->{status} eq 'OK') { #We can reserve this Item! }
313 @RETURNS { status => OK }, if the Item can be reserved.
314 { status => ageRestricted }, if the Item is age restricted for this borrower.
315 { status => damaged }, if the Item is damaged.
316 { status => cannotReserveFromOtherBranches }, if syspref 'canreservefromotherbranches' is OK.
317 { status => branchNotInHoldGroup }, if borrower home library is not in hold group, and holds are only allowed from hold groups.
318 { status => tooManyReserves, limit => $limit }, if the borrower has exceeded their maximum reserve amount.
319 { status => notReservable }, if holds on this item are not allowed
320 { status => libraryNotFound }, if given branchcode is not an existing library
321 { status => libraryNotPickupLocation }, if given branchcode is not configured to be a pickup location
322 { status => cannotBeTransferred }, if branch transfer limit applies on given item and branchcode
323 { status => pickupNotInHoldGroup }, pickup location is not in hold group, and pickup locations are only allowed from hold groups.
325 =cut
327 sub CanItemBeReserved {
328 my ( $borrowernumber, $itemnumber, $pickup_branchcode ) = @_;
330 my $dbh = C4::Context->dbh;
331 my $ruleitemtype; # itemtype of the matching issuing rule
332 my $allowedreserves = 0; # Total number of holds allowed across all records
333 my $holds_per_record = 1; # Total number of holds allowed for this one given record
334 my $holds_per_day; # Default to unlimited
336 # we retrieve borrowers and items informations #
337 # item->{itype} will come for biblioitems if necessery
338 my $item = Koha::Items->find($itemnumber);
339 my $biblio = $item->biblio;
340 my $patron = Koha::Patrons->find( $borrowernumber );
341 my $borrower = $patron->unblessed;
343 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
344 return { status =>'damaged' }
345 if ( $item->damaged
346 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
348 # Check for the age restriction
349 my ( $ageRestriction, $daysToAgeRestriction ) =
350 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
351 return { status => 'ageRestricted' } if $daysToAgeRestriction && $daysToAgeRestriction > 0;
353 # Check that the patron doesn't have an item level hold on this item already
354 return { status =>'itemAlreadyOnHold' }
355 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
357 my $controlbranch = C4::Context->preference('ReservesControlBranch');
359 my $querycount = q{
360 SELECT count(*) AS count
361 FROM reserves
362 LEFT JOIN items USING (itemnumber)
363 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
364 LEFT JOIN borrowers USING (borrowernumber)
365 WHERE borrowernumber = ?
368 my $branchcode = "";
369 my $branchfield = "reserves.branchcode";
371 if ( $controlbranch eq "ItemHomeLibrary" ) {
372 $branchfield = "items.homebranch";
373 $branchcode = $item->homebranch;
375 elsif ( $controlbranch eq "PatronLibrary" ) {
376 $branchfield = "borrowers.branchcode";
377 $branchcode = $borrower->{branchcode};
380 # we retrieve rights
381 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->effective_itemtype, $branchcode ) ) {
382 $ruleitemtype = $rights->{itemtype};
383 $allowedreserves = $rights->{reservesallowed};
384 $holds_per_record = $rights->{holds_per_record};
385 $holds_per_day = $rights->{holds_per_day};
387 else {
388 $ruleitemtype = '*';
391 my $holds = Koha::Holds->search(
393 borrowernumber => $borrowernumber,
394 biblionumber => $item->biblionumber,
395 found => undef, # Found holds don't count against a patron's holds limit
398 if ( $holds->count() >= $holds_per_record ) {
399 return { status => "tooManyHoldsForThisRecord", limit => $holds_per_record };
402 my $today_holds = Koha::Holds->search({
403 borrowernumber => $borrowernumber,
404 reservedate => dt_from_string->date
407 if ( defined $holds_per_day &&
408 ( ( $holds_per_day > 0 && $today_holds->count() >= $holds_per_day )
409 or ( $holds_per_day == 0 ) )
411 return { status => 'tooManyReservesToday', limit => $holds_per_day };
414 # we retrieve count
416 $querycount .= "AND ( $branchfield = ? OR $branchfield IS NULL )";
418 # If using item-level itypes, fall back to the record
419 # level itemtype if the hold has no associated item
420 $querycount .=
421 C4::Context->preference('item-level_itypes')
422 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
423 : " AND biblioitems.itemtype = ?"
424 if ( $ruleitemtype ne "*" );
426 my $sthcount = $dbh->prepare($querycount);
428 if ( $ruleitemtype eq "*" ) {
429 $sthcount->execute( $borrowernumber, $branchcode );
431 else {
432 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
435 my $reservecount = "0";
436 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
437 $reservecount = $rowcount->{count};
440 # we check if it's ok or not
441 if ( $reservecount >= $allowedreserves ) {
442 return { status => 'tooManyReserves', limit => $allowedreserves };
445 # Now we need to check hold limits by patron category
446 my $rule = Koha::CirculationRules->get_effective_rule(
448 categorycode => $borrower->{categorycode},
449 branchcode => $branchcode,
450 rule_name => 'max_holds',
453 if ( $rule && defined( $rule->rule_value ) && $rule->rule_value ne '' ) {
454 my $total_holds_count = Koha::Holds->search(
456 borrowernumber => $borrower->{borrowernumber}
458 )->count();
460 return { status => 'tooManyReserves', limit => $rule->rule_value} if $total_holds_count >= $rule->rule_value;
463 my $reserves_control_branch =
464 GetReservesControlBranch( $item->unblessed(), $borrower );
465 my $branchitemrule =
466 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype ); # FIXME Should not be item->effective_itemtype?
468 if ( $branchitemrule->{holdallowed} == 0 ) {
469 return { status => 'notReservable' };
472 if ( $branchitemrule->{holdallowed} == 1
473 && $borrower->{branchcode} ne $item->homebranch )
475 return { status => 'cannotReserveFromOtherBranches' };
478 my $item_library = Koha::Libraries->find( {branchcode => $item->homebranch} );
479 if ( $branchitemrule->{holdallowed} == 3) {
480 if($borrower->{branchcode} ne $item->homebranch && !$item_library->validate_hold_sibling( {branchcode => $borrower->{branchcode}} )) {
481 return { status => 'branchNotInHoldGroup' };
485 # If reservecount is ok, we check item branch if IndependentBranches is ON
486 # and canreservefromotherbranches is OFF
487 if ( C4::Context->preference('IndependentBranches')
488 and !C4::Context->preference('canreservefromotherbranches') )
490 if ( $item->homebranch ne $borrower->{branchcode} ) {
491 return { status => 'cannotReserveFromOtherBranches' };
495 if ($pickup_branchcode) {
496 my $destination = Koha::Libraries->find({
497 branchcode => $pickup_branchcode,
500 unless ($destination) {
501 return { status => 'libraryNotFound' };
503 unless ($destination->pickup_location) {
504 return { status => 'libraryNotPickupLocation' };
506 unless ($item->can_be_transferred({ to => $destination })) {
507 return { status => 'cannotBeTransferred' };
509 unless ($branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $item_library->validate_hold_sibling( {branchcode => $pickup_branchcode} )) {
510 return { status => 'pickupNotInHoldGroup' };
512 unless ($branchitemrule->{hold_fulfillment_policy} ne 'patrongroup' || Koha::Libraries->find({branchcode => $borrower->{branchcode}})->validate_hold_sibling({branchcode => $pickup_branchcode})) {
513 return { status => 'pickupNotInHoldGroup' };
517 return { status => 'OK' };
520 =head2 CanReserveBeCanceledFromOpac
522 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
524 returns 1 if reserve can be cancelled by user from OPAC.
525 First check if reserve belongs to user, next checks if reserve is not in
526 transfer or waiting status
528 =cut
530 sub CanReserveBeCanceledFromOpac {
531 my ($reserve_id, $borrowernumber) = @_;
533 return unless $reserve_id and $borrowernumber;
534 my $reserve = Koha::Holds->find($reserve_id);
536 return 0 unless $reserve->borrowernumber == $borrowernumber;
537 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
539 return 1;
543 =head2 GetOtherReserves
545 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
547 Check queued list of this document and check if this document must be transferred
549 =cut
551 sub GetOtherReserves {
552 my ($itemnumber) = @_;
553 my $messages;
554 my $nextreservinfo;
555 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
556 if ($checkreserves) {
557 my $item = Koha::Items->find($itemnumber);
558 if ( $item->holdingbranch ne $checkreserves->{'branchcode'} ) {
559 $messages->{'transfert'} = $checkreserves->{'branchcode'};
560 #minus priorities of others reservs
561 ModReserveMinusPriority(
562 $itemnumber,
563 $checkreserves->{'reserve_id'},
566 #launch the subroutine dotransfer
567 C4::Items::ModItemTransfer(
568 $itemnumber,
569 $item->holdingbranch,
570 $checkreserves->{'branchcode'}
575 #step 2b : case of a reservation on the same branch, set the waiting status
576 else {
577 $messages->{'waiting'} = 1;
578 ModReserveMinusPriority(
579 $itemnumber,
580 $checkreserves->{'reserve_id'},
582 ModReserveStatus($itemnumber,'W');
585 $nextreservinfo = $checkreserves->{'borrowernumber'};
588 return ( $messages, $nextreservinfo );
591 =head2 ChargeReserveFee
593 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
595 Charge the fee for a reserve (if $fee > 0)
597 =cut
599 sub ChargeReserveFee {
600 my ( $borrowernumber, $fee, $title ) = @_;
601 return if !$fee || $fee == 0; # the last test is needed to include 0.00
602 Koha::Account->new( { patron_id => $borrowernumber } )->add_debit(
604 amount => $fee,
605 description => $title,
606 note => undef,
607 user_id => C4::Context->userenv ? C4::Context->userenv->{'number'} : undef,
608 library_id => C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef,
609 interface => C4::Context->interface,
610 invoice_type => undef,
611 type => 'RESERVE',
612 item_id => undef
617 =head2 GetReserveFee
619 $fee = GetReserveFee( $borrowernumber, $biblionumber );
621 Calculate the fee for a reserve (if applicable).
623 =cut
625 sub GetReserveFee {
626 my ( $borrowernumber, $biblionumber ) = @_;
627 my $borquery = qq{
628 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
630 my $issue_qry = qq{
631 SELECT COUNT(*) FROM items
632 LEFT JOIN issues USING (itemnumber)
633 WHERE items.biblionumber=? AND issues.issue_id IS NULL
635 my $holds_qry = qq{
636 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
639 my $dbh = C4::Context->dbh;
640 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
641 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
642 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
643 # This is a reconstruction of the old code:
644 # Compare number of items with items issued, and optionally check holds
645 # If not all items are issued and there are no holds: charge no fee
646 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
647 my ( $notissued, $reserved );
648 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
649 ( $biblionumber ) );
650 if( $notissued ) {
651 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
652 ( $biblionumber, $borrowernumber ) );
653 $fee = 0 if $reserved == 0;
656 return $fee;
659 =head2 GetReserveStatus
661 $reservestatus = GetReserveStatus($itemnumber);
663 Takes an itemnumber and returns the status of the reserve placed on it.
664 If several reserves exist, the reserve with the lower priority is given.
666 =cut
668 ## FIXME: I don't think this does what it thinks it does.
669 ## It only ever checks the first reserve result, even though
670 ## multiple reserves for that bib can have the itemnumber set
671 ## the sub is only used once in the codebase.
672 sub GetReserveStatus {
673 my ($itemnumber) = @_;
675 my $dbh = C4::Context->dbh;
677 my ($sth, $found, $priority);
678 if ( $itemnumber ) {
679 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
680 $sth->execute($itemnumber);
681 ($found, $priority) = $sth->fetchrow_array;
684 if(defined $found) {
685 return 'Waiting' if $found eq 'W' and $priority == 0;
686 return 'Finished' if $found eq 'F';
689 return 'Reserved' if $priority > 0;
691 return ''; # empty string here will remove need for checking undef, or less log lines
694 =head2 CheckReserves
696 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber);
697 ($status, $matched_reserve, $possible_reserves) = &CheckReserves(undef, $barcode);
698 ($status, $matched_reserve, $possible_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
700 Find a book in the reserves.
702 C<$itemnumber> is the book's item number.
703 C<$lookahead> is the number of days to look in advance for future reserves.
705 As I understand it, C<&CheckReserves> looks for the given item in the
706 reserves. If it is found, that's a match, and C<$status> is set to
707 C<Waiting>.
709 Otherwise, it finds the most important item in the reserves with the
710 same biblio number as this book (I'm not clear on this) and returns it
711 with C<$status> set to C<Reserved>.
713 C<&CheckReserves> returns a two-element list:
715 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
717 C<$reserve> is the reserve item that matched. It is a
718 reference-to-hash whose keys are mostly the fields of the reserves
719 table in the Koha database.
721 =cut
723 sub CheckReserves {
724 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
725 my $dbh = C4::Context->dbh;
726 my $sth;
727 my $select;
728 if (C4::Context->preference('item-level_itypes')){
729 $select = "
730 SELECT items.biblionumber,
731 items.biblioitemnumber,
732 itemtypes.notforloan,
733 items.notforloan AS itemnotforloan,
734 items.itemnumber,
735 items.damaged,
736 items.homebranch,
737 items.holdingbranch
738 FROM items
739 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
740 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
743 else {
744 $select = "
745 SELECT items.biblionumber,
746 items.biblioitemnumber,
747 itemtypes.notforloan,
748 items.notforloan AS itemnotforloan,
749 items.itemnumber,
750 items.damaged,
751 items.homebranch,
752 items.holdingbranch
753 FROM items
754 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
755 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
759 if ($item) {
760 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
761 $sth->execute($item);
763 else {
764 $sth = $dbh->prepare("$select WHERE barcode = ?");
765 $sth->execute($barcode);
767 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
768 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
769 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
771 return unless $itemnumber; # bail if we got nothing.
772 # if item is not for loan it cannot be reserved either.....
773 # except where items.notforloan < 0 : This indicates the item is holdable.
774 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
776 # Find this item in the reserves
777 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
779 # $priority and $highest are used to find the most important item
780 # in the list returned by &_Findgroupreserve. (The lower $priority,
781 # the more important the item.)
782 # $highest is the most important item we've seen so far.
783 my $highest;
784 if (scalar @reserves) {
785 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
786 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
787 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
789 my $priority = 10000000;
790 foreach my $res (@reserves) {
791 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
792 if ($res->{'found'} eq 'W') {
793 return ( "Waiting", $res, \@reserves ); # Found it, it is waiting
794 } else {
795 return ( "Reserved", $res, \@reserves ); # Found determinated hold, e. g. the tranferred one
797 } else {
798 my $patron;
799 my $item;
800 my $local_hold_match;
802 if ($LocalHoldsPriority) {
803 $patron = Koha::Patrons->find( $res->{borrowernumber} );
804 $item = Koha::Items->find($itemnumber);
806 my $local_holds_priority_item_branchcode =
807 $item->$LocalHoldsPriorityItemControl;
808 my $local_holds_priority_patron_branchcode =
809 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
810 ? $res->{branchcode}
811 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
812 ? $patron->branchcode
813 : undef;
814 $local_hold_match =
815 $local_holds_priority_item_branchcode eq
816 $local_holds_priority_patron_branchcode;
819 # See if this item is more important than what we've got so far
820 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
821 $item ||= Koha::Items->find($itemnumber);
822 next if $res->{itemtype} && $res->{itemtype} ne $item->effective_itemtype;
823 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
824 my $branch = GetReservesControlBranch( $item->unblessed, $patron->unblessed );
825 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$item->effective_itemtype);
826 next if ($branchitemrule->{'holdallowed'} == 0);
827 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
828 my $library = Koha::Libraries->find({branchcode=>$item->homebranch});
829 next if (($branchitemrule->{'holdallowed'} == 3) && (!$library->validate_hold_sibling({branchcode => $patron->branchcode}) ));
830 my $hold_fulfillment_policy = $branchitemrule->{hold_fulfillment_policy};
831 next if ( ($hold_fulfillment_policy eq 'holdgroup') && (!$library->validate_hold_sibling({branchcode => $res->{branchcode}})) );
832 next if ( ($hold_fulfillment_policy eq 'homebranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
833 next if ( ($hold_fulfillment_policy eq 'holdingbranch') && ($res->{branchcode} ne $item->$hold_fulfillment_policy) );
834 next unless $item->can_be_transferred( { to => scalar Koha::Libraries->find( $res->{branchcode} ) } );
835 $priority = $res->{'priority'};
836 $highest = $res;
837 last if $local_hold_match;
843 # If we get this far, then no exact match was found.
844 # We return the most important (i.e. next) reservation.
845 if ($highest) {
846 $highest->{'itemnumber'} = $item;
847 return ( "Reserved", $highest, \@reserves );
850 return ( '' );
853 =head2 CancelExpiredReserves
855 CancelExpiredReserves();
857 Cancels all reserves with an expiration date from before today.
859 =cut
861 sub CancelExpiredReserves {
862 my $today = dt_from_string();
863 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
864 my $expireWaiting = C4::Context->preference('ExpireReservesMaxPickUpDelay');
866 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
867 my $params = { expirationdate => { '<', $dtf->format_date($today) } };
868 $params->{found} = [ { '!=', 'W' }, undef ] unless $expireWaiting;
870 # FIXME To move to Koha::Holds->search_expired (?)
871 my $holds = Koha::Holds->search( $params );
873 while ( my $hold = $holds->next ) {
874 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
876 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
878 my $cancel_params = {};
879 if ( $hold->found eq 'W' ) {
880 $cancel_params->{charge_cancel_fee} = 1;
882 $hold->cancel( $cancel_params );
886 =head2 AutoUnsuspendReserves
888 AutoUnsuspendReserves();
890 Unsuspends all suspended reserves with a suspend_until date from before today.
892 =cut
894 sub AutoUnsuspendReserves {
895 my $today = dt_from_string();
897 my @holds = Koha::Holds->search( { suspend_until => { '<=' => $today->ymd() } } );
899 map { $_->resume() } @holds;
902 =head2 ModReserve
904 ModReserve({ rank => $rank,
905 reserve_id => $reserve_id,
906 branchcode => $branchcode
907 [, itemnumber => $itemnumber ]
908 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
911 Change a hold request's priority or cancel it.
913 C<$rank> specifies the effect of the change. If C<$rank>
914 is 'W' or 'n', nothing happens. This corresponds to leaving a
915 request alone when changing its priority in the holds queue
916 for a bib.
918 If C<$rank> is 'del', the hold request is cancelled.
920 If C<$rank> is an integer greater than zero, the priority of
921 the request is set to that value. Since priority != 0 means
922 that the item is not waiting on the hold shelf, setting the
923 priority to a non-zero value also sets the request's found
924 status and waiting date to NULL.
926 The optional C<$itemnumber> parameter is used only when
927 C<$rank> is a non-zero integer; if supplied, the itemnumber
928 of the hold request is set accordingly; if omitted, the itemnumber
929 is cleared.
931 B<FIXME:> Note that the forgoing can have the effect of causing
932 item-level hold requests to turn into title-level requests. This
933 will be fixed once reserves has separate columns for requested
934 itemnumber and supplying itemnumber.
936 =cut
938 sub ModReserve {
939 my ( $params ) = @_;
941 my $rank = $params->{'rank'};
942 my $reserve_id = $params->{'reserve_id'};
943 my $branchcode = $params->{'branchcode'};
944 my $itemnumber = $params->{'itemnumber'};
945 my $suspend_until = $params->{'suspend_until'};
946 my $borrowernumber = $params->{'borrowernumber'};
947 my $biblionumber = $params->{'biblionumber'};
949 return if $rank eq "W";
950 return if $rank eq "n";
952 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
954 my $hold;
955 unless ( $reserve_id ) {
956 my $holds = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
957 return unless $holds->count; # FIXME Should raise an exception
958 $hold = $holds->next;
959 $reserve_id = $hold->reserve_id;
962 $hold ||= Koha::Holds->find($reserve_id);
964 if ( $rank eq "del" ) {
965 $hold->cancel;
967 elsif ($rank =~ /^\d+/ and $rank > 0) {
968 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
969 if C4::Context->preference('HoldsLog');
971 my $properties = {
972 priority => $rank,
973 branchcode => $branchcode,
974 itemnumber => $itemnumber,
975 found => undef,
976 waitingdate => undef
978 if (exists $params->{reservedate}) {
979 $properties->{reservedate} = $params->{reservedate} || undef;
981 if (exists $params->{expirationdate}) {
982 $properties->{expirationdate} = $params->{expirationdate} || undef;
985 $hold->set($properties)->store();
987 if ( defined( $suspend_until ) ) {
988 if ( $suspend_until ) {
989 $suspend_until = eval { dt_from_string( $suspend_until ) };
990 $hold->suspend_hold( $suspend_until );
991 } else {
992 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
993 # If the hold is not suspended, this does nothing.
994 $hold->set( { suspend_until => undef } )->store();
998 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
1002 =head2 ModReserveFill
1004 &ModReserveFill($reserve);
1006 Fill a reserve. If I understand this correctly, this means that the
1007 reserved book has been found and given to the patron who reserved it.
1009 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
1010 whose keys are fields from the reserves table in the Koha database.
1012 =cut
1014 sub ModReserveFill {
1015 my ($res) = @_;
1016 my $reserve_id = $res->{'reserve_id'};
1018 my $hold = Koha::Holds->find($reserve_id);
1019 # get the priority on this record....
1020 my $priority = $hold->priority;
1022 # update the hold statuses, no need to store it though, we will be deleting it anyway
1023 $hold->set(
1025 found => 'F',
1026 priority => 0,
1030 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
1031 Koha::Old::Hold->new( $hold->unblessed() )->store();
1033 $hold->delete();
1035 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
1036 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
1037 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
1040 # now fix the priority on the others (if the priority wasn't
1041 # already sorted!)....
1042 unless ( $priority == 0 ) {
1043 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
1047 =head2 ModReserveStatus
1049 &ModReserveStatus($itemnumber, $newstatus);
1051 Update the reserve status for the active (priority=0) reserve.
1053 $itemnumber is the itemnumber the reserve is on
1055 $newstatus is the new status.
1057 =cut
1059 sub ModReserveStatus {
1061 #first : check if we have a reservation for this item .
1062 my ($itemnumber, $newstatus) = @_;
1063 my $dbh = C4::Context->dbh;
1065 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
1066 my $sth_set = $dbh->prepare($query);
1067 $sth_set->execute( $newstatus, $itemnumber );
1069 my $item = Koha::Items->find($itemnumber);
1070 if ( $item->location && $item->location eq 'CART'
1071 && ( !$item->permanent_location || $item->permanent_location ne 'CART' )
1072 && $newstatus ) {
1073 CartToShelf( $itemnumber );
1077 =head2 ModReserveAffect
1079 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1081 This function affect an item and a status for a given reserve, either fetched directly
1082 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1083 is given, only first reserve returned is affected, which is ok for anything but
1084 multi-item holds.
1086 if $transferToDo is not set, then the status is set to "Waiting" as well.
1087 otherwise, a transfer is on the way, and the end of the transfer will
1088 take care of the waiting status
1090 =cut
1092 sub ModReserveAffect {
1093 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1094 my $dbh = C4::Context->dbh;
1096 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1097 # attached to $itemnumber
1098 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1099 $sth->execute($itemnumber);
1100 my ($biblionumber) = $sth->fetchrow;
1102 # get request - need to find out if item is already
1103 # waiting in order to not send duplicate hold filled notifications
1105 my $hold;
1106 # Find hold by id if we have it
1107 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1108 # Find item level hold for this item if there is one
1109 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1110 # Find record level hold if there is no item level hold
1111 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1113 return unless $hold;
1115 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1117 $hold->itemnumber($itemnumber);
1118 $hold->set_waiting($transferToDo);
1120 _koha_notify_reserve( $hold->reserve_id )
1121 if ( !$transferToDo && !$already_on_shelf );
1123 _FixPriority( { biblionumber => $biblionumber } );
1124 my $item = Koha::Items->find($itemnumber);
1125 if ( $item->location && $item->location eq 'CART'
1126 && ( !$item->permanent_location || $item->permanent_location ne 'CART' ) ) {
1127 CartToShelf( $itemnumber );
1130 return;
1133 =head2 ModReserveCancelAll
1135 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1137 function to cancel reserv,check other reserves, and transfer document if it's necessary
1139 =cut
1141 sub ModReserveCancelAll {
1142 my $messages;
1143 my $nextreservinfo;
1144 my ( $itemnumber, $borrowernumber ) = @_;
1146 #step 1 : cancel the reservation
1147 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1148 return unless $holds->count;
1149 $holds->next->cancel;
1151 #step 2 launch the subroutine of the others reserves
1152 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1154 return ( $messages, $nextreservinfo );
1157 =head2 ModReserveMinusPriority
1159 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1161 Reduce the values of queued list
1163 =cut
1165 sub ModReserveMinusPriority {
1166 my ( $itemnumber, $reserve_id ) = @_;
1168 #first step update the value of the first person on reserv
1169 my $dbh = C4::Context->dbh;
1170 my $query = "
1171 UPDATE reserves
1172 SET priority = 0 , itemnumber = ?
1173 WHERE reserve_id = ?
1175 my $sth_upd = $dbh->prepare($query);
1176 $sth_upd->execute( $itemnumber, $reserve_id );
1177 # second step update all others reserves
1178 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1181 =head2 IsAvailableForItemLevelRequest
1183 my $is_available = IsAvailableForItemLevelRequest( $item_record, $borrower_record, $pickup_branchcode );
1185 Checks whether a given item record is available for an
1186 item-level hold request. An item is available if
1188 * it is not lost AND
1189 * it is not damaged AND
1190 * it is not withdrawn AND
1191 * a waiting or in transit reserve is placed on
1192 * does not have a not for loan value > 0
1194 Need to check the issuingrules onshelfholds column,
1195 if this is set items on the shelf can be placed on hold
1197 Note that IsAvailableForItemLevelRequest() does not
1198 check if the staff operator is authorized to place
1199 a request on the item - in particular,
1200 this routine does not check IndependentBranches
1201 and canreservefromotherbranches.
1203 =cut
1205 sub IsAvailableForItemLevelRequest {
1206 my ( $item, $patron, $pickup_branchcode ) = @_;
1208 my $dbh = C4::Context->dbh;
1209 # must check the notforloan setting of the itemtype
1210 # FIXME - a lot of places in the code do this
1211 # or something similar - need to be
1212 # consolidated
1213 my $itemtype = $item->effective_itemtype;
1214 my $notforloan_per_itemtype = Koha::ItemTypes->find($itemtype)->notforloan;
1216 return 0 if
1217 $notforloan_per_itemtype ||
1218 $item->itemlost ||
1219 $item->notforloan > 0 ||
1220 $item->withdrawn ||
1221 ($item->damaged && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1223 my $on_shelf_holds = Koha::IssuingRules->get_onshelfholds_policy( { item => $item, patron => $patron } );
1225 if ($pickup_branchcode) {
1226 my $destination = Koha::Libraries->find($pickup_branchcode);
1227 return 0 unless $destination;
1228 return 0 unless $destination->pickup_location;
1229 return 0 unless $item->can_be_transferred( { to => $destination } );
1230 my $reserves_control_branch =
1231 GetReservesControlBranch( $item->unblessed(), $patron->unblessed() );
1232 my $branchitemrule =
1233 C4::Circulation::GetBranchItemRule( $reserves_control_branch, $item->itype );
1234 my $home_library = Koka::Libraries->find( {branchcode => $item->homebranch} );
1235 return 0 unless $branchitemrule->{hold_fulfillment_policy} ne 'holdgroup' || $home_library->validate_hold_sibling( {branchcode => $pickup_branchcode} );
1238 if ( $on_shelf_holds == 1 ) {
1239 return 1;
1240 } elsif ( $on_shelf_holds == 2 ) {
1241 my @items =
1242 Koha::Items->search( { biblionumber => $item->biblionumber } );
1244 my $any_available = 0;
1246 foreach my $i (@items) {
1247 my $reserves_control_branch = GetReservesControlBranch( $i->unblessed(), $patron->unblessed );
1248 my $branchitemrule = C4::Circulation::GetBranchItemRule( $reserves_control_branch, $i->itype );
1249 my $item_library = Koha::Libraries->find( {branchcode => $i->homebranch} );
1252 $any_available = 1
1253 unless $i->itemlost
1254 || $i->notforloan > 0
1255 || $i->withdrawn
1256 || $i->onloan
1257 || IsItemOnHoldAndFound( $i->id )
1258 || ( $i->damaged
1259 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1260 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan
1261 || $branchitemrule->{holdallowed} == 1 && $patron->branchcode ne $i->homebranch
1262 || $branchitemrule->{holdallowed} == 3 && !$item_library->validate_hold_sibling( {branchcode => $patron->branchcode} );
1265 return $any_available ? 0 : 1;
1266 } else { # on_shelf_holds == 0 "If any unavailable" (the description is rather cryptic and could still be improved)
1267 return $item->onloan || IsItemOnHoldAndFound( $item->itemnumber );
1271 sub _get_itype {
1272 my $item = shift;
1274 my $itype;
1275 if (C4::Context->preference('item-level_itypes')) {
1276 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1277 # When GetItem is fixed, we can remove this
1278 $itype = $item->{itype};
1280 else {
1281 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1282 # So if we already have a biblioitems join when calling this function,
1283 # we don't need to access the database again
1284 $itype = $item->{itemtype};
1286 unless ($itype) {
1287 my $dbh = C4::Context->dbh;
1288 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1289 my $sth = $dbh->prepare($query);
1290 $sth->execute($item->{biblioitemnumber});
1291 if (my $data = $sth->fetchrow_hashref()){
1292 $itype = $data->{itemtype};
1295 return $itype;
1298 =head2 AlterPriority
1300 AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
1302 This function changes a reserve's priority up, down, to the top, or to the bottom.
1303 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1305 =cut
1307 sub AlterPriority {
1308 my ( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority ) = @_;
1310 my $hold = Koha::Holds->find( $reserve_id );
1311 return unless $hold;
1313 if ( $hold->cancellationdate ) {
1314 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1315 return;
1318 if ( $where eq 'up' ) {
1319 return unless $prev_priority;
1320 _FixPriority({ reserve_id => $reserve_id, rank => $prev_priority })
1321 } elsif ( $where eq 'down' ) {
1322 return unless $next_priority;
1323 _FixPriority({ reserve_id => $reserve_id, rank => $next_priority })
1324 } elsif ( $where eq 'top' ) {
1325 _FixPriority({ reserve_id => $reserve_id, rank => $first_priority })
1326 } elsif ( $where eq 'bottom' ) {
1327 _FixPriority({ reserve_id => $reserve_id, rank => $last_priority });
1330 # FIXME Should return the new priority
1333 =head2 ToggleLowestPriority
1335 ToggleLowestPriority( $borrowernumber, $biblionumber );
1337 This function sets the lowestPriority field to true if is false, and false if it is true.
1339 =cut
1341 sub ToggleLowestPriority {
1342 my ( $reserve_id ) = @_;
1344 my $dbh = C4::Context->dbh;
1346 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1347 $sth->execute( $reserve_id );
1349 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1352 =head2 ToggleSuspend
1354 ToggleSuspend( $reserve_id );
1356 This function sets the suspend field to true if is false, and false if it is true.
1357 If the reserve is currently suspended with a suspend_until date, that date will
1358 be cleared when it is unsuspended.
1360 =cut
1362 sub ToggleSuspend {
1363 my ( $reserve_id, $suspend_until ) = @_;
1365 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1367 my $hold = Koha::Holds->find( $reserve_id );
1369 if ( $hold->is_suspended ) {
1370 $hold->resume()
1371 } else {
1372 $hold->suspend_hold( $suspend_until );
1376 =head2 SuspendAll
1378 SuspendAll(
1379 borrowernumber => $borrowernumber,
1380 [ biblionumber => $biblionumber, ]
1381 [ suspend_until => $suspend_until, ]
1382 [ suspend => $suspend ]
1385 This function accepts a set of hash keys as its parameters.
1386 It requires either borrowernumber or biblionumber, or both.
1388 suspend_until is wholly optional.
1390 =cut
1392 sub SuspendAll {
1393 my %params = @_;
1395 my $borrowernumber = $params{'borrowernumber'} || undef;
1396 my $biblionumber = $params{'biblionumber'} || undef;
1397 my $suspend_until = $params{'suspend_until'} || undef;
1398 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1400 $suspend_until = eval { dt_from_string($suspend_until) }
1401 if ( defined($suspend_until) );
1403 return unless ( $borrowernumber || $biblionumber );
1405 my $params;
1406 $params->{found} = undef;
1407 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1408 $params->{biblionumber} = $biblionumber if $biblionumber;
1410 my @holds = Koha::Holds->search($params);
1412 if ($suspend) {
1413 map { $_->suspend_hold($suspend_until) } @holds;
1415 else {
1416 map { $_->resume() } @holds;
1421 =head2 _FixPriority
1423 _FixPriority({
1424 reserve_id => $reserve_id,
1425 [rank => $rank,]
1426 [ignoreSetLowestRank => $ignoreSetLowestRank]
1431 _FixPriority({ biblionumber => $biblionumber});
1433 This routine adjusts the priority of a hold request and holds
1434 on the same bib.
1436 In the first form, where a reserve_id is passed, the priority of the
1437 hold is set to supplied rank, and other holds for that bib are adjusted
1438 accordingly. If the rank is "del", the hold is cancelled. If no rank
1439 is supplied, all of the holds on that bib have their priority adjusted
1440 as if the second form had been used.
1442 In the second form, where a biblionumber is passed, the holds on that
1443 bib (that are not captured) are sorted in order of increasing priority,
1444 then have reserves.priority set so that the first non-captured hold
1445 has its priority set to 1, the second non-captured hold has its priority
1446 set to 2, and so forth.
1448 In both cases, holds that have the lowestPriority flag on are have their
1449 priority adjusted to ensure that they remain at the end of the line.
1451 Note that the ignoreSetLowestRank parameter is meant to be used only
1452 when _FixPriority calls itself.
1454 =cut
1456 sub _FixPriority {
1457 my ( $params ) = @_;
1458 my $reserve_id = $params->{reserve_id};
1459 my $rank = $params->{rank} // '';
1460 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1461 my $biblionumber = $params->{biblionumber};
1463 my $dbh = C4::Context->dbh;
1465 my $hold;
1466 if ( $reserve_id ) {
1467 $hold = Koha::Holds->find( $reserve_id );
1468 return unless $hold;
1471 unless ( $biblionumber ) { # FIXME This is a very weird API
1472 $biblionumber = $hold->biblionumber;
1475 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1476 $hold->cancel;
1478 elsif ( $reserve_id && ( $rank eq "W" || $rank eq "0" ) ) {
1480 # make sure priority for waiting or in-transit items is 0
1481 my $query = "
1482 UPDATE reserves
1483 SET priority = 0
1484 WHERE reserve_id = ?
1485 AND found IN ('W', 'T')
1487 my $sth = $dbh->prepare($query);
1488 $sth->execute( $reserve_id );
1490 my @priority;
1492 # get whats left
1493 my $query = "
1494 SELECT reserve_id, borrowernumber, reservedate
1495 FROM reserves
1496 WHERE biblionumber = ?
1497 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1498 ORDER BY priority ASC
1500 my $sth = $dbh->prepare($query);
1501 $sth->execute( $biblionumber );
1502 while ( my $line = $sth->fetchrow_hashref ) {
1503 push( @priority, $line );
1506 # FIXME This whole sub must be rewritten, especially to highlight what is done when reserve_id is not given
1507 # To find the matching index
1508 my $i;
1509 my $key = -1; # to allow for 0 to be a valid result
1510 for ( $i = 0 ; $i < @priority ; $i++ ) {
1511 if ( $reserve_id && $reserve_id == $priority[$i]->{'reserve_id'} ) {
1512 $key = $i; # save the index
1513 last;
1517 # if index exists in array then move it to new position
1518 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1519 my $new_rank = $rank -
1520 1; # $new_rank is what you want the new index to be in the array
1521 my $moving_item = splice( @priority, $key, 1 );
1522 splice( @priority, $new_rank, 0, $moving_item );
1525 # now fix the priority on those that are left....
1526 $query = "
1527 UPDATE reserves
1528 SET priority = ?
1529 WHERE reserve_id = ?
1531 $sth = $dbh->prepare($query);
1532 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1533 $sth->execute(
1534 $j + 1,
1535 $priority[$j]->{'reserve_id'}
1539 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1540 $sth->execute();
1542 unless ( $ignoreSetLowestRank ) {
1543 while ( my $res = $sth->fetchrow_hashref() ) {
1544 _FixPriority({
1545 reserve_id => $res->{'reserve_id'},
1546 rank => '999999',
1547 ignoreSetLowestRank => 1
1553 =head2 _Findgroupreserve
1555 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1557 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1558 first match found. If neither, then we look for non-holds-queue based holds.
1559 Lookahead is the number of days to look in advance.
1561 C<&_Findgroupreserve> returns :
1562 C<@results> is an array of references-to-hash whose keys are mostly
1563 fields from the reserves table of the Koha database, plus
1564 C<biblioitemnumber>.
1566 This routine with either return:
1567 1 - Item specific holds from the holds queue
1568 2 - Title level holds from the holds queue
1569 3 - All holds for this biblionumber
1571 All return values will respect any borrowernumbers passed as arrayref in $ignore_borrowers
1573 =cut
1575 sub _Findgroupreserve {
1576 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1577 my $dbh = C4::Context->dbh;
1579 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1580 # check for exact targeted match
1581 my $item_level_target_query = qq{
1582 SELECT reserves.biblionumber AS biblionumber,
1583 reserves.borrowernumber AS borrowernumber,
1584 reserves.reservedate AS reservedate,
1585 reserves.branchcode AS branchcode,
1586 reserves.cancellationdate AS cancellationdate,
1587 reserves.found AS found,
1588 reserves.reservenotes AS reservenotes,
1589 reserves.priority AS priority,
1590 reserves.timestamp AS timestamp,
1591 biblioitems.biblioitemnumber AS biblioitemnumber,
1592 reserves.itemnumber AS itemnumber,
1593 reserves.reserve_id AS reserve_id,
1594 reserves.itemtype AS itemtype
1595 FROM reserves
1596 JOIN biblioitems USING (biblionumber)
1597 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1598 WHERE found IS NULL
1599 AND priority > 0
1600 AND item_level_request = 1
1601 AND itemnumber = ?
1602 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1603 AND suspend = 0
1604 ORDER BY priority
1606 my $sth = $dbh->prepare($item_level_target_query);
1607 $sth->execute($itemnumber, $lookahead||0);
1608 my @results;
1609 if ( my $data = $sth->fetchrow_hashref ) {
1610 push( @results, $data )
1611 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1613 return @results if @results;
1615 # check for title-level targeted match
1616 my $title_level_target_query = qq{
1617 SELECT reserves.biblionumber AS biblionumber,
1618 reserves.borrowernumber AS borrowernumber,
1619 reserves.reservedate AS reservedate,
1620 reserves.branchcode AS branchcode,
1621 reserves.cancellationdate AS cancellationdate,
1622 reserves.found AS found,
1623 reserves.reservenotes AS reservenotes,
1624 reserves.priority AS priority,
1625 reserves.timestamp AS timestamp,
1626 biblioitems.biblioitemnumber AS biblioitemnumber,
1627 reserves.itemnumber AS itemnumber,
1628 reserves.reserve_id AS reserve_id,
1629 reserves.itemtype AS itemtype
1630 FROM reserves
1631 JOIN biblioitems USING (biblionumber)
1632 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1633 WHERE found IS NULL
1634 AND priority > 0
1635 AND item_level_request = 0
1636 AND hold_fill_targets.itemnumber = ?
1637 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1638 AND suspend = 0
1639 ORDER BY priority
1641 $sth = $dbh->prepare($title_level_target_query);
1642 $sth->execute($itemnumber, $lookahead||0);
1643 @results = ();
1644 if ( my $data = $sth->fetchrow_hashref ) {
1645 push( @results, $data )
1646 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1648 return @results if @results;
1650 my $query = qq{
1651 SELECT reserves.biblionumber AS biblionumber,
1652 reserves.borrowernumber AS borrowernumber,
1653 reserves.reservedate AS reservedate,
1654 reserves.waitingdate AS waitingdate,
1655 reserves.branchcode AS branchcode,
1656 reserves.cancellationdate AS cancellationdate,
1657 reserves.found AS found,
1658 reserves.reservenotes AS reservenotes,
1659 reserves.priority AS priority,
1660 reserves.timestamp AS timestamp,
1661 reserves.itemnumber AS itemnumber,
1662 reserves.reserve_id AS reserve_id,
1663 reserves.itemtype AS itemtype
1664 FROM reserves
1665 WHERE reserves.biblionumber = ?
1666 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1667 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1668 AND suspend = 0
1669 ORDER BY priority
1671 $sth = $dbh->prepare($query);
1672 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1673 @results = ();
1674 while ( my $data = $sth->fetchrow_hashref ) {
1675 push( @results, $data )
1676 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1678 return @results;
1681 =head2 _koha_notify_reserve
1683 _koha_notify_reserve( $hold->reserve_id );
1685 Sends a notification to the patron that their hold has been filled (through
1686 ModReserveAffect, _not_ ModReserveFill)
1688 The letter code for this notice may be found using the following query:
1690 select distinct letter_code
1691 from message_transports
1692 inner join message_attributes using (message_attribute_id)
1693 where message_name = 'Hold_Filled'
1695 This will probably sipmly be 'HOLD', but because it is defined in the database,
1696 it is subject to addition or change.
1698 The following tables are availalbe witin the notice:
1700 branches
1701 borrowers
1702 biblio
1703 biblioitems
1704 reserves
1705 items
1707 =cut
1709 sub _koha_notify_reserve {
1710 my $reserve_id = shift;
1711 my $hold = Koha::Holds->find($reserve_id);
1712 my $borrowernumber = $hold->borrowernumber;
1714 my $patron = Koha::Patrons->find( $borrowernumber );
1716 # Try to get the borrower's email address
1717 my $to_address = $patron->notice_email_address;
1719 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1720 borrowernumber => $borrowernumber,
1721 message_name => 'Hold_Filled'
1722 } );
1724 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1726 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1728 my %letter_params = (
1729 module => 'reserves',
1730 branchcode => $hold->branchcode,
1731 lang => $patron->lang,
1732 tables => {
1733 'branches' => $library,
1734 'borrowers' => $patron->unblessed,
1735 'biblio' => $hold->biblionumber,
1736 'biblioitems' => $hold->biblionumber,
1737 'reserves' => $hold->unblessed,
1738 'items' => $hold->itemnumber,
1742 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.
1743 my $send_notification = sub {
1744 my ( $mtt, $letter_code ) = (@_);
1745 return unless defined $letter_code;
1746 $letter_params{letter_code} = $letter_code;
1747 $letter_params{message_transport_type} = $mtt;
1748 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1749 unless ($letter) {
1750 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1751 return;
1754 C4::Letters::EnqueueLetter( {
1755 letter => $letter,
1756 borrowernumber => $borrowernumber,
1757 from_address => $admin_email_address,
1758 message_transport_type => $mtt,
1759 } );
1762 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1763 next if (
1764 ( $mtt eq 'email' and not $to_address ) # No email address
1765 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1766 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1769 &$send_notification($mtt, $letter_code);
1770 $notification_sent++;
1772 #Making sure that a print notification is sent if no other transport types can be utilized.
1773 if (! $notification_sent) {
1774 &$send_notification('print', 'HOLD');
1779 =head2 _ShiftPriorityByDateAndPriority
1781 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1783 This increments the priority of all reserves after the one
1784 with either the lowest date after C<$reservedate>
1785 or the lowest priority after C<$priority>.
1787 It effectively makes room for a new reserve to be inserted with a certain
1788 priority, which is returned.
1790 This is most useful when the reservedate can be set by the user. It allows
1791 the new reserve to be placed before other reserves that have a later
1792 reservedate. Since priority also is set by the form in reserves/request.pl
1793 the sub accounts for that too.
1795 =cut
1797 sub _ShiftPriorityByDateAndPriority {
1798 my ( $biblio, $resdate, $new_priority ) = @_;
1800 my $dbh = C4::Context->dbh;
1801 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1802 my $sth = $dbh->prepare( $query );
1803 $sth->execute( $biblio, $resdate, $new_priority );
1804 my $min_priority = $sth->fetchrow;
1805 # if no such matches are found, $new_priority remains as original value
1806 $new_priority = $min_priority if ( $min_priority );
1808 # Shift the priority up by one; works in conjunction with the next SQL statement
1809 $query = "UPDATE reserves
1810 SET priority = priority+1
1811 WHERE biblionumber = ?
1812 AND borrowernumber = ?
1813 AND reservedate = ?
1814 AND found IS NULL";
1815 my $sth_update = $dbh->prepare( $query );
1817 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1818 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1819 $sth = $dbh->prepare( $query );
1820 $sth->execute( $new_priority, $biblio );
1821 while ( my $row = $sth->fetchrow_hashref ) {
1822 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1825 return $new_priority; # so the caller knows what priority they wind up receiving
1828 =head2 MoveReserve
1830 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1832 Use when checking out an item to handle reserves
1833 If $cancelreserve boolean is set to true, it will remove existing reserve
1835 =cut
1837 sub MoveReserve {
1838 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1840 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1841 my ( $restype, $res, undef ) = CheckReserves( $itemnumber, undef, $lookahead );
1842 return unless $res;
1844 my $biblionumber = $res->{biblionumber};
1846 if ($res->{borrowernumber} == $borrowernumber) {
1847 ModReserveFill($res);
1849 else {
1850 # warn "Reserved";
1851 # The item is reserved by someone else.
1852 # Find this item in the reserves
1854 my $borr_res = Koha::Holds->search({
1855 borrowernumber => $borrowernumber,
1856 biblionumber => $biblionumber,
1858 order_by => 'priority'
1859 })->next();
1861 if ( $borr_res ) {
1862 # The item is reserved by the current patron
1863 ModReserveFill($borr_res->unblessed);
1866 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1867 RevertWaitingStatus({ itemnumber => $itemnumber });
1869 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1870 my $hold = Koha::Holds->find( $res->{reserve_id} );
1871 $hold->cancel;
1876 =head2 MergeHolds
1878 MergeHolds($dbh,$to_biblio, $from_biblio);
1880 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1882 =cut
1884 sub MergeHolds {
1885 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1886 my $sth = $dbh->prepare(
1887 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1889 $sth->execute($from_biblio);
1890 if ( my $data = $sth->fetchrow_hashref() ) {
1892 # holds exist on old record, if not we don't need to do anything
1893 $sth = $dbh->prepare(
1894 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1895 $sth->execute( $to_biblio, $from_biblio );
1897 # Reorder by date
1898 # don't reorder those already waiting
1900 $sth = $dbh->prepare(
1901 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1903 my $upd_sth = $dbh->prepare(
1904 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1905 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1907 $sth->execute( $to_biblio, 'W', 'T' );
1908 my $priority = 1;
1909 while ( my $reserve = $sth->fetchrow_hashref() ) {
1910 $upd_sth->execute(
1911 $priority, $to_biblio,
1912 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1913 $reserve->{'itemnumber'}
1915 $priority++;
1920 =head2 RevertWaitingStatus
1922 RevertWaitingStatus({ itemnumber => $itemnumber });
1924 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1926 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1927 item level hold, even if it was only a bibliolevel hold to
1928 begin with. This is because we can no longer know if a hold
1929 was item-level or bib-level after a hold has been set to
1930 waiting status.
1932 =cut
1934 sub RevertWaitingStatus {
1935 my ( $params ) = @_;
1936 my $itemnumber = $params->{'itemnumber'};
1938 return unless ( $itemnumber );
1940 my $dbh = C4::Context->dbh;
1942 ## Get the waiting reserve we want to revert
1943 my $query = "
1944 SELECT * FROM reserves
1945 WHERE itemnumber = ?
1946 AND found IS NOT NULL
1948 my $sth = $dbh->prepare( $query );
1949 $sth->execute( $itemnumber );
1950 my $reserve = $sth->fetchrow_hashref();
1952 my $hold = Koha::Holds->find( $reserve->{reserve_id} ); # TODO Remove the next raw SQL statements and use this instead
1954 ## Increment the priority of all other non-waiting
1955 ## reserves for this bib record
1956 $query = "
1957 UPDATE reserves
1959 priority = priority + 1
1960 WHERE
1961 biblionumber = ?
1963 priority > 0
1965 $sth = $dbh->prepare( $query );
1966 $sth->execute( $reserve->{'biblionumber'} );
1968 ## Fix up the currently waiting reserve
1969 $query = "
1970 UPDATE reserves
1972 priority = 1,
1973 found = NULL,
1974 waitingdate = NULL
1975 WHERE
1976 reserve_id = ?
1978 $sth = $dbh->prepare( $query );
1979 $sth->execute( $reserve->{'reserve_id'} );
1981 unless ( $hold->item_level_hold ) {
1982 $hold->itemnumber(undef)->store;
1985 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1988 =head2 ReserveSlip
1990 ReserveSlip(
1992 branchcode => $branchcode,
1993 borrowernumber => $borrowernumber,
1994 biblionumber => $biblionumber,
1995 [ itemnumber => $itemnumber, ]
1996 [ barcode => $barcode, ]
2000 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
2002 The letter code will be HOLD_SLIP, and the following tables are
2003 available within the slip:
2005 reserves
2006 branches
2007 borrowers
2008 biblio
2009 biblioitems
2010 items
2012 =cut
2014 sub ReserveSlip {
2015 my ($args) = @_;
2016 my $branchcode = $args->{branchcode};
2017 my $borrowernumber = $args->{borrowernumber};
2018 my $biblionumber = $args->{biblionumber};
2019 my $itemnumber = $args->{itemnumber};
2020 my $barcode = $args->{barcode};
2023 my $patron = Koha::Patrons->find($borrowernumber);
2025 my $hold;
2026 if ($itemnumber || $barcode ) {
2027 $itemnumber ||= Koha::Items->find( { barcode => $barcode } )->itemnumber;
2029 $hold = Koha::Holds->search(
2031 biblionumber => $biblionumber,
2032 borrowernumber => $borrowernumber,
2033 itemnumber => $itemnumber
2035 )->next;
2037 else {
2038 $hold = Koha::Holds->search(
2040 biblionumber => $biblionumber,
2041 borrowernumber => $borrowernumber
2043 )->next;
2046 return unless $hold;
2047 my $reserve = $hold->unblessed;
2049 return C4::Letters::GetPreparedLetter (
2050 module => 'circulation',
2051 letter_code => 'HOLD_SLIP',
2052 branchcode => $branchcode,
2053 lang => $patron->lang,
2054 tables => {
2055 'reserves' => $reserve,
2056 'branches' => $reserve->{branchcode},
2057 'borrowers' => $reserve->{borrowernumber},
2058 'biblio' => $reserve->{biblionumber},
2059 'biblioitems' => $reserve->{biblionumber},
2060 'items' => $reserve->{itemnumber},
2065 =head2 GetReservesControlBranch
2067 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2069 Return the branchcode to be used to determine which reserves
2070 policy applies to a transaction.
2072 C<$item> is a hashref for an item. Only 'homebranch' is used.
2074 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2076 =cut
2078 sub GetReservesControlBranch {
2079 my ( $item, $borrower ) = @_;
2081 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2083 my $branchcode =
2084 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2085 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2086 : undef;
2088 return $branchcode;
2091 =head2 CalculatePriority
2093 my $p = CalculatePriority($biblionumber, $resdate);
2095 Calculate priority for a new reserve on biblionumber, placing it at
2096 the end of the line of all holds whose start date falls before
2097 the current system time and that are neither on the hold shelf
2098 or in transit.
2100 The reserve date parameter is optional; if it is supplied, the
2101 priority is based on the set of holds whose start date falls before
2102 the parameter value.
2104 After calculation of this priority, it is recommended to call
2105 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2106 AddReserves.
2108 =cut
2110 sub CalculatePriority {
2111 my ( $biblionumber, $resdate ) = @_;
2113 my $sql = q{
2114 SELECT COUNT(*) FROM reserves
2115 WHERE biblionumber = ?
2116 AND priority > 0
2117 AND (found IS NULL OR found = '')
2119 #skip found==W or found==T (waiting or transit holds)
2120 if( $resdate ) {
2121 $sql.= ' AND ( reservedate <= ? )';
2123 else {
2124 $sql.= ' AND ( reservedate < NOW() )';
2126 my $dbh = C4::Context->dbh();
2127 my @row = $dbh->selectrow_array(
2128 $sql,
2129 undef,
2130 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2133 return @row ? $row[0]+1 : 1;
2136 =head2 IsItemOnHoldAndFound
2138 my $bool = IsItemFoundHold( $itemnumber );
2140 Returns true if the item is currently on hold
2141 and that hold has a non-null found status ( W, T, etc. )
2143 =cut
2145 sub IsItemOnHoldAndFound {
2146 my ($itemnumber) = @_;
2148 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2150 my $found = $rs->count(
2152 itemnumber => $itemnumber,
2153 found => { '!=' => undef }
2157 return $found;
2160 =head2 GetMaxPatronHoldsForRecord
2162 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2164 For multiple holds on a given record for a given patron, the max
2165 number of record level holds that a patron can be placed is the highest
2166 value of the holds_per_record rule for each item if the record for that
2167 patron. This subroutine finds and returns the highest holds_per_record
2168 rule value for a given patron id and record id.
2170 =cut
2172 sub GetMaxPatronHoldsForRecord {
2173 my ( $borrowernumber, $biblionumber ) = @_;
2175 my $patron = Koha::Patrons->find($borrowernumber);
2176 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2178 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2180 my $categorycode = $patron->categorycode;
2181 my $branchcode;
2182 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2184 my $max = 0;
2185 foreach my $item (@items) {
2186 my $itemtype = $item->effective_itemtype();
2188 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2190 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2191 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2192 $max = $holds_per_record if $holds_per_record > $max;
2195 return $max;
2198 =head2 GetHoldRule
2200 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2202 Returns the matching hold related issuingrule fields for a given
2203 patron category, itemtype, and library.
2205 =cut
2207 sub GetHoldRule {
2208 my ( $categorycode, $itemtype, $branchcode ) = @_;
2210 my $dbh = C4::Context->dbh;
2212 my $sth = $dbh->prepare(
2214 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record, holds_per_day
2215 FROM issuingrules
2216 WHERE (categorycode in (?,'*') )
2217 AND (itemtype IN (?,'*'))
2218 AND (branchcode IN (?,'*'))
2219 ORDER BY categorycode DESC,
2220 itemtype DESC,
2221 branchcode DESC
2225 $sth->execute( $categorycode, $itemtype, $branchcode );
2227 return $sth->fetchrow_hashref();
2230 =head1 AUTHOR
2232 Koha Development Team <http://koha-community.org/>
2234 =cut