4 #written 2/1/00 by chris@katipo.oc.nz
5 # Copyright 2000-2002 Katipo Communications
6 # Parts Copyright 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>.
25 script to place reserves/requests
32 use List::MoreUtils qw( uniq );
33 use Date::Calc qw( Date_to_Days );
34 use C4::Output qw( output_html_with_http_headers );
35 use C4::Auth qw( get_template_and_user );
36 use C4::Reserves qw( RevertWaitingStatus AlterPriority ToggleLowestPriority ToggleSuspend CanBookBeReserved GetMaxPatronHoldsForRecord CanItemBeReserved IsAvailableForItemLevelRequest );
37 use C4::Items qw( get_hostitemnumbers_of );
38 use C4::Koha qw( getitemtypeimagelocation );
39 use C4::Serials qw( CountSubscriptionFromBiblionumber );
40 use C4::Circulation qw( _GetCircControlBranch GetBranchItemRule );
41 use Koha::DateUtils qw( dt_from_string );
42 use C4::Search qw( enabled_staff_search_views );
47 use Koha::CirculationRules;
52 use Koha::Patron::Attribute::Types;
54 use Koha::BackgroundJob::BatchCancelHold;
56 my $dbh = C4::Context->dbh;
58 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
60 template_name => "reserve/request.tt",
63 flagsrequired => { reserveforothers => 'place_holds' },
67 my $showallitems = $input->param('showallitems');
68 my $pickup = $input->param('pickup');
73 { %{ $_->unblessed }, image_location => $_->image_location('intranet'), notforloan => $_->notforloan }
74 } Koha::ItemTypes->search_with_localization->as_list
77 # Select borrowers infos
78 my $findborrower = $input->param('findborrower');
79 $findborrower = '' unless defined $findborrower;
80 $findborrower =~ s|,| |g;
81 my $findclub = $input->param('findclub');
82 $findclub = '' unless defined $findclub && !$findborrower;
83 my $borrowernumber_hold = $input->param('borrowernumber') || '';
84 my $club_hold = $input->param('club')||'';
89 my $exceeded_maxreserves;
90 my $exceeded_holds_per_record;
92 my $op = $input->param('op') || q{};
94 if ( $op eq 'cud-move' ) {
95 my $where = $input->param('where');
96 my $reserve_id = $input->param('reserve_id');
97 my $prev_priority = $input->param('prev_priority');
98 my $next_priority = $input->param('next_priority');
99 my $first_priority = $input->param('first_priority');
100 my $last_priority = $input->param('last_priority');
101 my $hold_itemnumber = $input->param('itemnumber');
102 if ( $prev_priority == 0 && $next_priority == 1 ) {
103 C4::Reserves::RevertWaitingStatus( { itemnumber => $hold_itemnumber } );
107 $where, $reserve_id, $prev_priority,
108 $next_priority, $first_priority, $last_priority
112 elsif ( $op eq 'cud-cancel' ) {
113 my $reserve_id = $input->param('reserve_id');
114 my $cancellation_reason = $input->param("cancellation-reason");
115 my $hold = Koha::Holds->find($reserve_id);
116 $hold->cancel( { cancellation_reason => $cancellation_reason } ) if $hold;
118 elsif ( $op eq 'cud-setLowestPriority' ) {
119 my $reserve_id = $input->param('reserve_id');
120 ToggleLowestPriority($reserve_id);
122 elsif ( $op eq 'cud-toggleSuspend' ) {
123 my $reserve_id = $input->param('reserve_id');
124 my $suspend_until = $input->param('suspend_until');
125 ToggleSuspend( $reserve_id, $suspend_until );
127 elsif ( $op eq 'cud-cancel_bulk' ) {
128 my $cancellation_reason = $input->param("cancellation-reason");
129 my @hold_ids = split( ',', scalar $input->param("ids"));
131 reason => $cancellation_reason,
132 hold_ids => \@hold_ids,
134 my $job_id = Koha::BackgroundJob::BatchCancelHold->new->enqueue($params);
143 my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
144 $borrowernumber_hold = $patron->borrowernumber if $patron;
148 my $club = Koha::Clubs->find( { name => $findclub } );
150 $club_hold = $club->id;
152 my @clubs = Koha::Clubs->search( [
153 { name => { like => '%'.$findclub.'%' } },
154 { description => { like => '%'.$findclub.'%' } }
156 if( scalar @clubs == 1 ) {
157 $club_hold = $clubs[0]->id;
159 $template->param( clubs => \@clubs );
161 $messageclub = "'$findclub'";
166 my @biblionumbers = $input->multi_param('biblionumber');
168 my $multi_hold = @biblionumbers > 1;
170 multi_hold => $multi_hold,
173 # If we have the borrowernumber because we've performed an action, then we
174 # don't want to try to place another reserve.
175 if ($borrowernumber_hold && !$op) {
176 my $patron = Koha::Patrons->find( $borrowernumber_hold );
179 # we check the reserves of the user, and if they can reserve a document
180 # FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
182 my $reserves_count = $patron->holds->count;
184 my $new_reserves_count = scalar( @biblionumbers );
186 my $maxreserves = C4::Context->preference('maxreserves');
187 $template->param( maxreserves => $maxreserves );
190 && ( $reserves_count + $new_reserves_count > $maxreserves ) )
192 my $new_reserves_allowed =
193 $maxreserves - $reserves_count > 0
194 ? $maxreserves - $reserves_count
197 $exceeded_maxreserves = 1;
199 new_reserves_allowed => $new_reserves_allowed,
200 new_reserves_count => $new_reserves_count,
201 reserves_count => $reserves_count,
202 maxreserves => $maxreserves,
206 # check if the borrower make the reserv in a different branch
207 if ( $patron->branchcode ne C4::Context->userenv->{'branch'} ) {
211 my $amount_outstanding = $patron->account->balance;
214 diffbranch => $diffbranch,
215 messages => $messages,
216 warnings => $warnings,
217 amount_outstanding => $amount_outstanding,
221 if ($club_hold && !$borrowernumber_hold && !$op) {
222 my $club = Koha::Clubs->find($club_hold);
224 my $enrollments = $club->club_enrollments;
226 my $maxreserves = C4::Context->preference('maxreserves');
227 my $new_reserves_count = scalar( @biblionumbers );
231 while(my $enrollment = $enrollments->next) {
232 next if $enrollment->is_canceled;
233 my $member = { patron => $enrollment->patron };
234 my $reserves_count = $enrollment->patron->holds->count;
236 && ( $reserves_count + $new_reserves_count > $maxreserves ) )
238 $member->{new_reserves_allowed} = $maxreserves - $reserves_count > 0
239 ? $maxreserves - $reserves_count
241 $member->{exceeded_maxreserves} = 1;
243 $member->{amount_outstanding} = $enrollment->patron->account->balance;
244 if ( $enrollment->patron->branchcode ne C4::Context->userenv->{'branch'} ) {
245 $member->{diffbranch} = 1;
248 push @members, $member;
253 members => \@members,
254 maxreserves => $maxreserves,
255 new_reserves_count => $new_reserves_count
259 unless ( $club_hold or $borrowernumber_hold ) {
260 $template->param( clubcount => Koha::Clubs->search->count );
264 messageborrower => $messageborrower,
265 messageclub => $messageclub
268 # Load the hold list if
269 # - we are searching for a patron or club and found one
270 # - we are not searching for anything
271 if ( ( $findborrower && $borrowernumber_hold || $findclub && $club_hold )
272 || ( !$findborrower && !$findclub ) )
274 # FIXME launch another time GetMember perhaps until (Joubu: Why?)
275 my $patron = Koha::Patrons->find( $borrowernumber_hold );
277 if ( $patron && $multi_hold ) {
278 my @multi_pickup_locations =
279 Koha::Biblios->search( { biblionumber => \@biblionumbers } )
280 ->pickup_locations( { patron => $patron } )->as_list;
281 $template->param( multi_pickup_locations => \@multi_pickup_locations );
284 my $logged_in_patron = Koha::Patrons->find( $borrowernumber );
288 $wants_check = $patron->wants_check_for_previous_checkout;
290 my $itemdata_enumchron = 0;
291 my $itemdata_ccode = 0;
293 my $no_reserves_allowed = 0;
294 my $num_bibs_available = 0;
295 foreach my $biblionumber (@biblionumbers) {
296 next unless $biblionumber =~ m|^\d+$|;
298 my %biblioloopiter = ();
300 my $biblio = Koha::Biblios->find( $biblionumber );
303 $biblioloopiter{noitems} = 1;
304 $template->param('nobiblio' => 1);
308 $biblioloopiter{object} = $biblio;
311 { # CanBookBeReserved
312 my $canReserve = CanBookBeReserved( $patron->borrowernumber, $biblionumber );
313 if ( $canReserve->{status} eq 'OK' ) {
315 #All is OK and we can continue
317 elsif ( $canReserve->{status} eq 'noReservesAllowed' || $canReserve->{status} eq 'notReservable' ) {
318 $no_reserves_allowed = 1;
320 elsif ( $canReserve->{status} eq 'tooManyReserves' ) {
321 $exceeded_maxreserves = 1;
322 $template->param( maxreserves => $canReserve->{limit} );
324 elsif ( $canReserve->{status} eq 'tooManyHoldsForThisRecord' ) {
325 $exceeded_holds_per_record = 1;
326 $biblioloopiter{ $canReserve->{status} } = 1;
328 elsif ( $canReserve->{status} eq 'ageRestricted' ) {
329 $template->param( $canReserve->{status} => 1 );
330 $biblioloopiter{ $canReserve->{status} } = 1;
332 elsif ( $canReserve->{status} eq 'alreadypossession' ) {
333 $template->param( $canReserve->{status} => 1);
334 $biblioloopiter{ $canReserve->{status} } = 1;
336 elsif ( $canReserve->{status} eq 'recall' ) {
337 $template->param( $canReserve->{status} => 1 );
338 $biblioloopiter{ $canReserve->{status} } = 1;
341 $biblioloopiter{ $canReserve->{status} } = 1;
345 # For multiple holds per record, if a patron has previously placed a hold,
346 # the patron can only place more holds of the same type. That is, if the
347 # patron placed a record level hold, all the holds the patron places must
348 # be record level. If the patron placed an item level hold, all holds
349 # the patron places must be item level
350 my $holds = Koha::Holds->search(
352 borrowernumber => $patron->borrowernumber,
353 biblionumber => $biblionumber,
357 $template->param( force_hold_level => $holds->forced_hold_level() );
359 # For a librarian to be able to place multiple record holds for a patron for a record,
360 # we must find out what the maximum number of holds they can place for the patron is
361 my $max_holds_for_record = GetMaxPatronHoldsForRecord( $patron->borrowernumber, $biblionumber );
362 my $remaining_holds_for_record = $max_holds_for_record - $holds->count();
363 $biblioloopiter{remaining_holds_for_record} = $max_holds_for_record;
364 $template->param( max_holds_for_record => $max_holds_for_record );
365 $template->param( remaining_holds_for_record => $remaining_holds_for_record );
368 # adding a fixed value for priority options
369 my $fixedRank = $biblio->holds->count + 1;
371 my @items = $biblio->items->as_list;
373 my @host_items = $biblio->host_items->as_list;
375 push @items, @host_items;
379 # FIXME Then why do we continue?
380 $template->param('noitems' => 1) unless ( $multi_hold );
381 $biblioloopiter{noitems} = 1;
384 if ( $club_hold or $borrowernumber_hold ) {
385 my @available_itemtypes;
386 my $num_items_available = 0;
387 my $num_override = 0;
389 my $num_alreadyheld = 0;
391 # iterating through all items first to check if any of them available
392 # to pass this value further inside down to IsAvailableForItemLevelRequest to
393 # it's complicated logic to analyse.
394 # (before this loop was inside that sub loop so it was O(n^2) )
396 for my $item_object ( @items ) {
398 my $item = $item_object->unblessed;
399 $item->{object} = $item_object;
401 $do_check = $patron->do_check_for_previous_checkout($item) if $wants_check;
402 if ( $do_check && $wants_check ) {
403 $item->{checked_previously} = $do_check;
405 $biblioloopiter{checked_previously} = $do_check;
407 $template->param( checked_previously => $do_check );
412 $item->{itemtype} = $itemtypes->{ $item_object->effective_itemtype };
414 if($item->{biblionumber} ne $biblio->biblionumber){
415 $item->{hosttitle} = Koha::Biblios->find( $item->{biblionumber} )->title;
418 # if the item is currently on loan, we display its return date and
419 # change the background color
420 my $issue = $item_object->checkout;
421 if ( $issue ) { # FIXME must be moved to the template
422 $item->{date_due} = $issue->date_due;
423 $item->{backgroundcolor} = 'onloan';
427 my $holds = $item_object->current_holds;
428 if ( my $first_hold = $holds->next ) {
429 my $p = Koha::Patrons->find( $first_hold->borrowernumber );
431 $item->{backgroundcolor} = 'reserved';
432 $item->{reservedate} = $first_hold->reservedate;
433 $item->{ReservedFor} = $p;
434 $item->{reserve_id} = $first_hold->reserve_id;
435 $item->{ExpectedAtLibrary} = $first_hold->branchcode;
436 $item->{waitingdate} = $first_hold->waitingdate;
439 # Management of the notforloan document
440 if ( $item->{notforloan} ) {
441 $item->{backgroundcolor} = 'other';
444 # Management of lost or long overdue items
445 if ( $item->{itemlost} ) {
446 $item->{backgroundcolor} = 'other';
447 if ($logged_in_patron->category->hidelostitems && !$showallitems) {
453 # Check the transit status
454 my $transfer = $item_object->get_transfer;
455 if ( $transfer && $transfer->in_transit ) {
456 $item->{transfertwhen} = $transfer->datesent;
457 $item->{transfertfrom} = $transfer->frombranch;
458 $item->{transfertto} = $transfer->tobranch;
459 $item->{nocancel} = 1;
462 # If there is no loan, return and transfer, we show a checkbox.
463 $item->{notforloanitype} = $item->{itemtype}->{notforloan};
464 $item->{notforloan} ||= 0;
466 # if independent branches is on we need to check if the person can reserve
467 # for branches they arent logged in to
468 if ( C4::Context->preference("IndependentBranches") ) {
469 if (! C4::Context->preference("canreservefromotherbranches")){
470 # can't reserve items so need to check if item homebranch and userenv branch match if not we can't reserve
471 my $userenv = C4::Context->userenv;
472 unless ( C4::Context->IsSuperLibrarian ) {
473 $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
479 my $branch = _GetCircControlBranch($item_object, $patron);
481 my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} );
483 $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
485 my $can_item_be_reserved = CanItemBeReserved( $patron, $item_object, undef, { get_from_cache => 1 } )->{status};
486 $item->{not_holdable} = $can_item_be_reserved unless ( $can_item_be_reserved eq 'OK' );
487 $item->{not_holdable} ||= 'notforloan' if ( $item->{notforloanitype} || $item->{notforloan} > 0 );
490 $item->{item_level_holds} = Koha::CirculationRules->get_opacitemholds_policy( { item => $item_object, patron => $patron } );
492 my $default_hold_pickup_location_pref = C4::Context->preference('DefaultHoldPickupLocation');
493 my $default_pickup_branch;
494 if( $default_hold_pickup_location_pref eq 'homebranch' ){
495 $default_pickup_branch = $item->{homebranch};
496 } elsif ( $default_hold_pickup_location_pref eq 'holdingbranch' ){
497 $default_pickup_branch = $item->{holdingbranch};
499 $default_pickup_branch = C4::Context->userenv->{branch};
502 if ( $can_item_be_reserved eq 'itemAlreadyOnHold' ) {
503 # itemAlreadyOnHold cannot be overridden
508 !$item->{cantreserve}
509 && !$exceeded_maxreserves
510 && $can_item_be_reserved eq 'OK'
511 && IsAvailableForItemLevelRequest($item_object, $patron, undef)
512 ) || C4::Context->preference('AllowHoldPolicyOverride')
513 # If AllowHoldPolicyOverride is set, it overrides EVERY restriction
514 # not just branch item rules
517 # Send the pickup locations count to the UI, the pickup locations will be pulled using the API
518 my $pickup_locations = $item_object->pickup_locations({ patron => $patron });
519 $item->{pickup_locations_count} = $pickup_locations->count;
520 if ( $item->{pickup_locations_count} > 0 ) {
521 $num_items_available++;
522 $item->{available} = 1;
523 # pass the holding branch for use as default
524 my $default_pickup_location = $pickup_locations->search({ branchcode => $default_pickup_branch })->next;
525 $item->{default_pickup_location} = $default_pickup_location;
527 elsif ( C4::Context->preference('AllowHoldPolicyOverride') ){
528 $num_items_available++;
529 $item->{override} = 1;
530 my $default_pickup_location = $pickup_locations->search({ branchcode => $default_pickup_branch })->next;
531 $item->{default_pickup_location} = $default_pickup_location;
534 $item->{available} = 0;
535 $item->{not_holdable} = "no_valid_pickup_location";
538 push( @available_itemtypes, $item->{itype} );
540 # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
541 $item->{available} = 0;
545 # Show serial enumeration when needed
546 if ($item->{enumchron}) {
547 $itemdata_enumchron = 1;
549 # Show collection when needed
550 if ($item->{ccode}) {
555 push @{ $biblioloopiter{itemloop} }, $item;
558 $biblioloopiter{biblioitem} = $biblio->biblioitem;
560 # While we can't override an alreay held item, we should be able to override the others
561 # Unless all items are already held
562 if ( $num_override > 0 && ($num_override + $num_alreadyheld) == scalar( @{ $biblioloopiter{itemloop} } ) ) {
563 # That is, if all items require an override
564 $template->param( override_required => 1 );
565 } elsif ( $num_items_available == 0 ) {
566 $template->param( none_available => 1 );
567 $biblioloopiter{warn} = 1;
568 $biblioloopiter{none_avail} = 1;
570 $template->param( hiddencount => $hiddencount);
572 @available_itemtypes = uniq( @available_itemtypes );
573 $template->param( available_itemtypes => \@available_itemtypes );
576 # existingreserves building
578 my $always_show_holds = $input->cookie('always_show_holds');
579 $template->param( always_show_holds => $always_show_holds );
580 my $show_holds_now = $input->param('show_holds_now');
581 unless( (defined $always_show_holds && $always_show_holds eq 'DONT') && !$show_holds_now ){
582 my $holds_count_per_patron = {
583 map { $_->{borrowernumber} => $_->{hold_count} } @{ Koha::Holds->search(
584 { biblionumber => $biblionumber },
586 select => [ "borrowernumber", { count => { distinct => "reserve_id" } } ],
587 as => [qw( borrowernumber hold_count )],
588 group_by => [qw( borrowernumber )]
593 my @reserves = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } )->as_list;
596 my $a_found = $a->found() || '';
597 my $b_found = $a->found() || '';
598 $a_found cmp $b_found;
603 if ( $res->is_found() ) {
604 $reserve{'holdingbranch'} = $res->item()->holdingbranch();
605 $reserve{'biblionumber'} = $res->item()->biblionumber();
606 $reserve{'barcodenumber'} = $res->item()->barcode();
607 $reserve{'wbrcode'} = $res->branchcode();
608 $reserve{'itemnumber'} = $res->itemnumber();
609 $reserve{'wbrname'} = $res->branch()->branchname();
610 $reserve{'atdestination'} = $res->is_at_destination();
611 $reserve{'desk_name'} = ( $res->desk() ) ? $res->desk()->desk_name() : '' ;
612 $reserve{'found'} = $res->is_found();
613 $reserve{'inprocessing'} = $res->is_in_processing();
614 $reserve{'intransit'} = $res->is_in_transit();
616 elsif ( $res->priority() > 0 ) {
617 if ( my $item = $res->item() ) {
618 $reserve{'itemnumber'} = $item->id();
619 $reserve{'barcodenumber'} = $item->barcode();
620 $reserve{'item_level_hold'} = 1;
623 $reserve{'expirationdate'} = $res->expirationdate;
624 $reserve{'expired'} = 1
625 if ( DateTime->compare( dt_from_string( $res->expirationdate ), dt_from_string() ) == -1 );
626 $reserve{'date'} = $res->reservedate;
627 $reserve{'borrowernumber'} = $res->borrowernumber();
628 $reserve{'biblionumber'} = $res->biblionumber();
629 $reserve{'patron'} = $res->borrower;
630 $reserve{'notes'} = $res->reservenotes();
631 $reserve{'waiting_date'} = $res->waitingdate();
632 $reserve{'ccode'} = $res->item() ? $res->item()->ccode() : undef;
633 $reserve{'barcode'} = $res->item() ? $res->item()->barcode() : undef;
634 $reserve{'priority'} = $res->priority();
635 $reserve{'lowestPriority'} = $res->lowestPriority();
636 $reserve{'suspend'} = $res->suspend();
637 $reserve{'suspend_until'} = $res->suspend_until();
638 $reserve{'reserve_id'} = $res->reserve_id();
639 $reserve{itemtype} = $res->itemtype();
640 $reserve{branchcode} = $res->branchcode();
641 $reserve{non_priority} = $res->non_priority();
642 $reserve{object} = $res;
644 if ( $holds_count_per_patron->{ $reserve{'borrowernumber'} } == 1 ) {
645 $reserve{'change_hold_type_allowed'} = 1;
648 push( @reserveloop, \%reserve );
652 # get the time for the form name...
657 fixedRank => $fixedRank,
662 itemdata_enumchron => $itemdata_enumchron,
663 itemdata_ccode => $itemdata_ccode,
664 date => dt_from_string,
665 biblionumber => $biblionumber,
666 findborrower => $findborrower,
669 C4::Search::enabled_staff_search_views,
672 $biblioloopiter{biblionumber} = $biblionumber;
673 $biblioloopiter{title} = $biblio->title;
674 $biblioloopiter{author} = $biblio->author;
675 $biblioloopiter{rank} = $fixedRank;
676 $biblioloopiter{reserveloop} = \@reserveloop;
679 $template->param( reserveloop => \@reserveloop );
682 if ( $patron && $multi_hold ) {
683 # Add the valid pickup locations
684 my @pickup_locations = $biblio->pickup_locations({ patron => $patron })->as_list;
685 $biblioloopiter{pickup_locations} = \@pickup_locations;
686 $biblioloopiter{pickup_locations_codes} = [ map { $_->branchcode } @pickup_locations ];
689 $num_bibs_available++ unless $biblioloopiter{none_avail};
690 push @biblioloop, \%biblioloopiter;
693 $template->param( no_bibs_available => 1 ) unless $num_bibs_available > 0;
695 $template->param( biblioloop => \@biblioloop );
696 $template->param( no_reserves_allowed => $no_reserves_allowed );
697 $template->param( exceeded_maxreserves => $exceeded_maxreserves );
698 $template->param( exceeded_holds_per_record => $exceeded_holds_per_record );
699 # FIXME: getting just the first bib's result doesn't seem right
700 $template->param( subscriptionsnumber => CountSubscriptionFromBiblionumber($biblionumbers[0]));
701 } elsif ( ! $multi_hold ) {
702 my $biblio = Koha::Biblios->find( $biblionumbers[0] );
703 $template->param( biblio => $biblio );
705 $template->param( biblionumbers => \@biblionumbers );
707 # pass the userenv branch if no pickup location selected
708 $template->param( pickup => $pickup || C4::Context->userenv->{branch} );
710 $template->param(borrowernumber => $borrowernumber_hold);
713 output_html_with_http_headers $input, $cookie, $template->output;
715 sub sort_borrowerlist {
716 my $borrowerslist = shift;
719 uc( $a->{surname} . $a->{firstname} ) cmp
720 uc( $b->{surname} . $b->{firstname} )