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 GetTransfers );
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::DateUtils qw( dt_from_string output_pref );
38 use Koha::CirculationRules;
44 use List::MoreUtils qw( uniq );
46 my $maxreserves = C4::Context->preference("maxreserves");
50 # if OPACHoldRequests (for placing holds) is disabled, leave immediately
51 if ( ! C4::Context->preference('OPACHoldRequests') ) {
52 print $query->redirect("/cgi-bin/koha/errors/404.pl");
56 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
58 template_name => "opac-reserve.tt",
64 my ($show_holds_count, $show_priority);
65 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
66 m/holds/o and $show_holds_count = 1;
67 m/priority/ and $show_priority = 1;
70 my $patron = Koha::Patrons->find( $borrowernumber, { prefetch => ['categorycode'] } );
71 my $category = $patron->category;
73 my $can_place_hold_if_available_at_pickup = C4::Context->preference('OPACHoldsIfAvailableAtPickup');
74 unless ( $can_place_hold_if_available_at_pickup ) {
75 my @patron_categories = split ',', C4::Context->preference('OPACHoldsIfAvailableAtPickupExceptions');
76 if ( @patron_categories ) {
77 my $categorycode = $patron->categorycode;
78 $can_place_hold_if_available_at_pickup = grep { $_ eq $categorycode } @patron_categories;
82 # check if this user can place a reserve, -1 means use sys pref, 0 means dont block, 1 means block
83 if ( $category->effective_BlockExpiredPatronOpacActions ) {
85 if ( $patron->is_expired ) {
87 # cannot reserve, their card has expired and the rules set mean this is not allowed
88 $template->param( message => 1, expired_patron => 1 );
89 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
94 # Pass through any reserve charge
95 my $reservefee = $category->reservefee;
96 if ( $reservefee > 0){
97 $template->param( RESERVE_CHARGE => $reservefee);
100 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
102 # There are two ways of calling this script, with a single biblio num
103 # or multiple biblio nums.
104 my $biblionumbers = $query->param('biblionumbers');
105 my $reserveMode = $query->param('reserve_mode');
106 if ($reserveMode && ($reserveMode eq 'single')) {
107 my $bib = $query->param('single_bib');
108 $biblionumbers = "$bib/";
110 if (! $biblionumbers) {
111 $biblionumbers = $query->param('biblionumber');
114 if ((! $biblionumbers) && (! $query->param('place_reserve'))) {
115 $template->param(message=>1, no_biblionumber=>1);
116 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
120 # Pass the numbers to the page so they can be fed back
121 # when the hold is confirmed. TODO: Not necessary?
122 $template->param( biblionumbers => $biblionumbers );
124 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
125 my @biblionumbers = split /\//, $biblionumbers;
126 if (($#biblionumbers < 0) && (! $query->param('place_reserve'))) {
128 $template->param(message=>1, no_biblionumber=>1);
129 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
134 # pass the pickup branch along....
135 my $branch = $query->param('branch') || $patron->branchcode || C4::Context->userenv->{branch} || '' ;
136 $template->param( branch => $branch );
140 # Build hashes of the requested biblio(item)s and items.
144 my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record.
145 foreach my $biblioNumber (@biblionumbers) {
147 my $biblioData = GetBiblioData($biblioNumber);
148 $biblioDataHash{$biblioNumber} = $biblioData;
150 my $biblio = Koha::Biblios->find( $biblioNumber );
153 my $marcrecord = $biblio->metadata->record;
155 my $items = Koha::Items->search_ordered(
157 biblionumber => $biblioNumber,
160 $biblio->host_items->get_column('itemnumber')
164 { prefetch => [ 'issue', 'homebranch', 'holdingbranch' ] }
165 )->filter_by_visible_in_opac({ patron => $patron });
167 $biblioData->{items} = [$items->as_list]; # FIXME Potentially a lot in memory here!
169 # Compute the priority rank.
170 $biblioData->{object} = $biblio;
171 my $holds = $biblio->holds;
172 my $rank = $holds->count;
173 $biblioData->{reservecount} = 1; # new reserve
174 while ( my $hold = $holds->next ) {
175 if ( $hold->is_waiting ) {
179 $biblioData->{reservecount}++;
182 $biblioData->{rank} = $rank + 1;
187 # If this is the second time through this script, it
188 # means we are carrying out the hold request, possibly
189 # with a specific item for each biblionumber.
192 if ( $query->param('place_reserve') ) {
195 $reserve_cnt = $patron->holds->count;
198 # List is composed of alternating biblio/item/branch
199 my $selectedItems = $query->param('selecteditems');
201 if ($query->param('reserve_mode') eq 'single') {
202 # This indicates non-JavaScript mode, so there was
203 # only a single biblio number selected.
204 my $bib = $query->param('single_bib');
205 my $item = $query->param("checkitem_$bib");
206 if ($item eq 'any') {
209 my $branch = $query->param('branch');
210 $selectedItems = "$bib/$item/$branch/";
213 $selectedItems =~ s!/$!!;
214 my @selectedItems = split /\//, $selectedItems, -1;
216 # Make sure there is a biblionum/itemnum/branch triplet for each item.
217 # The itemnum can be 'any', meaning next available.
218 my $selectionCount = @selectedItems;
219 if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
220 $template->param(message=>1, bad_data=>1);
221 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
225 my $failed_holds = 0;
226 while (@selectedItems) {
227 my $biblioNum = shift(@selectedItems);
228 my $itemNum = shift(@selectedItems);
229 my $branch = shift(@selectedItems); # i.e., branch code, not name
233 my $singleBranchMode = Koha::Libraries->search->count == 1;
234 if ( $singleBranchMode || ! C4::Context->preference("OPACAllowUserToChooseBranch") )
235 { # single branch mode or disabled user choosing
236 $branch = $patron->branchcode;
239 # FIXME We shouldn't need to fetch the item here
240 my $item = $itemNum ? Koha::Items->find( $itemNum ) : undef;
241 # When choosing a specific item, the default pickup library should be dictated by the default hold policy
242 if ( ! C4::Context->preference("OPACAllowUserToChooseBranch") && $item ) {
243 my $type = $item->effective_itemtype;
244 my $rule = GetBranchItemRule( $patron->branchcode, $type );
246 if ( $rule->{hold_fulfillment_policy} eq 'any' || $rule->{hold_fulfillment_policy} eq 'patrongroup' ) {
247 $branch = $patron->branchcode;
248 } elsif ( $rule->{hold_fulfillment_policy} eq 'holdgroup' ){
249 $branch = $item->homebranch;
251 my $policy = $rule->{hold_fulfillment_policy};
252 $branch = $item->$policy;
256 #item may belong to a host biblio, if yes change biblioNum to hosts bilbionumber
258 my $hostbiblioNum = $item->biblio->biblionumber;
259 if ( $hostbiblioNum ne $biblioNum ) {
260 $biblioNum = $hostbiblioNum;
264 my $biblioData = $biblioDataHash{$biblioNum};
267 # Check for user supplied reserve date
269 if ( C4::Context->preference('AllowHoldDateInFuture')
270 && C4::Context->preference('OPACAllowHoldDateInFuture') )
272 $startdate = $query->param("reserve_date_$biblioNum");
275 my $patron_expiration_date = $query->param("expiration_date_$biblioNum");
277 my $itemtype = $query->param('itemtype') || undef;
278 $itemtype = undef if $itemNum;
280 my $rank = $biblioData->{rank};
281 my $patron = Koha::Patrons->find( $borrowernumber );
283 $canreserve = 1 if CanItemBeReserved( $patron, $item, $branch )->{status} eq 'OK';
287 if CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $itemtype } )->{status} eq 'OK';
289 # Inserts a null into the 'itemnumber' field of 'reserves' table.
292 my $notes = $query->param('notes_'.$biblioNum)||'';
295 && $reserve_cnt >= $maxreserves )
300 unless ( $can_place_hold_if_available_at_pickup ) {
301 my $items_in_this_library = Koha::Items->search({ biblionumber => $biblioNum, holdingbranch => $branch });
302 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
303 my $nb_of_items_unavailable = $items_in_this_library->search({ -or => { lost => { '!=' => 0 }, damaged => { '!=' => 0 }, } });
304 if ( $items_in_this_library->count > $nb_of_items_issued + $nb_of_items_unavailable ) {
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 => $biblioData->{title},
321 itemnumber => $itemNum,
323 itemtype => $itemtype,
326 $failed_holds++ unless $reserve_id;
331 print $query->redirect("/cgi-bin/koha/opac-user.pl?" . ( $failed_holds ? "failed_holds=$failed_holds" : q|| ) . "#opac-user-holds");
337 # Here we check that the borrower can actually make reserves Stage 1.
341 my $maxoutstanding = C4::Context->preference("maxoutstanding");
342 $template->param( noreserve => 1 ) unless $maxoutstanding;
343 my $amountoutstanding = $patron->account->balance;
344 if ( $amountoutstanding && ($amountoutstanding > $maxoutstanding) ) {
345 my $amount = sprintf "%.02f", $amountoutstanding;
346 $template->param( message => 1 );
348 $template->param( too_much_oweing => $amount );
351 if ( $patron->gonenoaddress && ($patron->gonenoaddress == 1) ) {
359 if ( $patron->lost && ($patron->lost == 1) ) {
367 if ( $patron->is_debarred ) {
372 debarred_comment => $patron->debarredcomment,
373 debarred_date => $patron->debarred,
377 my $holds = $patron->holds;
378 my $reserves_count = $holds->count;
379 $template->param( RESERVES => $holds->unblessed );
380 if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) {
381 $template->param( message => 1 );
383 $template->param( too_many_reserves => $holds->count );
386 unless ( $noreserves ) {
387 my $requested_reserves_count = scalar( @biblionumbers );
388 if ( $maxreserves && ( $reserves_count + $requested_reserves_count > $maxreserves ) ) {
389 $template->param( new_reserves_allowed => $maxreserves - $reserves_count );
393 unless ($noreserves) {
394 $template->param( select_item_types => 1 );
400 # Build the template parameters that will show the info
401 # and items for each biblionumber.
406 my $numBibsAvailable = 0;
407 my $itemdata_enumchron = 0;
408 my $itemdata_ccode = 0;
410 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
411 my $pickup_locations = Koha::Libraries->search({ pickup_location => 1 });
412 $template->param('item_level_itypes' => $itemLevelTypes);
414 my $patron_unblessed = $patron->unblessed;
415 foreach my $biblioNum (@biblionumbers) {
417 # Init the bib item with the choices for branch pickup
420 # Get relevant biblio data.
421 my $biblioData = $biblioDataHash{$biblioNum};
423 $template->param(message=>1, bad_biblionumber=>$biblioNum);
424 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
428 my @not_available_at = ();
429 my $biblio = $biblioData->{object};
430 foreach my $library ( $pickup_locations->as_list ) {
431 push( @not_available_at, $library->branchcode ) unless $biblio->can_be_transferred({ to => $library });
434 my $frameworkcode = GetFrameworkCode( $biblioData->{biblionumber} );
435 $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
436 $biblioLoopIter{title} = $biblioData->{title};
437 $biblioLoopIter{subtitle} = $biblioData->{'subtitle'};
438 $biblioLoopIter{medium} = $biblioData->{medium};
439 $biblioLoopIter{part_number} = $biblioData->{part_number};
440 $biblioLoopIter{part_name} = $biblioData->{part_name};
441 $biblioLoopIter{author} = $biblioData->{author};
442 $biblioLoopIter{rank} = $biblioData->{rank};
443 $biblioLoopIter{reservecount} = $biblioData->{reservecount};
444 $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
445 $biblioLoopIter{reqholdnotes}=0; #TODO: For future use
447 if (!$itemLevelTypes && $biblioData->{itemtype}) {
448 $biblioLoopIter{translated_description} = $itemtypes->{$biblioData->{itemtype}}{translated_description};
449 $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$biblioData->{itemtype}}{imageurl};
454 $biblioLoopIter{itemLoop} = [];
455 my $numCopiesAvailable = 0;
456 my $numCopiesOPACAvailable = 0;
457 # iterating through all items first to check if any of them available
458 # to pass this value further inside down to IsAvailableForItemLevelRequest to
459 # it's complicated logic to analyse.
460 # (before this loop was inside that sub loop so it was O(n^2) )
461 my $items_any_available;
462 $items_any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblioNum, patron => $patron }) if $patron;
463 foreach my $item (@{$biblioData->{items}}) {
465 my $item_info = $item->unblessed;
466 $item_info->{holding_branch} = $item->holding_branch;
467 $item_info->{home_branch} = $item->home_branch;
468 if ($itemLevelTypes) {
469 my $itemtype = $item->itemtype;
470 $item_info->{'imageurl'} = getitemtypeimagelocation( 'opac',
471 $itemtypes->{ $itemtype->itemtype }->{'imageurl'} );
472 $item_info->{'translated_description'} =
473 $itemtypes->{ $itemtype->itemtype }->{translated_description};
477 my $holds = $item->current_holds;
478 if ( my $first_hold = $holds->next ) {
479 $item_info->{first_hold} = $first_hold;
482 $item_info->{checkout} = $item->checkout;
484 # Check of the transferred documents
485 my ( $transfertwhen, $transfertfrom, $transfertto ) =
486 GetTransfers($item->itemnumber);
487 if ( $transfertwhen && ($transfertwhen ne '') ) {
488 $item_info->{transfertwhen} = $transfertwhen;
489 $item_info->{transfertfrom} = $transfertfrom;
490 $item_info->{transfertto} = $transfertto;
491 $item_info->{nocancel} = 1;
494 # if the items belongs to a host record, show link to host record
495 if ( $item_info->{biblionumber} ne $biblioNum ) {
496 $item_info->{hostbiblionumber} = $item->biblionumber;
497 $item_info->{hosttitle} = Koha::Biblios->find( $item_info->{biblionumber} )->title;
500 my $branch = GetReservesControlBranch( $item_info, $patron_unblessed );
502 # items_any_available defined outside of the current loop,
503 # so we avoiding loop inside IsAvailableForItemLevelRequest:
504 my $policy_holdallowed =
505 CanItemBeReserved( $patron, $item )->{status} eq 'OK' &&
506 IsAvailableForItemLevelRequest($item, $patron, undef, $items_any_available);
508 if ($policy_holdallowed) {
509 my $opac_hold_policy = Koha::CirculationRules->get_opacitemholds_policy( { item => $item, patron => $patron } );
510 if ( $opac_hold_policy ne 'N' ) { # If Y or F
511 $item_info->{available} = 1;
512 $numCopiesOPACAvailable++;
513 $biblioLoopIter{force_hold} = 1 if $opac_hold_policy eq 'F';
515 $numCopiesAvailable++;
517 unless ( $can_place_hold_if_available_at_pickup ) {
518 my $items_in_this_library = Koha::Items->search({ biblionumber => $item->biblionumber, holdingbranch => $item->holdingbranch });
519 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
520 if ( $items_in_this_library->count > $nb_of_items_issued ) {
521 push @not_available_at, $item->holdingbranch;
526 # Show serial enumeration when needed
527 if ($item_info->{enumchron}) {
528 $itemdata_enumchron = 1;
530 # Show collection when needed
531 if ($item_info->{ccode}) {
535 push @{$biblioLoopIter{itemLoop}}, $item_info;
538 itemdata_enumchron => $itemdata_enumchron,
539 itemdata_ccode => $itemdata_ccode,
542 if ($numCopiesAvailable > 0) {
544 $biblioLoopIter{bib_available} = 1;
545 $biblioLoopIter{holdable} = 1;
546 $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable;
548 if ($biblioLoopIter{already_reserved}) {
549 $biblioLoopIter{holdable} = undef;
550 $biblioLoopIter{itemholdable} = undef;
552 if ( $biblioLoopIter{holdable} ) {
553 @not_available_at = uniq @not_available_at;
554 $biblioLoopIter{not_available_at} = \@not_available_at ;
557 unless ( $can_place_hold_if_available_at_pickup ) {
558 @not_available_at = uniq @not_available_at;
559 $biblioLoopIter{not_available_at} = \@not_available_at ;
560 # The record is not holdable is not available at any of the libraries
561 if ( Koha::Libraries->search->count == @not_available_at ) {
562 $biblioLoopIter{holdable} = 0;
566 my $status = CanBookBeReserved( $borrowernumber, $biblioNum )->{status};
567 $biblioLoopIter{holdable} &&= $status eq 'OK';
568 $biblioLoopIter{$status} = 1;
570 if ( $biblioLoopIter{holdable} and C4::Context->preference('AllowHoldItemTypeSelection') ) {
571 # build the allowed item types loop
572 my $rs = $biblio->items->search_ordered(
574 { select => [ { distinct => 'itype' } ],
580 grep { CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $_ } )->{status} eq 'OK' }
581 $rs->get_column('item_type');
583 $biblioLoopIter{allowed_item_types} = \@item_types;
586 if ( $status eq 'recall' ) {
587 $biblioLoopIter{recall} = 1;
590 # For multiple holds per record, if a patron has previously placed a hold,
591 # the patron can only place more holds of the same type. That is, if the
592 # patron placed a record level hold, all the holds the patron places must
593 # be record level. If the patron placed an item level hold, all holds
594 # the patron places must be item level
595 my $forced_hold_level = Koha::Holds->search(
597 borrowernumber => $borrowernumber,
598 biblionumber => $biblioNum,
601 )->forced_hold_level();
602 if ($forced_hold_level) {
603 $biblioLoopIter{force_hold} = 1 if $forced_hold_level eq 'item';
604 $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'record';
605 $biblioLoopIter{forced_hold_level} = $forced_hold_level;
609 push @$biblioLoop, \%biblioLoopIter;
611 $anyholdable = 1 if $biblioLoopIter{holdable};
614 unless ($pickup_locations->count) {
615 $numBibsAvailable = 0;
619 no_pickup_locations => 1
623 if ( $numBibsAvailable == 0 || $anyholdable == 0) {
624 $template->param( none_available => 1 );
627 if (scalar @biblionumbers > 1) {
628 $template->param( multi_hold => 1);
631 my $show_notes=C4::Context->preference('OpacHoldNotes');
632 $template->param(OpacHoldNotes=>$show_notes);
635 $template->param(bibitemloop => $biblioLoop);
636 # can set reserve date in future
638 C4::Context->preference( 'AllowHoldDateInFuture' ) &&
639 C4::Context->preference( 'OPACAllowHoldDateInFuture' )
642 reserve_in_future => 1,
646 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };