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 );
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 ($show_holds_count, $show_priority);
64 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
65 m/holds/o and $show_holds_count = 1;
66 m/priority/ and $show_priority = 1;
69 my $patron = Koha::Patrons->find( $borrowernumber, { prefetch => ['categorycode'] } );
70 my $category = $patron->category;
72 my $can_place_hold_if_available_at_pickup = C4::Context->preference('OPACHoldsIfAvailableAtPickup');
73 unless ( $can_place_hold_if_available_at_pickup ) {
74 my @patron_categories = split ',', C4::Context->preference('OPACHoldsIfAvailableAtPickupExceptions');
75 if ( @patron_categories ) {
76 my $categorycode = $patron->categorycode;
77 $can_place_hold_if_available_at_pickup = grep { $_ eq $categorycode } @patron_categories;
81 # check if this user can place a reserve, -1 means use sys pref, 0 means dont block, 1 means block
82 if ( $category->effective_BlockExpiredPatronOpacActions ) {
84 if ( $patron->is_expired ) {
86 # cannot reserve, their card has expired and the rules set mean this is not allowed
87 $template->param( message => 1, expired_patron => 1 );
88 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
93 # Pass through any reserve charge
94 my $reservefee = $category->reservefee;
95 if ( $reservefee > 0){
96 $template->param( RESERVE_CHARGE => $reservefee);
99 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
101 # There are two ways of calling this script, with a single biblio num
102 # or multiple biblio nums.
103 my $biblionumbers = $query->param('biblionumbers');
104 my $reserveMode = $query->param('reserve_mode');
105 if ($reserveMode && ($reserveMode eq 'single')) {
106 my $bib = $query->param('single_bib');
107 $biblionumbers = "$bib/";
109 if (! $biblionumbers) {
110 $biblionumbers = $query->param('biblionumber');
113 if ((! $biblionumbers) && (! $query->param('place_reserve'))) {
114 $template->param(message=>1, no_biblionumber=>1);
115 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
119 # Pass the numbers to the page so they can be fed back
120 # when the hold is confirmed. TODO: Not necessary?
121 $template->param( biblionumbers => $biblionumbers );
123 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
124 my @biblionumbers = split /\//, $biblionumbers;
125 if (($#biblionumbers < 0) && (! $query->param('place_reserve'))) {
127 $template->param(message=>1, no_biblionumber=>1);
128 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
133 # pass the pickup branch along....
134 my $branch = $query->param('branch') || $patron->branchcode || C4::Context->userenv->{branch} || '' ;
135 $template->param( branch => $branch );
139 # Build hashes of the requested biblio(item)s and items.
143 my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record.
144 foreach my $biblioNumber (@biblionumbers) {
146 my $biblioData = GetBiblioData($biblioNumber);
147 $biblioDataHash{$biblioNumber} = $biblioData;
149 my $biblio = Koha::Biblios->find( $biblioNumber );
152 my $marcrecord = $biblio->metadata->record;
154 my $items = Koha::Items->search_ordered(
156 biblionumber => $biblioNumber,
159 $biblio->host_items->get_column('itemnumber')
163 { prefetch => [ 'issue', 'homebranch', 'holdingbranch' ] }
164 )->filter_by_visible_in_opac({ patron => $patron });
166 $biblioData->{items} = [$items->as_list]; # FIXME Potentially a lot in memory here!
168 # Compute the priority rank.
169 $biblioData->{object} = $biblio;
170 my $reservecount = $biblio->holds->search({ found => [ {"!=" => "W"},undef] })->count;
171 $biblioData->{reservecount} = $reservecount;
172 $biblioData->{rank} = $reservecount + 1;
177 # If this is the second time through this script, it
178 # means 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 #item may belong to a host biblio, if yes change biblioNum to hosts bilbionumber
248 my $hostbiblioNum = $item->biblio->biblionumber;
249 if ( $hostbiblioNum ne $biblioNum ) {
250 $biblioNum = $hostbiblioNum;
254 my $biblioData = $biblioDataHash{$biblioNum};
257 # Check for user supplied reserve date
259 if ( C4::Context->preference('AllowHoldDateInFuture')
260 && C4::Context->preference('OPACAllowHoldDateInFuture') )
262 $startdate = $query->param("reserve_date_$biblioNum");
265 my $patron_expiration_date = $query->param("expiration_date_$biblioNum");
267 my $itemtype = $query->param('itemtype') || undef;
268 $itemtype = undef if $itemNum;
270 my $rank = $biblioData->{rank};
271 my $patron = Koha::Patrons->find( $borrowernumber );
273 $canreserve = 1 if CanItemBeReserved( $patron, $item, $branch )->{status} eq 'OK';
277 if CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $itemtype } )->{status} eq 'OK';
279 # Inserts a null into the 'itemnumber' field of 'reserves' table.
282 my $notes = $query->param('notes_'.$biblioNum)||'';
285 && $reserve_cnt >= $maxreserves )
290 unless ( $can_place_hold_if_available_at_pickup ) {
291 my $items_in_this_library = Koha::Items->search({ biblionumber => $biblioNum, holdingbranch => $branch });
292 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
293 my $nb_of_items_unavailable = $items_in_this_library->search({ -or => { lost => { '!=' => 0 }, damaged => { '!=' => 0 }, } });
294 if ( $items_in_this_library->count > $nb_of_items_issued + $nb_of_items_unavailable ) {
299 # Here we actually do the reserveration. Stage 3.
301 my $reserve_id = AddReserve(
303 branchcode => $branch,
304 borrowernumber => $borrowernumber,
305 biblionumber => $biblioNum,
307 reservation_date => $startdate,
308 expiration_date => $patron_expiration_date,
310 title => $biblioData->{title},
311 itemnumber => $itemNum,
313 itemtype => $itemtype,
316 $failed_holds++ unless $reserve_id;
321 print $query->redirect("/cgi-bin/koha/opac-user.pl?" . ( $failed_holds ? "failed_holds=$failed_holds" : q|| ) . "#opac-user-holds");
327 # Here we check that the borrower can actually make reserves Stage 1.
331 my $maxoutstanding = C4::Context->preference("maxoutstanding");
332 my $amountoutstanding = $patron->account->balance;
333 if ( $amountoutstanding && ($amountoutstanding > $maxoutstanding) ) {
334 my $amount = sprintf "%.02f", $amountoutstanding;
335 $template->param( message => 1 );
337 $template->param( too_much_oweing => $amount );
340 if ( $patron->gonenoaddress && ($patron->gonenoaddress == 1) ) {
348 if ( $patron->lost && ($patron->lost == 1) ) {
356 if ( $patron->is_debarred ) {
361 debarred_comment => $patron->debarredcomment,
362 debarred_date => $patron->debarred,
366 my $holds = $patron->holds;
367 my $reserves_count = $holds->count;
368 $template->param( RESERVES => $holds->unblessed );
369 if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) {
370 $template->param( message => 1 );
372 $template->param( too_many_reserves => $holds->count );
375 unless ( $noreserves ) {
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 );
382 unless ($noreserves) {
383 $template->param( select_item_types => 1 );
389 # Build the template parameters that will show the info
390 # and items for each biblionumber.
395 my $numBibsAvailable = 0;
396 my $itemdata_enumchron = 0;
397 my $itemdata_ccode = 0;
399 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
400 my $pickup_locations = Koha::Libraries->search({ pickup_location => 1 });
401 $template->param('item_level_itypes' => $itemLevelTypes);
403 my $patron_unblessed = $patron->unblessed;
404 foreach my $biblioNum (@biblionumbers) {
406 # Init the bib item with the choices for branch pickup
409 # Get relevant biblio data.
410 my $biblioData = $biblioDataHash{$biblioNum};
412 $template->param(message=>1, bad_biblionumber=>$biblioNum);
413 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
417 my @not_available_at = ();
418 my $biblio = $biblioData->{object};
419 foreach my $library ( $pickup_locations->as_list ) {
420 push( @not_available_at, $library->branchcode ) unless $biblio->can_be_transferred({ to => $library });
423 my $frameworkcode = GetFrameworkCode( $biblioData->{biblionumber} );
424 $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
425 $biblioLoopIter{title} = $biblioData->{title};
426 $biblioLoopIter{subtitle} = $biblioData->{'subtitle'};
427 $biblioLoopIter{medium} = $biblioData->{medium};
428 $biblioLoopIter{part_number} = $biblioData->{part_number};
429 $biblioLoopIter{part_name} = $biblioData->{part_name};
430 $biblioLoopIter{author} = $biblioData->{author};
431 $biblioLoopIter{rank} = $biblioData->{rank};
432 $biblioLoopIter{reservecount} = $biblioData->{reservecount};
433 $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
434 $biblioLoopIter{reqholdnotes}=0; #TODO: For future use
436 if (!$itemLevelTypes && $biblioData->{itemtype}) {
437 $biblioLoopIter{translated_description} = $itemtypes->{$biblioData->{itemtype}}{translated_description};
438 $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$biblioData->{itemtype}}{imageurl};
443 $biblioLoopIter{itemLoop} = [];
444 my $numCopiesAvailable = 0;
445 my $numCopiesOPACAvailable = 0;
446 # iterating through all items first to check if any of them available
447 # to pass this value further inside down to IsAvailableForItemLevelRequest to
448 # it's complicated logic to analyse.
449 # (before this loop was inside that sub loop so it was O(n^2) )
450 my $items_any_available;
451 $items_any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblioNum, patron => $patron }) if $patron;
452 foreach my $item (@{$biblioData->{items}}) {
454 my $item_info = $item->unblessed;
455 $item_info->{holding_branch} = $item->holding_branch;
456 $item_info->{home_branch} = $item->home_branch;
457 if ($itemLevelTypes) {
458 my $itemtype = $item->itemtype;
459 $item_info->{'imageurl'} = getitemtypeimagelocation( 'opac',
460 $itemtypes->{ $itemtype->itemtype }->{'imageurl'} );
461 $item_info->{'translated_description'} =
462 $itemtypes->{ $itemtype->itemtype }->{translated_description};
466 my $holds = $item->current_holds;
467 if ( my $first_hold = $holds->next ) {
468 $item_info->{first_hold} = $first_hold;
471 $item_info->{checkout} = $item->checkout;
473 # Check of the transferred documents
474 my $transfer = $item->get_transfer;
475 if ( $transfer && $transfer->in_transit ) {
476 $item_info->{transfertwhen} = $transfer->datesent;
477 $item_info->{transfertfrom} = $transfer->frombranch;
478 $item_info->{transfertto} = $transfer->tobranch;
479 $item_info->{nocancel} = 1;
482 # if the items belongs to a host record, show link to host record
483 if ( $item_info->{biblionumber} ne $biblioNum ) {
484 $item_info->{hostbiblionumber} = $item->biblionumber;
485 $item_info->{hosttitle} = Koha::Biblios->find( $item_info->{biblionumber} )->title;
488 my $branch = GetReservesControlBranch( $item_info, $patron_unblessed );
490 # items_any_available defined outside of the current loop,
491 # so we avoiding loop inside IsAvailableForItemLevelRequest:
492 my $policy_holdallowed =
493 CanItemBeReserved( $patron, $item )->{status} eq 'OK' &&
494 IsAvailableForItemLevelRequest($item, $patron, undef, $items_any_available);
496 if ($policy_holdallowed) {
497 my $opac_hold_policy = Koha::CirculationRules->get_opacitemholds_policy( { item => $item, patron => $patron } );
498 if ( $opac_hold_policy ne 'N' ) { # If Y or F
499 $item_info->{available} = 1;
500 $numCopiesOPACAvailable++;
501 $biblioLoopIter{force_hold} = 1 if $opac_hold_policy eq 'F';
503 $numCopiesAvailable++;
505 unless ( $can_place_hold_if_available_at_pickup ) {
506 my $items_in_this_library = Koha::Items->search({ biblionumber => $item->biblionumber, holdingbranch => $item->holdingbranch });
507 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
508 if ( $items_in_this_library->count > $nb_of_items_issued ) {
509 push @not_available_at, $item->holdingbranch;
514 # Show serial enumeration when needed
515 if ($item_info->{enumchron}) {
516 $itemdata_enumchron = 1;
518 # Show collection when needed
519 if ($item_info->{ccode}) {
523 push @{$biblioLoopIter{itemLoop}}, $item_info;
526 itemdata_enumchron => $itemdata_enumchron,
527 itemdata_ccode => $itemdata_ccode,
530 if ($numCopiesAvailable > 0) {
532 $biblioLoopIter{bib_available} = 1;
533 $biblioLoopIter{holdable} = 1;
534 $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable;
536 if ($biblioLoopIter{already_reserved}) {
537 $biblioLoopIter{holdable} = undef;
538 $biblioLoopIter{itemholdable} = undef;
540 if ( $biblioLoopIter{holdable} ) {
541 @not_available_at = uniq @not_available_at;
542 $biblioLoopIter{not_available_at} = \@not_available_at ;
545 unless ( $can_place_hold_if_available_at_pickup ) {
546 @not_available_at = uniq @not_available_at;
547 $biblioLoopIter{not_available_at} = \@not_available_at ;
548 # The record is not holdable is not available at any of the libraries
549 if ( Koha::Libraries->search->count == @not_available_at ) {
550 $biblioLoopIter{holdable} = 0;
554 my $status = CanBookBeReserved( $borrowernumber, $biblioNum )->{status};
555 $biblioLoopIter{holdable} &&= $status eq 'OK';
556 $biblioLoopIter{$status} = 1;
558 if ( $biblioLoopIter{holdable} and C4::Context->preference('AllowHoldItemTypeSelection') ) {
559 # build the allowed item types loop
560 my $rs = $biblio->items->search_ordered(
562 { select => [ { distinct => 'itype' } ],
568 grep { CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $_ } )->{status} eq 'OK' }
569 $rs->get_column('item_type');
571 $biblioLoopIter{allowed_item_types} = \@item_types;
574 if ( $status eq 'recall' ) {
575 $biblioLoopIter{recall} = 1;
578 # For multiple holds per record, if a patron has previously placed a hold,
579 # the patron can only place more holds of the same type. That is, if the
580 # patron placed a record level hold, all the holds the patron places must
581 # be record level. If the patron placed an item level hold, all holds
582 # the patron places must be item level
583 my $forced_hold_level = Koha::Holds->search(
585 borrowernumber => $borrowernumber,
586 biblionumber => $biblioNum,
589 )->forced_hold_level();
590 if ($forced_hold_level) {
591 $biblioLoopIter{force_hold} = 1 if $forced_hold_level eq 'item';
592 $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'record';
593 $biblioLoopIter{forced_hold_level} = $forced_hold_level;
597 push @$biblioLoop, \%biblioLoopIter;
599 $anyholdable = 1 if $biblioLoopIter{holdable};
602 unless ($pickup_locations->count) {
603 $numBibsAvailable = 0;
607 no_pickup_locations => 1
611 if ( $numBibsAvailable == 0 || $anyholdable == 0) {
612 $template->param( none_available => 1 );
615 if (scalar @biblionumbers > 1) {
616 $template->param( multi_hold => 1);
619 my $show_notes=C4::Context->preference('OpacHoldNotes');
620 $template->param(OpacHoldNotes=>$show_notes);
623 $template->param(bibitemloop => $biblioLoop);
624 # can set reserve date in future
626 C4::Context->preference( 'AllowHoldDateInFuture' ) &&
627 C4::Context->preference( 'OPACAllowHoldDateInFuture' )
630 reserve_in_future => 1,
634 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };