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 GetReservesControlBranch ItemsAnyAvailableAndNotRestricted 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;
43 use List::MoreUtils qw( uniq );
45 my $maxreserves = C4::Context->preference("maxreserves");
49 # if OPACHoldRequests (for placing holds) is disabled, leave immediately
50 if ( ! C4::Context->preference('OPACHoldRequests') ) {
51 print $query->redirect("/cgi-bin/koha/errors/404.pl");
55 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
57 template_name => "opac-reserve.tt",
63 my $patron = Koha::Patrons->find( $borrowernumber, { prefetch => ['categorycode'] } );
64 my $category = $patron->category;
66 my $can_place_hold_if_available_at_pickup = C4::Context->preference('OPACHoldsIfAvailableAtPickup');
67 unless ( $can_place_hold_if_available_at_pickup ) {
68 my @patron_categories = split ',', C4::Context->preference('OPACHoldsIfAvailableAtPickupExceptions');
69 if ( @patron_categories ) {
70 my $categorycode = $patron->categorycode;
71 $can_place_hold_if_available_at_pickup = grep { $_ eq $categorycode } @patron_categories;
75 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
77 # There are two ways of calling this script, with a single biblio num
78 # or multiple biblio nums.
79 my $biblionumbers = $query->param('biblionumbers');
80 my $reserveMode = $query->param('reserve_mode');
81 if ($reserveMode && ($reserveMode eq 'single')) {
82 my $bib = $query->param('single_bib');
83 $biblionumbers = "$bib/";
85 if (! $biblionumbers) {
86 $biblionumbers = $query->param('biblionumber');
89 if ((! $biblionumbers) && (! $query->param('place_reserve'))) {
90 $template->param(message=>1, no_biblionumber=>1);
91 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
95 # Pass the numbers to the page so they can be fed back
96 # when the hold is confirmed. TODO: Not necessary?
97 $template->param( biblionumbers => $biblionumbers );
99 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
100 my @biblionumbers = split /\//, $biblionumbers;
101 if (($#biblionumbers < 0) && (! $query->param('place_reserve'))) {
103 $template->param(message=>1, no_biblionumber=>1);
104 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
110 # Here we check that the borrower can actually make reserves Stage 1.
114 if ( $category->effective_BlockExpiredPatronOpacActions ) {
115 if ( $patron->is_expired ) {
116 # cannot reserve, their card has expired and the rules set mean this is not allowed
118 $template->param( message => 1, expired_patron => 1 );
122 my $maxoutstanding = C4::Context->preference("maxoutstanding");
123 my $amountoutstanding = $patron->account->balance;
124 if ( $amountoutstanding && ($amountoutstanding > $maxoutstanding) ) {
125 my $amount = sprintf "%.02f", $amountoutstanding;
126 $template->param( message => 1 );
128 $template->param( too_much_oweing => $amount );
131 if ( $patron->gonenoaddress && ($patron->gonenoaddress == 1) ) {
139 if ( $patron->lost && ($patron->lost == 1) ) {
147 if ( $patron->is_debarred ) {
152 debarred_comment => $patron->debarredcomment,
153 debarred_date => $patron->debarred,
157 my $holds = $patron->holds;
158 my $reserves_count = $holds->count;
159 $template->param( RESERVES => $holds->unblessed );
160 if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) {
161 $template->param( message => 1 );
163 $template->param( too_many_reserves => $holds->count );
167 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
172 # pass the pickup branch along....
173 my $branch = $query->param('branch') || $patron->branchcode || C4::Context->userenv->{branch} || '' ;
174 $template->param( branch => $branch );
178 # Here we are carrying out the hold request, possibly
179 # with a specific item for each biblionumber.
182 if ( $query->param('place_reserve') ) {
185 $reserve_cnt = $patron->holds->count;
188 # List is composed of alternating biblio/item/branch
189 my $selectedItems = $query->param('selecteditems');
191 if ($query->param('reserve_mode') eq 'single') {
192 # This indicates non-JavaScript mode, so there was
193 # only a single biblio number selected.
194 my $bib = $query->param('single_bib');
195 my $item = $query->param("checkitem_$bib");
196 if ($item eq 'any') {
199 my $branch = $query->param('branch');
200 $selectedItems = "$bib/$item/$branch/";
203 $selectedItems =~ s!/$!!;
204 my @selectedItems = split /\//, $selectedItems, -1;
206 # Make sure there is a biblionum/itemnum/branch triplet for each item.
207 # The itemnum can be 'any', meaning next available.
208 my $selectionCount = @selectedItems;
209 if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
210 $template->param(message=>1, bad_data=>1);
211 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
215 my $failed_holds = 0;
216 while (@selectedItems) {
217 my $biblioNum = shift(@selectedItems);
218 my $itemNum = shift(@selectedItems);
219 my $branch = shift(@selectedItems); # i.e., branch code, not name
223 my $singleBranchMode = Koha::Libraries->search->count == 1;
224 if ( $singleBranchMode || ! C4::Context->preference("OPACAllowUserToChooseBranch") )
225 { # single branch mode or disabled user choosing
226 $branch = $patron->branchcode;
229 # FIXME We shouldn't need to fetch the item here
230 my $item = $itemNum ? Koha::Items->find( $itemNum ) : undef;
231 # When choosing a specific item, the default pickup library should be dictated by the default hold policy
232 if ( ! C4::Context->preference("OPACAllowUserToChooseBranch") && $item ) {
233 my $type = $item->effective_itemtype;
234 my $rule = GetBranchItemRule( $patron->branchcode, $type );
236 if ( $rule->{hold_fulfillment_policy} eq 'any' || $rule->{hold_fulfillment_policy} eq 'patrongroup' ) {
237 $branch = $patron->branchcode;
238 } elsif ( $rule->{hold_fulfillment_policy} eq 'holdgroup' ){
239 $branch = $item->homebranch;
241 my $policy = $rule->{hold_fulfillment_policy};
242 $branch = $item->$policy;
246 # if we have an item, we are placing the hold on the item's bib, in case of analytics
248 $biblioNum = $item->biblionumber;
251 # Check for user supplied reserve date
253 if ( C4::Context->preference('AllowHoldDateInFuture')
254 && C4::Context->preference('OPACAllowHoldDateInFuture') )
256 $startdate = $query->param("reserve_date_$biblioNum");
259 my $patron_expiration_date = $query->param("expiration_date_$biblioNum");
261 my $itemtype = $query->param('itemtype') || undef;
262 $itemtype = undef if $itemNum;
264 my $biblio = Koha::Biblios->find($biblioNum);
265 my $rank = $biblio->holds->search( { found => [ { "!=" => "W" }, undef ] } )->count + 1;
267 $canreserve = 1 if CanItemBeReserved( $patron, $item, $branch )->{status} eq 'OK';
271 if CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $itemtype } )->{status} eq 'OK';
273 # Inserts a null into the 'itemnumber' field of 'reserves' table.
276 my $notes = $query->param('notes_'.$biblioNum)||'';
279 && $reserve_cnt >= $maxreserves )
284 unless ( $can_place_hold_if_available_at_pickup ) {
285 my $items_in_this_library = Koha::Items->search({ biblionumber => $biblioNum, holdingbranch => $branch });
286 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
287 my $nb_of_items_unavailable = $items_in_this_library->search({ -or => { lost => { '!=' => 0 }, damaged => { '!=' => 0 }, } });
288 if ( $items_in_this_library->count > $nb_of_items_issued + $nb_of_items_unavailable ) {
293 # Here we actually do the reserveration. Stage 3.
295 my $reserve_id = AddReserve(
297 branchcode => $branch,
298 borrowernumber => $borrowernumber,
299 biblionumber => $biblioNum,
301 reservation_date => $startdate,
302 expiration_date => $patron_expiration_date,
304 title => $biblio->title,
305 itemnumber => $itemNum,
307 itemtype => $itemtype,
310 $failed_holds++ unless $reserve_id;
315 print $query->redirect("/cgi-bin/koha/opac-user.pl?" . ( $failed_holds ? "failed_holds=$failed_holds" : q|| ) . "#opac-user-holds");
321 # Build hashes of the requested biblio(item)s and items.
325 my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record.
326 foreach my $biblioNumber (@biblionumbers) {
328 my $biblioData = GetBiblioData($biblioNumber);
329 $biblioDataHash{$biblioNumber} = $biblioData;
331 my $biblio = Koha::Biblios->find( $biblioNumber );
334 my $items = Koha::Items->search_ordered(
336 biblionumber => $biblioNumber,
339 $biblio->host_items->get_column('itemnumber')
343 { prefetch => [ 'issue', 'homebranch', 'holdingbranch' ] }
344 )->filter_by_visible_in_opac({ patron => $patron });
346 $biblioData->{items} = [$items->as_list]; # FIXME Potentially a lot in memory here!
348 # Compute the priority rank.
349 $biblioData->{object} = $biblio;
350 my $reservecount = $biblio->holds->search({ found => [ {"!=" => "W"},undef] })->count;
351 $biblioData->{reservecount} = $reservecount;
352 $biblioData->{rank} = $reservecount + 1;
356 my $requested_reserves_count = scalar( @biblionumbers );
357 if ( $maxreserves && ( $reserves_count + $requested_reserves_count > $maxreserves ) ) {
358 $template->param( new_reserves_allowed => $maxreserves - $reserves_count );
361 $template->param( select_item_types => 1 );
366 # Build the template parameters that will show the info
367 # and items for each biblionumber.
372 my $numBibsAvailable = 0;
373 my $itemdata_enumchron = 0;
374 my $itemdata_ccode = 0;
376 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
377 my $pickup_locations = Koha::Libraries->search({ pickup_location => 1 });
378 $template->param('item_level_itypes' => $itemLevelTypes);
380 my $patron_unblessed = $patron->unblessed;
381 foreach my $biblioNum (@biblionumbers) {
383 # Init the bib item with the choices for branch pickup
386 # Get relevant biblio data.
387 my $biblioData = $biblioDataHash{$biblioNum};
389 $template->param(message=>1, bad_biblionumber=>$biblioNum);
390 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
394 my @not_available_at = ();
395 my $biblio = $biblioData->{object};
396 foreach my $library ( $pickup_locations->as_list ) {
397 push( @not_available_at, $library->branchcode ) unless $biblio->can_be_transferred({ to => $library });
400 my $frameworkcode = GetFrameworkCode( $biblioData->{biblionumber} );
401 $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
402 $biblioLoopIter{title} = $biblioData->{title};
403 $biblioLoopIter{subtitle} = $biblioData->{'subtitle'};
404 $biblioLoopIter{medium} = $biblioData->{medium};
405 $biblioLoopIter{part_number} = $biblioData->{part_number};
406 $biblioLoopIter{part_name} = $biblioData->{part_name};
407 $biblioLoopIter{author} = $biblioData->{author};
408 $biblioLoopIter{rank} = $biblioData->{rank};
409 $biblioLoopIter{reservecount} = $biblioData->{reservecount};
410 $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
412 if (!$itemLevelTypes && $biblioData->{itemtype}) {
413 $biblioLoopIter{translated_description} = $itemtypes->{$biblioData->{itemtype}}{translated_description};
414 $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$biblioData->{itemtype}}{imageurl};
419 $biblioLoopIter{itemLoop} = [];
420 my $numCopiesAvailable = 0;
421 my $numCopiesOPACAvailable = 0;
422 # iterating through all items first to check if any of them available
423 # to pass this value further inside down to IsAvailableForItemLevelRequest to
424 # it's complicated logic to analyse.
425 # (before this loop was inside that sub loop so it was O(n^2) )
426 my $items_any_available;
427 $items_any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblioNum, patron => $patron }) if $patron;
428 foreach my $item (@{$biblioData->{items}}) {
430 my $item_info = $item->unblessed;
431 $item_info->{holding_branch} = $item->holding_branch;
432 $item_info->{home_branch} = $item->home_branch;
433 if ($itemLevelTypes) {
434 my $itemtype = $item->itemtype;
435 $item_info->{'imageurl'} = getitemtypeimagelocation( 'opac',
436 $itemtypes->{ $itemtype->itemtype }->{'imageurl'} );
437 $item_info->{'translated_description'} =
438 $itemtypes->{ $itemtype->itemtype }->{translated_description};
442 my $holds = $item->current_holds;
443 if ( my $first_hold = $holds->next ) {
444 $item_info->{first_hold} = $first_hold;
447 $item_info->{checkout} = $item->checkout;
449 # Check of the transferred documents
450 my $transfer = $item->get_transfer;
451 if ( $transfer && $transfer->in_transit ) {
452 $item_info->{transfertwhen} = $transfer->datesent;
453 $item_info->{transfertfrom} = $transfer->frombranch;
454 $item_info->{transfertto} = $transfer->tobranch;
455 $item_info->{nocancel} = 1;
458 # if the items belongs to a host record, show link to host record
459 if ( $item_info->{biblionumber} ne $biblioNum ) {
460 $item_info->{hostbiblionumber} = $item->biblionumber;
461 $item_info->{hosttitle} = Koha::Biblios->find( $item_info->{biblionumber} )->title;
464 my $branch = GetReservesControlBranch( $item_info, $patron_unblessed );
466 # items_any_available defined outside of the current loop,
467 # so we avoiding loop inside IsAvailableForItemLevelRequest:
468 my $policy_holdallowed =
469 CanItemBeReserved( $patron, $item )->{status} eq 'OK' &&
470 IsAvailableForItemLevelRequest($item, $patron, undef, $items_any_available);
472 if ($policy_holdallowed) {
473 my $opac_hold_policy = Koha::CirculationRules->get_opacitemholds_policy( { item => $item, patron => $patron } );
474 if ( $opac_hold_policy ne 'N' ) { # If Y or F
475 $item_info->{available} = 1;
476 $numCopiesOPACAvailable++;
477 $biblioLoopIter{force_hold} = 1 if $opac_hold_policy eq 'F';
479 $numCopiesAvailable++;
481 unless ( $can_place_hold_if_available_at_pickup ) {
482 my $items_in_this_library = Koha::Items->search({ biblionumber => $item->biblionumber, holdingbranch => $item->holdingbranch });
483 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
484 if ( $items_in_this_library->count > $nb_of_items_issued ) {
485 push @not_available_at, $item->holdingbranch;
490 # Show serial enumeration when needed
491 if ($item_info->{enumchron}) {
492 $itemdata_enumchron = 1;
494 # Show collection when needed
495 if ($item_info->{ccode}) {
499 push @{$biblioLoopIter{itemLoop}}, $item_info;
502 itemdata_enumchron => $itemdata_enumchron,
503 itemdata_ccode => $itemdata_ccode,
506 if ($numCopiesAvailable > 0) {
508 $biblioLoopIter{bib_available} = 1;
509 $biblioLoopIter{holdable} = 1;
510 $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable;
512 if ($biblioLoopIter{already_reserved}) {
513 $biblioLoopIter{holdable} = undef;
514 $biblioLoopIter{itemholdable} = undef;
516 if ( $biblioLoopIter{holdable} ) {
517 @not_available_at = uniq @not_available_at;
518 $biblioLoopIter{not_available_at} = \@not_available_at ;
521 unless ( $can_place_hold_if_available_at_pickup ) {
522 @not_available_at = uniq @not_available_at;
523 $biblioLoopIter{not_available_at} = \@not_available_at ;
524 # The record is not holdable is not available at any of the libraries
525 if ( Koha::Libraries->search->count == @not_available_at ) {
526 $biblioLoopIter{holdable} = 0;
530 my $status = CanBookBeReserved( $borrowernumber, $biblioNum )->{status};
531 $biblioLoopIter{holdable} &&= $status eq 'OK';
532 $biblioLoopIter{$status} = 1;
534 if ( $biblioLoopIter{holdable} and C4::Context->preference('AllowHoldItemTypeSelection') ) {
535 # build the allowed item types loop
536 my $rs = $biblio->items->search_ordered(
538 { select => [ { distinct => 'itype' } ],
544 grep { CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $_ } )->{status} eq 'OK' }
545 $rs->get_column('item_type');
547 $biblioLoopIter{allowed_item_types} = \@item_types;
550 if ( $status eq 'recall' ) {
551 $biblioLoopIter{recall} = 1;
554 # For multiple holds per record, if a patron has previously placed a hold,
555 # the patron can only place more holds of the same type. That is, if the
556 # patron placed a record level hold, all the holds the patron places must
557 # be record level. If the patron placed an item level hold, all holds
558 # the patron places must be item level
559 my $forced_hold_level = Koha::Holds->search(
561 borrowernumber => $borrowernumber,
562 biblionumber => $biblioNum,
565 )->forced_hold_level();
566 if ($forced_hold_level) {
567 $biblioLoopIter{force_hold} = 1 if $forced_hold_level eq 'item';
568 $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'record';
569 $biblioLoopIter{forced_hold_level} = $forced_hold_level;
572 # Pass through any reserve charge
573 $biblioLoopIter{reserve_charge} = GetReserveFee( $patron->id, $biblioNum );
575 push @$biblioLoop, \%biblioLoopIter;
577 $anyholdable = 1 if $biblioLoopIter{holdable};
580 unless ($pickup_locations->count) {
581 $numBibsAvailable = 0;
585 no_pickup_locations => 1
589 if ( $numBibsAvailable == 0 || $anyholdable == 0) {
590 $template->param( none_available => 1 );
593 if (scalar @biblionumbers > 1) {
594 $template->param( multi_hold => 1);
597 my $show_notes=C4::Context->preference('OpacHoldNotes');
598 $template->param(OpacHoldNotes=>$show_notes);
601 $template->param(bibitemloop => $biblioLoop);
602 # can set reserve date in future
604 C4::Context->preference( 'AllowHoldDateInFuture' ) &&
605 C4::Context->preference( 'OPACAllowHoldDateInFuture' )
608 reserve_in_future => 1,
612 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };