4 # Copyright Katipo Communications 2002
5 # Copyright Koha Development team 2012
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
25 use C4::Auth qw( get_template_and_user );
26 use C4::Koha qw( getitemtypeimagelocation getitemtypeimagesrc );
27 use C4::Circulation qw( GetBranchItemRule );
28 use C4::Reserves qw( CanItemBeReserved CanBookBeReserved AddReserve IsAvailableForItemLevelRequest GetReserveFee );
29 use C4::Biblio qw( GetBiblioData GetFrameworkCode );
30 use C4::Output qw( output_html_with_http_headers );
35 use Koha::AuthorisedValues;
37 use Koha::CirculationRules;
38 use Koha::DateUtils qw( dt_from_string );
44 use List::MoreUtils qw( uniq );
46 my $maxreserves = C4::Context->preference("maxreserves");
49 my $op = $query->param('op') // q{};
51 # if OPACHoldRequests (for placing holds) is disabled, leave immediately
52 if ( ! C4::Context->preference('OPACHoldRequests') ) {
53 print $query->redirect("/cgi-bin/koha/errors/404.pl");
57 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
59 template_name => "opac-reserve.tt",
65 my $patron = Koha::Patrons->find( $borrowernumber, { prefetch => ['categorycode'] } );
66 my $category = $patron->category;
68 my $can_place_hold_if_available_at_pickup = C4::Context->preference('OPACHoldsIfAvailableAtPickup');
69 unless ( $can_place_hold_if_available_at_pickup ) {
70 my @patron_categories = split ',', C4::Context->preference('OPACHoldsIfAvailableAtPickupExceptions');
71 if ( @patron_categories ) {
72 my $categorycode = $patron->categorycode;
73 $can_place_hold_if_available_at_pickup = grep { $_ eq $categorycode } @patron_categories;
77 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
79 # There are two ways of calling this script, with a single biblio num
80 # or multiple biblio nums.
81 my $biblionumbers = $query->param('biblionumbers');
82 my $reserveMode = $query->param('reserve_mode');
83 if ($reserveMode && ($reserveMode eq 'single')) {
84 my $bib = $query->param('single_bib');
85 $biblionumbers = "$bib/";
87 if (! $biblionumbers) {
88 $biblionumbers = $query->param('biblionumber');
91 if ( !$biblionumbers && $op ne 'cud-place_reserve' ) {
92 $template->param( message => 1, no_biblionumber => 1 );
93 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
97 # Pass the numbers to the page so they can be fed back
98 # when the hold is confirmed. TODO: Not necessary?
99 $template->param( biblionumbers => $biblionumbers );
101 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
102 my @biblionumbers = split /\//, $biblionumbers;
103 if ( $#biblionumbers < 0 && $op ne 'cud-place_reserve' ) {
105 $template->param(message=>1, no_biblionumber=>1);
106 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
112 # Here we check that the borrower can actually make reserves Stage 1.
116 if ( $category->effective_BlockExpiredPatronOpacActions_contains('hold') ) {
117 if ( $patron->is_expired ) {
118 # cannot reserve, their card has expired and the rules set mean this is not allowed
120 $template->param( message => 1, expired_patron => 1 );
124 my $maxoutstanding = C4::Context->preference("maxoutstanding");
125 my $amountoutstanding = $patron->account->balance;
126 if ( $amountoutstanding && ($amountoutstanding > $maxoutstanding) ) {
127 my $amount = sprintf "%.02f", $amountoutstanding;
128 $template->param( message => 1 );
130 $template->param( too_much_oweing => $amount );
133 if ( $patron->gonenoaddress && ($patron->gonenoaddress == 1) ) {
141 if ( $patron->lost && ($patron->lost == 1) ) {
149 if ( $patron->is_debarred ) {
154 debarred_comment => $patron->debarredcomment,
155 debarred_date => $patron->debarred,
159 my $holds = $patron->holds;
160 my $reserves_count = $holds->count;
161 $template->param( RESERVES => $holds->unblessed );
162 if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) {
163 $template->param( message => 1 );
165 $template->param( too_many_reserves => $holds->count );
169 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
174 # pass the pickup branch along....
175 my $branch = $query->param('branch') || $patron->branchcode || C4::Context->userenv->{branch} || '' ;
176 $template->param( branch => $branch );
180 # Here we are carrying out the hold request, possibly
181 # with a specific item for each biblionumber.
184 if ( $op eq 'cud-place_reserve' ) {
187 $reserve_cnt = $patron->holds->count;
190 # List is composed of alternating biblio/item/branch
191 my $selectedItems = $query->param('selecteditems');
193 if ($query->param('reserve_mode') eq 'single') {
194 # This indicates non-JavaScript mode, so there was
195 # only a single biblio number selected.
196 my $bib = $query->param('single_bib');
197 my $item = $query->param("checkitem_$bib");
198 if ($item eq 'any') {
201 my $branch = $query->param('branch');
202 $selectedItems = "$bib/$item/$branch/";
205 $selectedItems =~ s!/$!!;
206 my @selectedItems = split /\//, $selectedItems, -1;
208 # Make sure there is a biblionum/itemnum/branch triplet for each item.
209 # The itemnum can be 'any', meaning next available.
210 my $selectionCount = @selectedItems;
211 if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
212 $template->param(message=>1, bad_data=>1);
213 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
218 while (@selectedItems) {
219 my $biblioNum = shift(@selectedItems);
220 my $itemNum = shift(@selectedItems);
221 my $branch = shift(@selectedItems); # i.e., branch code, not name
225 my $singleBranchMode = Koha::Libraries->search->count == 1;
226 if ( $singleBranchMode || ! C4::Context->preference("OPACAllowUserToChooseBranch") )
227 { # single branch mode or disabled user choosing
228 $branch = $patron->branchcode;
231 # FIXME We shouldn't need to fetch the item here
232 my $item = $itemNum ? Koha::Items->find( $itemNum ) : undef;
233 # When choosing a specific item, the default pickup library should be dictated by the default hold policy
234 if ( ! C4::Context->preference("OPACAllowUserToChooseBranch") && $item ) {
235 my $type = $item->effective_itemtype;
236 my $reserves_control_branch = Koha::Policy::Holds->holds_control_library( $item, $patron );
237 my $rule = GetBranchItemRule( $reserves_control_branch, $type );
239 if ( $rule->{hold_fulfillment_policy} eq 'any' || $rule->{hold_fulfillment_policy} eq 'patrongroup' ) {
240 $branch = $patron->branchcode;
241 } elsif ( $rule->{hold_fulfillment_policy} eq 'holdgroup' ){
242 $branch = $item->homebranch;
244 my $policy = $rule->{hold_fulfillment_policy};
245 $branch = $item->$policy;
249 # if we have an item, we are placing the hold on the item's bib, in case of analytics
251 $biblioNum = $item->biblionumber;
254 # Check for user supplied reserve date
256 if ( C4::Context->preference('AllowHoldDateInFuture')
257 && C4::Context->preference('OPACAllowHoldDateInFuture') )
259 $startdate = $query->param("reserve_date_$biblioNum");
262 my $patron_expiration_date = $query->param("expiration_date_$biblioNum");
264 my $itemtype = $query->param('itemtype') || undef;
265 $itemtype = undef if $itemNum;
267 my $biblio = Koha::Biblios->find($biblioNum);
268 my $rank = $biblio->holds->search( { found => [ { "!=" => "W" }, undef ] } )->count + 1;
270 my $status = CanItemBeReserved( $patron, $item, $branch, { get_from_cache => 1 } )->{status};
271 if( $status eq 'OK' ){
274 push @failed_holds, $status;
279 my $status = CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $itemtype } )->{status};
280 if( $status eq 'OK'){
283 push @failed_holds, $status;
286 # Inserts a null into the 'itemnumber' field of 'reserves' table.
289 my $notes = $query->param('notes_'.$biblioNum)||'';
290 my $item_group_id = $query->param("item_group_id_$biblioNum") || undef;
293 && $reserve_cnt >= $maxreserves )
295 push @failed_holds, 'tooManyReserves';
299 unless ( $can_place_hold_if_available_at_pickup ) {
300 my $items_in_this_library = Koha::Items->search({ biblionumber => $biblioNum, holdingbranch => $branch });
301 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
302 my $nb_of_items_unavailable = $items_in_this_library->search({ -or => { lost => { '!=' => 0 }, damaged => { '!=' => 0 }, } });
303 if ( $items_in_this_library->count > $nb_of_items_issued + $nb_of_items_unavailable ) {
305 push @failed_holds, 'items_available';
309 # Here we actually do the reserveration. Stage 3.
311 my $reserve_id = AddReserve(
313 branchcode => $branch,
314 borrowernumber => $borrowernumber,
315 biblionumber => $biblioNum,
317 reservation_date => $startdate,
318 expiration_date => $patron_expiration_date,
320 title => $biblio->title,
321 itemnumber => $itemNum,
323 itemtype => $itemtype,
324 item_group_id => $item_group_id,
330 push @failed_holds, 'not_placed';
335 print $query->redirect("/cgi-bin/koha/opac-user.pl?" . ( @failed_holds ? "failed_holds=" . join('|',@failed_holds) : q|| ) . "&opac-user-holds=1");
341 # Build hashes of the requested biblio(item)s and items.
345 my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record.
346 foreach my $biblioNumber (@biblionumbers) {
348 my $biblioData = GetBiblioData($biblioNumber);
349 $biblioDataHash{$biblioNumber} = $biblioData;
351 my $biblio = Koha::Biblios->find( $biblioNumber );
354 my $items = Koha::Items->search_ordered(
356 'me.biblionumber' => $biblioNumber,
359 $biblio->host_items->get_column('itemnumber')
363 { prefetch => [ 'issue', 'homebranch', 'holdingbranch' ] }
364 )->filter_by_visible_in_opac({ patron => $patron });
366 $biblioData->{items} = [$items->as_list]; # FIXME Potentially a lot in memory here!
368 # Compute the priority rank.
369 $biblioData->{object} = $biblio;
370 my $reservecount = $biblio->holds->search({ found => [ {"!=" => "W"},undef] })->count;
371 $biblioData->{reservecount} = $reservecount;
372 $biblioData->{rank} = $reservecount + 1;
376 my $requested_reserves_count = scalar( @biblionumbers );
377 if ( $maxreserves && ( $reserves_count + $requested_reserves_count > $maxreserves ) ) {
378 $template->param( new_reserves_allowed => $maxreserves - $reserves_count );
381 $template->param( select_item_types => 1 );
386 # Build the template parameters that will show the info
387 # and items for each biblionumber.
392 my $numBibsAvailable = 0;
393 my $itemdata_enumchron = 0;
394 my $itemdata_ccode = 0;
396 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
397 my $pickup_locations = Koha::Libraries->search({ pickup_location => 1 });
398 $template->param('item_level_itypes' => $itemLevelTypes);
400 my $patron_unblessed = $patron->unblessed;
401 foreach my $biblioNum (@biblionumbers) {
403 # Init the bib item with the choices for branch pickup
406 # Get relevant biblio data.
407 my $biblioData = $biblioDataHash{$biblioNum};
409 $template->param(message=>1, bad_biblionumber=>$biblioNum);
410 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
414 my @not_available_at = ();
415 my $biblio = $biblioData->{object};
416 foreach my $library ( $pickup_locations->as_list ) {
417 push( @not_available_at, $library->branchcode ) unless $biblio->can_be_transferred({ to => $library });
420 my $frameworkcode = GetFrameworkCode( $biblioData->{biblionumber} );
421 $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
422 $biblioLoopIter{title} = $biblioData->{title};
423 $biblioLoopIter{subtitle} = $biblioData->{'subtitle'};
424 $biblioLoopIter{medium} = $biblioData->{medium};
425 $biblioLoopIter{part_number} = $biblioData->{part_number};
426 $biblioLoopIter{part_name} = $biblioData->{part_name};
427 $biblioLoopIter{author} = $biblioData->{author};
428 $biblioLoopIter{rank} = $biblioData->{rank};
429 $biblioLoopIter{reservecount} = $biblioData->{reservecount};
430 $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
431 $biblioLoopIter{object} = $biblio;
433 if (!$itemLevelTypes && $biblioData->{itemtype}) {
434 $biblioLoopIter{translated_description} = $itemtypes->{$biblioData->{itemtype}}{translated_description};
435 $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$biblioData->{itemtype}}{imageurl};
440 $biblioLoopIter{itemLoop} = [];
441 my $numCopiesAvailable = 0;
442 my $numCopiesOPACAvailable = 0;
443 # iterating through all items first to check if any of them available
444 # to pass this value further inside down to IsAvailableForItemLevelRequest to
445 # it's complicated logic to analyse.
446 # (before this loop was inside that sub loop so it was O(n^2) )
447 foreach my $item (@{$biblioData->{items}}) {
449 my $item_info = $item->unblessed;
450 $item_info->{holding_branch} = $item->holding_branch;
451 $item_info->{home_branch} = $item->home_branch;
452 if ($itemLevelTypes) {
453 my $itemtype = $item->itemtype;
454 $item_info->{'imageurl'} = getitemtypeimagelocation( 'opac',
455 $itemtypes->{ $itemtype->itemtype }->{'imageurl'} );
456 $item_info->{'translated_description'} =
457 $itemtypes->{ $itemtype->itemtype }->{translated_description};
461 my $holds = $item->current_holds;
462 if ( my $first_hold = $holds->next ) {
463 $item_info->{first_hold} = $first_hold;
466 $item_info->{checkout} = $item->checkout;
468 # Check of the transferred documents
469 my $transfer = $item->get_transfer;
470 if ( $transfer && $transfer->in_transit ) {
471 $item_info->{transfertwhen} = $transfer->datesent;
472 $item_info->{transfertfrom} = $transfer->frombranch;
473 $item_info->{transfertto} = $transfer->tobranch;
474 $item_info->{nocancel} = 1;
477 # if the items belongs to a host record, show link to host record
478 if ( $item_info->{biblionumber} ne $biblioNum ) {
479 $item_info->{hostbiblionumber} = $item->biblionumber;
480 $item_info->{hosttitle} = Koha::Biblios->find( $item_info->{biblionumber} )->title;
483 my $branch = Koha::Policy::Holds->holds_control_library( $item, $patron );
485 my $policy_holdallowed =
486 CanItemBeReserved( $patron, $item, undef, { get_from_cache => 1 } )->{status} eq 'OK' &&
487 IsAvailableForItemLevelRequest($item, $patron, undef);
489 if ($policy_holdallowed) {
490 my $opac_hold_policy = Koha::CirculationRules->get_opacitemholds_policy( { item => $item, patron => $patron } );
491 if ( $opac_hold_policy ne 'N' ) { # If Y or F
492 $item_info->{available} = 1;
493 $numCopiesOPACAvailable++;
494 $biblioLoopIter{force_hold} = 1 if $opac_hold_policy eq 'F';
496 $numCopiesAvailable++;
498 unless ( $can_place_hold_if_available_at_pickup ) {
499 my $items_in_this_library = Koha::Items->search({ biblionumber => $item->biblionumber, holdingbranch => $item->holdingbranch, notforloan => 0 });
500 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
501 if ( $items_in_this_library->count > $nb_of_items_issued ) {
502 push @not_available_at, $item->holdingbranch;
507 # Show serial enumeration when needed
508 if ($item_info->{enumchron}) {
509 $itemdata_enumchron = 1;
511 # Show collection when needed
512 if ($item_info->{ccode}) {
516 push @{$biblioLoopIter{itemLoop}}, $item_info;
519 itemdata_enumchron => $itemdata_enumchron,
520 itemdata_ccode => $itemdata_ccode,
523 if ($numCopiesAvailable > 0) {
525 $biblioLoopIter{bib_available} = 1;
526 $biblioLoopIter{holdable} = 1;
527 $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable;
529 if ($biblioLoopIter{already_reserved}) {
530 $biblioLoopIter{holdable} = undef;
531 $biblioLoopIter{itemholdable} = undef;
533 if ( $biblioLoopIter{holdable} ) {
534 @not_available_at = uniq @not_available_at;
535 $biblioLoopIter{not_available_at} = \@not_available_at ;
538 unless ( $can_place_hold_if_available_at_pickup ) {
539 @not_available_at = uniq @not_available_at;
540 $biblioLoopIter{not_available_at} = \@not_available_at ;
541 # The record is not holdable is not available at any of the libraries
542 if ( Koha::Libraries->search->count == @not_available_at ) {
543 $biblioLoopIter{holdable} = 0;
547 my $status = CanBookBeReserved( $borrowernumber, $biblioNum )->{status};
548 $biblioLoopIter{holdable} &&= $status eq 'OK';
549 $biblioLoopIter{$status} = 1;
551 if ( $biblioLoopIter{holdable} and C4::Context->preference('AllowHoldItemTypeSelection') ) {
552 # build the allowed item types loop
553 my $rs = $biblio->items->search_ordered(
555 { select => [ { distinct => 'itype' } ],
561 grep { CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $_ } )->{status} eq 'OK' }
562 $rs->get_column('item_type');
564 $biblioLoopIter{allowed_item_types} = \@item_types;
567 if ( $status eq 'recall' ) {
568 $biblioLoopIter{recall} = 1;
571 # For multiple holds per record, if a patron has previously placed a hold,
572 # the patron can only place more holds of the same type. That is, if the
573 # patron placed a record level hold, all the holds the patron places must
574 # be record level. If the patron placed an item level hold, all holds
575 # the patron places must be item level
576 my $forced_hold_level = Koha::Holds->search(
578 borrowernumber => $borrowernumber,
579 biblionumber => $biblioNum,
582 )->forced_hold_level();
583 if ($forced_hold_level) {
584 $biblioLoopIter{force_hold} = 1 if $forced_hold_level eq 'item';
585 $biblioLoopIter{force_hold} = 0 if $forced_hold_level eq 'item_group';
586 $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'record';
587 $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'item_group';
588 $biblioLoopIter{forced_hold_level} = $forced_hold_level;
591 # Pass through any reserve charge
592 $biblioLoopIter{reserve_charge} = GetReserveFee( $patron->id, $biblioNum );
594 push @$biblioLoop, \%biblioLoopIter;
596 $anyholdable = 1 if $biblioLoopIter{holdable};
599 unless ($pickup_locations->count) {
600 $numBibsAvailable = 0;
604 no_pickup_locations => 1
608 if ( $numBibsAvailable == 0 || $anyholdable == 0) {
609 $template->param( none_available => 1 );
612 if (scalar @biblionumbers > 1) {
613 $template->param( multi_hold => 1);
616 my $show_notes=C4::Context->preference('OpacHoldNotes');
617 $template->param(OpacHoldNotes=>$show_notes);
620 $template->param(bibitemloop => $biblioLoop);
621 # can set reserve date in future
622 if ( C4::Context->preference('AllowHoldDateInFuture')
623 && C4::Context->preference('OPACAllowHoldDateInFuture') )
626 reserve_in_future => 1,
630 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };