Bug 19817: Move code to Koha::Manual to make it testable and reusable
[koha.git] / opac / opac-reserve.pl
blob684e57d1c3344d361b5937d00e5d773c6f749c8f
1 #!/usr/bin/perl
3 # Copyright Katipo Communications 2002
4 # Copyright Koha Development team 2012
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 use Modern::Perl;
23 use CGI qw ( -utf8 );
24 use C4::Auth; # checkauth, getborrowernumber.
25 use C4::Koha;
26 use C4::Circulation;
27 use C4::Reserves;
28 use C4::Biblio;
29 use C4::Items;
30 use C4::Output;
31 use C4::Context;
32 use C4::Members;
33 use C4::Overdues;
34 use C4::Debug;
36 use Koha::AuthorisedValues;
37 use Koha::Biblios;
38 use Koha::DateUtils;
39 use Koha::IssuingRules;
40 use Koha::Items;
41 use Koha::ItemTypes;
42 use Koha::Checkouts;
43 use Koha::Libraries;
44 use Koha::Patrons;
45 use Date::Calc qw/Today Date_to_Days/;
46 use List::MoreUtils qw/uniq/;
48 my $maxreserves = C4::Context->preference("maxreserves");
50 my $query = new CGI;
52 # if RequestOnOpac (for placing holds) is disabled, leave immediately
53 if ( ! C4::Context->preference('RequestOnOpac') ) {
54 print $query->redirect("/cgi-bin/koha/errors/404.pl");
55 exit;
58 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
60 template_name => "opac-reserve.tt",
61 query => $query,
62 type => "opac",
63 authnotrequired => 0,
64 debug => 1,
68 my ($show_holds_count, $show_priority);
69 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
70 m/holds/o and $show_holds_count = 1;
71 m/priority/ and $show_priority = 1;
74 sub get_out {
75 output_html_with_http_headers(shift,shift,shift); # $query, $cookie, $template->output;
76 exit;
79 my $patron = Koha::Patrons->find( $borrowernumber );
81 my $can_place_hold_if_available_at_pickup = C4::Context->preference('OPACHoldsIfAvailableAtPickup');
82 unless ( $can_place_hold_if_available_at_pickup ) {
83 my @patron_categories = split '\|', C4::Context->preference('OPACHoldsIfAvailableAtPickupExceptions');
84 if ( @patron_categories ) {
85 my $categorycode = $patron->categorycode;
86 $can_place_hold_if_available_at_pickup = grep /^$categorycode$/, @patron_categories;
90 # check if this user can place a reserve, -1 means use sys pref, 0 means dont block, 1 means block
91 if ( $patron->category->effective_BlockExpiredPatronOpacActions ) {
93 if ( $patron->is_expired ) {
95 # cannot reserve, their card has expired and the rules set mean this is not allowed
96 $template->param( message => 1, expired_patron => 1 );
97 get_out( $query, $cookie, $template->output );
101 # Pass through any reserve charge
102 my $reservefee = $patron->category->reservefee;
103 if ( $reservefee > 0){
104 $template->param( RESERVE_CHARGE => sprintf("%.2f",$reservefee));
107 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
109 # There are two ways of calling this script, with a single biblio num
110 # or multiple biblio nums.
111 my $biblionumbers = $query->param('biblionumbers');
112 my $reserveMode = $query->param('reserve_mode');
113 if ($reserveMode && ($reserveMode eq 'single')) {
114 my $bib = $query->param('single_bib');
115 $biblionumbers = "$bib/";
117 if (! $biblionumbers) {
118 $biblionumbers = $query->param('biblionumber');
121 if ((! $biblionumbers) && (! $query->param('place_reserve'))) {
122 $template->param(message=>1, no_biblionumber=>1);
123 &get_out($query, $cookie, $template->output);
126 # Pass the numbers to the page so they can be fed back
127 # when the hold is confirmed. TODO: Not necessary?
128 $template->param( biblionumbers => $biblionumbers );
130 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
131 my @biblionumbers = split /\//, $biblionumbers;
132 if (($#biblionumbers < 0) && (! $query->param('place_reserve'))) {
133 # TODO: New message?
134 $template->param(message=>1, no_biblionumber=>1);
135 &get_out($query, $cookie, $template->output);
139 # pass the pickup branch along....
140 my $branch = $query->param('branch') || $patron->branchcode || C4::Context->userenv->{branch} || '' ;
141 $template->param( branch => $branch );
143 # Is the person allowed to choose their branch
144 my $OPACChooseBranch = (C4::Context->preference("OPACAllowUserToChooseBranch")) ? 1 : 0;
146 $template->param( choose_branch => $OPACChooseBranch);
150 # Build hashes of the requested biblio(item)s and items.
154 my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record.
155 my %itemInfoHash; # Hash of itemnumber to item info.
156 foreach my $biblioNumber (@biblionumbers) {
158 my $biblioData = GetBiblioData($biblioNumber);
159 $biblioDataHash{$biblioNumber} = $biblioData;
161 my @itemInfos = GetItemsInfo($biblioNumber);
163 my $marcrecord= GetMarcBiblio({ biblionumber => $biblioNumber });
165 # flag indicating existence of at least one item linked via a host record
166 my $hostitemsflag;
167 # adding items linked via host biblios
168 my @hostitemInfos = GetHostItemsInfo($marcrecord);
169 if (@hostitemInfos){
170 $hostitemsflag =1;
171 push (@itemInfos,@hostitemInfos);
174 $biblioData->{itemInfos} = \@itemInfos;
175 foreach my $itemInfo (@itemInfos) {
176 $itemInfoHash{$itemInfo->{itemnumber}} = $itemInfo;
179 # Compute the priority rank.
180 my $biblio = Koha::Biblios->find( $biblioNumber );
181 my $holds = $biblio->holds;
182 my $rank = $holds->count;
183 $biblioData->{reservecount} = 1; # new reserve
184 while ( my $hold = $holds->next ) {
185 if ( $hold->is_waiting ) {
186 $rank--;
188 else {
189 $biblioData->{reservecount}++;
192 $biblioData->{rank} = $rank + 1;
197 # If this is the second time through this script, it
198 # means we are carrying out the hold request, possibly
199 # with a specific item for each biblionumber.
202 if ( $query->param('place_reserve') ) {
203 my $reserve_cnt = 0;
204 if ($maxreserves) {
205 $reserve_cnt = $patron->holds->count;
208 # List is composed of alternating biblio/item/branch
209 my $selectedItems = $query->param('selecteditems');
211 if ($query->param('reserve_mode') eq 'single') {
212 # This indicates non-JavaScript mode, so there was
213 # only a single biblio number selected.
214 my $bib = $query->param('single_bib');
215 my $item = $query->param("checkitem_$bib");
216 if ($item eq 'any') {
217 $item = '';
219 my $branch = $query->param('branch');
220 $selectedItems = "$bib/$item/$branch/";
223 $selectedItems =~ s!/$!!;
224 my @selectedItems = split /\//, $selectedItems, -1;
226 # Make sure there is a biblionum/itemnum/branch triplet for each item.
227 # The itemnum can be 'any', meaning next available.
228 my $selectionCount = @selectedItems;
229 if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
230 $template->param(message=>1, bad_data=>1);
231 &get_out($query, $cookie, $template->output);
234 my $failed_holds = 0;
235 while (@selectedItems) {
236 my $biblioNum = shift(@selectedItems);
237 my $itemNum = shift(@selectedItems);
238 my $branch = shift(@selectedItems); # i.e., branch code, not name
240 my $canreserve = 0;
242 my $singleBranchMode = Koha::Libraries->search->count == 1;
243 if ( $singleBranchMode || !$OPACChooseBranch )
244 { # single branch mode or disabled user choosing
245 $branch = $patron->branchcode;
248 #item may belong to a host biblio, if yes change biblioNum to hosts bilbionumber
249 if ( $itemNum ne '' ) {
250 my $item = Koha::Items->find( $itemNum );
251 my $hostbiblioNum = $item->biblio->biblionumber;
252 if ( $hostbiblioNum ne $biblioNum ) {
253 $biblioNum = $hostbiblioNum;
257 my $biblioData = $biblioDataHash{$biblioNum};
258 my $found;
260 # Check for user supplied reserve date
261 my $startdate;
262 if ( C4::Context->preference('AllowHoldDateInFuture')
263 && C4::Context->preference('OPACAllowHoldDateInFuture') )
265 $startdate = $query->param("reserve_date_$biblioNum");
268 my $expiration_date = $query->param("expiration_date_$biblioNum");
270 my $rank = $biblioData->{rank};
271 if ( $itemNum ne '' ) {
272 $canreserve = 1 if CanItemBeReserved( $borrowernumber, $itemNum )->{status} eq 'OK';
274 else {
275 $canreserve = 1 if CanBookBeReserved( $borrowernumber, $biblioNum )->{status} eq 'OK';
277 # Inserts a null into the 'itemnumber' field of 'reserves' table.
278 $itemNum = undef;
280 my $notes = $query->param('notes_'.$biblioNum)||'';
282 if ( $maxreserves
283 && $reserve_cnt >= $maxreserves )
285 $canreserve = 0;
288 unless ( $can_place_hold_if_available_at_pickup ) {
289 my $items_in_this_library = Koha::Items->search({ biblionumber => $biblioNum, holdingbranch => $branch });
290 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
291 my $nb_of_items_unavailable = $items_in_this_library->search({ -or => { lost => { '!=' => 0 }, damaged => { '!=' => 0 }, } });
292 if ( $items_in_this_library->count > $nb_of_items_issued + $nb_of_items_unavailable ) {
293 $canreserve = 0
297 my $itemtype = $query->param('itemtype') || undef;
298 $itemtype = undef if $itemNum;
300 # Here we actually do the reserveration. Stage 3.
301 if ($canreserve) {
302 my $reserve_id = AddReserve(
303 $branch, $borrowernumber, $biblioNum,
304 [$biblioNum], $rank, $startdate,
305 $expiration_date, $notes, $biblioData->{title},
306 $itemNum, $found, $itemtype,
308 $failed_holds++ unless $reserve_id;
309 ++$reserve_cnt;
313 print $query->redirect("/cgi-bin/koha/opac-user.pl?" . ( $failed_holds ? "failed_holds=$failed_holds" : q|| ) . "#opac-user-holds");
314 exit;
319 # Here we check that the borrower can actually make reserves Stage 1.
322 my $noreserves = 0;
323 my $maxoutstanding = C4::Context->preference("maxoutstanding");
324 $template->param( noreserve => 1 ) unless $maxoutstanding;
325 my $amountoutstanding = $patron->account->balance;
326 if ( $amountoutstanding && ($amountoutstanding > $maxoutstanding) ) {
327 my $amount = sprintf "%.02f", $amountoutstanding;
328 $template->param( message => 1 );
329 $noreserves = 1;
330 $template->param( too_much_oweing => $amount );
333 if ( $patron->gonenoaddress && ($patron->gonenoaddress == 1) ) {
334 $noreserves = 1;
335 $template->param(
336 message => 1,
337 GNA => 1
341 if ( $patron->lost && ($patron->lost == 1) ) {
342 $noreserves = 1;
343 $template->param(
344 message => 1,
345 lost => 1
349 if ( $patron->is_debarred ) {
350 $noreserves = 1;
351 $template->param(
352 message => 1,
353 debarred => 1,
354 debarred_comment => $patron->debarredcomment,
355 debarred_date => $patron->debarred,
359 my $holds = $patron->holds;
360 my $reserves_count = $holds->count;
361 $template->param( RESERVES => $holds->unblessed );
362 if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) {
363 $template->param( message => 1 );
364 $noreserves = 1;
365 $template->param( too_many_reserves => $holds->count );
368 unless ( $noreserves ) {
369 my $requested_reserves_count = scalar( @biblionumbers );
370 if ( $maxreserves && ( $reserves_count + $requested_reserves_count > $maxreserves ) ) {
371 $template->param( new_reserves_allowed => $maxreserves - $reserves_count );
375 unless ($noreserves) {
376 $template->param( select_item_types => 1 );
382 # Build the template parameters that will show the info
383 # and items for each biblionumber.
387 my $biblioLoop = [];
388 my $numBibsAvailable = 0;
389 my $itemdata_enumchron = 0;
390 my $anyholdable = 0;
391 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
392 $template->param('item_level_itypes' => $itemLevelTypes);
394 foreach my $biblioNum (@biblionumbers) {
396 my @not_available_at = ();
397 my $record = GetMarcBiblio({ biblionumber => $biblioNum });
398 # Init the bib item with the choices for branch pickup
399 my %biblioLoopIter;
401 # Get relevant biblio data.
402 my $biblioData = $biblioDataHash{$biblioNum};
403 if (! $biblioData) {
404 $template->param(message=>1, bad_biblionumber=>$biblioNum);
405 &get_out($query, $cookie, $template->output);
408 my $frameworkcode = GetFrameworkCode( $biblioData->{biblionumber} );
409 $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
410 $biblioLoopIter{title} = $biblioData->{title};
411 $biblioLoopIter{subtitle} = GetRecordValue('subtitle', $record, $frameworkcode);
412 $biblioLoopIter{author} = $biblioData->{author};
413 $biblioLoopIter{rank} = $biblioData->{rank};
414 $biblioLoopIter{reservecount} = $biblioData->{reservecount};
415 $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
416 $biblioLoopIter{reqholdnotes}=0; #TODO: For future use
418 if (!$itemLevelTypes && $biblioData->{itemtype}) {
419 $biblioLoopIter{translated_description} = $itemtypes->{$biblioData->{itemtype}}{translated_description};
420 $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$biblioData->{itemtype}}{imageurl};
423 foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
424 if ($itemLevelTypes && $itemInfo->{itype}) {
425 $itemInfo->{translated_description} = $itemtypes->{$itemInfo->{itype}}{translated_description};
426 $itemInfo->{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$itemInfo->{itype}}{imageurl};
429 if (!$itemInfo->{'notforloan'} && !($itemInfo->{'itemnotforloan'} > 0)) {
430 $biblioLoopIter{forloan} = 1;
434 my @notforloan_avs = Koha::AuthorisedValues->search_by_koha_field({ kohafield => 'items.notforloan', frameworkcode => $frameworkcode });
435 my $notforloan_label_of = { map { $_->authorised_value => $_->opac_description } @notforloan_avs };
437 $biblioLoopIter{itemLoop} = [];
438 my $numCopiesAvailable = 0;
439 my $numCopiesOPACAvailable = 0;
440 foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
441 my $itemNum = $itemInfo->{itemnumber};
442 my $item = Koha::Items->find( $itemNum );
443 my $itemLoopIter = {};
445 $itemLoopIter->{itemnumber} = $itemNum;
446 $itemLoopIter->{barcode} = $itemInfo->{barcode};
447 $itemLoopIter->{homeBranchName} = $itemInfo->{homebranch};
448 $itemLoopIter->{callNumber} = $itemInfo->{itemcallnumber};
449 $itemLoopIter->{enumchron} = $itemInfo->{enumchron};
450 $itemLoopIter->{copynumber} = $itemInfo->{copynumber};
451 if ($itemLevelTypes) {
452 $itemLoopIter->{translated_description} = $itemInfo->{translated_description};
453 $itemLoopIter->{itype} = $itemInfo->{itype};
454 $itemLoopIter->{imageurl} = $itemInfo->{imageurl};
457 # If the holdingbranch is different than the homebranch, we show the
458 # holdingbranch of the document too.
459 if ( $itemInfo->{homebranch} ne $itemInfo->{holdingbranch} ) {
460 $itemLoopIter->{holdingBranchName} = $itemInfo->{holdingbranch};
463 # If the item is currently on loan, we display its return date and
464 # change the background color.
465 my $issue = Koha::Checkouts->find( { itemnumber => $itemNum } );
466 if ( $issue ) {
467 $itemLoopIter->{dateDue} = output_pref({ dt => dt_from_string($issue->date_due, 'sql'), as_due_date => 1 });
468 $itemLoopIter->{backgroundcolor} = 'onloan';
471 # checking reserve
472 my $holds = $item->current_holds;
474 if ( my $first_hold = $holds->next ) {
475 $itemLoopIter->{backgroundcolor} = 'reserved';
476 $itemLoopIter->{reservedate} = output_pref({ dt => dt_from_string($first_hold->reservedate), dateonly => 1 }); # FIXME Should be formatted in the template
477 $itemLoopIter->{ExpectedAtLibrary} = $first_hold->branchcode;
478 $itemLoopIter->{waitingdate} = $first_hold->waitingdate;
481 $itemLoopIter->{notforloan} = $itemInfo->{notforloan};
482 $itemLoopIter->{itemnotforloan} = $itemInfo->{itemnotforloan};
484 # Management of the notforloan document
485 if ( $itemLoopIter->{notforloan} || $itemLoopIter->{itemnotforloan}) {
486 $itemLoopIter->{backgroundcolor} = 'other';
487 $itemLoopIter->{notforloanvalue} =
488 $notforloan_label_of->{ $itemLoopIter->{notforloan} };
491 # Management of lost or long overdue items
492 if ( $itemInfo->{itemlost} ) {
494 # FIXME localized strings should never be in Perl code
495 $itemLoopIter->{message} =
496 $itemInfo->{itemlost} == 1 ? "(lost)"
497 : $itemInfo->{itemlost} == 2 ? "(long overdue)"
498 : "";
499 $itemInfo->{backgroundcolor} = 'other';
502 # Check of the transfered documents
503 my ( $transfertwhen, $transfertfrom, $transfertto ) =
504 GetTransfers($itemNum);
505 if ( $transfertwhen && ($transfertwhen ne '') ) {
506 $itemLoopIter->{transfertwhen} = output_pref({ dt => dt_from_string($transfertwhen), dateonly => 1 });
507 $itemLoopIter->{transfertfrom} = $transfertfrom;
508 $itemLoopIter->{transfertto} = $transfertto;
509 $itemLoopIter->{nocancel} = 1;
512 # if the items belongs to a host record, show link to host record
513 if ( $itemInfo->{biblionumber} ne $biblioNum ) {
514 $biblioLoopIter{hostitemsflag} = 1;
515 $itemLoopIter->{hostbiblionumber} = $itemInfo->{biblionumber};
516 $itemLoopIter->{hosttitle} = Koha::Biblios->find( $itemInfo->{biblionumber} )->title;
519 # If there is no loan, return and transfer, we show a checkbox.
520 $itemLoopIter->{notforloan} = $itemLoopIter->{notforloan} || 0;
522 my $patron_unblessed = $patron->unblessed;
523 my $branch = GetReservesControlBranch( $itemInfo, $patron_unblessed );
525 my $policy_holdallowed = !$itemLoopIter->{already_reserved};
526 $policy_holdallowed &&=
527 IsAvailableForItemLevelRequest($itemInfo,$patron_unblessed) &&
528 CanItemBeReserved( $borrowernumber, $itemNum )->{status} eq 'OK';
530 if ($policy_holdallowed) {
531 my $opac_hold_policy = Koha::IssuingRules->get_opacitemholds_policy( { item => $item, patron => $patron } );
532 if ( $opac_hold_policy ne 'N' ) { # If Y or F
533 $itemLoopIter->{available} = 1;
534 $numCopiesOPACAvailable++;
535 $biblioLoopIter{force_hold} = 1 if $opac_hold_policy eq 'F';
537 $numCopiesAvailable++;
539 unless ( $can_place_hold_if_available_at_pickup ) {
540 my $items_in_this_library = Koha::Items->search({ biblionumber => $itemInfo->{biblionumber}, holdingbranch => $itemInfo->{holdingbranch} });
541 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
542 if ( $items_in_this_library->count > $nb_of_items_issued ) {
543 push @not_available_at, $itemInfo->{holdingbranch};
548 $itemLoopIter->{imageurl} = getitemtypeimagelocation( 'opac', $itemtypes->{ $itemInfo->{itype} }{imageurl} );
550 # Show serial enumeration when needed
551 if ($itemLoopIter->{enumchron}) {
552 $itemdata_enumchron = 1;
555 push @{$biblioLoopIter{itemLoop}}, $itemLoopIter;
557 $template->param( itemdata_enumchron => $itemdata_enumchron );
559 if ($numCopiesAvailable > 0) {
560 $numBibsAvailable++;
561 $biblioLoopIter{bib_available} = 1;
562 $biblioLoopIter{holdable} = 1;
563 $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable;
565 if ($biblioLoopIter{already_reserved}) {
566 $biblioLoopIter{holdable} = undef;
567 $biblioLoopIter{itemholdable} = undef;
569 if(not C4::Context->preference('AllowHoldsOnPatronsPossessions') and CheckIfIssuedToPatron($borrowernumber,$biblioNum)) {
570 $biblioLoopIter{holdable} = undef;
571 $biblioLoopIter{already_patron_possession} = 1;
574 if ( $biblioLoopIter{holdable} ) {
575 @not_available_at = uniq @not_available_at;
576 $biblioLoopIter{not_available_at} = \@not_available_at ;
579 unless ( $can_place_hold_if_available_at_pickup ) {
580 @not_available_at = uniq @not_available_at;
581 $biblioLoopIter{not_available_at} = \@not_available_at ;
582 # The record is not holdable is not available at any of the libraries
583 if ( Koha::Libraries->search->count == @not_available_at ) {
584 $biblioLoopIter{holdable} = 0;
588 $biblioLoopIter{holdable} &&= CanBookBeReserved( $borrowernumber, $biblioNum )->{status} eq 'OK';
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,
599 found => undef,
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';
608 push @$biblioLoop, \%biblioLoopIter;
610 $anyholdable = 1 if $biblioLoopIter{holdable};
614 if ( $numBibsAvailable == 0 || $anyholdable == 0) {
615 $template->param( none_available => 1 );
618 if (scalar @biblionumbers > 1) {
619 $template->param( multi_hold => 1);
622 my $show_notes=C4::Context->preference('OpacHoldNotes');
623 $template->param(OpacHoldNotes=>$show_notes);
625 # display infos
626 $template->param(bibitemloop => $biblioLoop);
627 # can set reserve date in future
628 if (
629 C4::Context->preference( 'AllowHoldDateInFuture' ) &&
630 C4::Context->preference( 'OPACAllowHoldDateInFuture' )
632 $template->param(
633 reserve_in_future => 1,
637 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };