Bug 30084: Remove explicit dependency of liblocale-codes-perl
[koha.git] / opac / opac-reserve.pl
1 #!/usr/bin/perl
2
3 # Copyright Katipo Communications 2002
4 # Copyright Koha Development team 2012
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
17 #
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>.
20
21 use Modern::Perl;
22
23 use CGI qw ( -utf8 );
24 use C4::Auth;    # checkauth, getborrowernumber.
25 use C4::Koha;
26 use C4::Circulation;
27 use C4::Biblio;
28 use C4::Items;
29 use C4::Output;
30 use C4::Reserves qw( CanItemBeReserved CanBookBeReserved AddReserve GetReservesControlBranch ItemsAnyAvailableAndNotRestricted IsAvailableForItemLevelRequest );
31 use C4::Context;
32 use C4::Members;
33 use C4::Overdues;
34 use C4::Debug;
35
36 use Koha::AuthorisedValues;
37 use Koha::Biblios;
38 use Koha::DateUtils;
39 use Koha::CirculationRules;
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/;
47
48 my $maxreserves = C4::Context->preference("maxreserves");
49
50 my $query = CGI->new;
51
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;
56 }
57
58 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
59     {
60         template_name   => "opac-reserve.tt",
61         query           => $query,
62         type            => "opac",
63         debug           => 1,
64     }
65 );
66
67 my ($show_holds_count, $show_priority);
68 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
69     m/holds/o and $show_holds_count = 1;
70     m/priority/ and $show_priority = 1;
71 }
72
73 my $patron = Koha::Patrons->find( $borrowernumber, { prefetch => ['categorycode'] } );
74 my $category = $patron->category;
75
76 my $can_place_hold_if_available_at_pickup = C4::Context->preference('OPACHoldsIfAvailableAtPickup');
77 unless ( $can_place_hold_if_available_at_pickup ) {
78     my @patron_categories = split ',', C4::Context->preference('OPACHoldsIfAvailableAtPickupExceptions');
79     if ( @patron_categories ) {
80         my $categorycode = $patron->categorycode;
81         $can_place_hold_if_available_at_pickup = grep { $_ eq $categorycode } @patron_categories;
82     }
83 }
84
85 # check if this user can place a reserve, -1 means use sys pref, 0 means dont block, 1 means block
86 if ( $category->effective_BlockExpiredPatronOpacActions ) {
87
88     if ( $patron->is_expired ) {
89
90         # cannot reserve, their card has expired and the rules set mean this is not allowed
91         $template->param( message => 1, expired_patron => 1 );
92         output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
93         exit;
94     }
95 }
96
97 # Pass through any reserve charge
98 my $reservefee = $category->reservefee;
99 if ( $reservefee > 0){
100     $template->param( RESERVE_CHARGE => $reservefee);
101 }
102
103 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
104
105 # There are two ways of calling this script, with a single biblio num
106 # or multiple biblio nums.
107 my $biblionumbers = $query->param('biblionumbers');
108 my $reserveMode = $query->param('reserve_mode');
109 if ($reserveMode && ($reserveMode eq 'single')) {
110     my $bib = $query->param('single_bib');
111     $biblionumbers = "$bib/";
112 }
113 if (! $biblionumbers) {
114     $biblionumbers = $query->param('biblionumber');
115 }
116
117 if ((! $biblionumbers) && (! $query->param('place_reserve'))) {
118     $template->param(message=>1, no_biblionumber=>1);
119     output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
120     exit;
121 }
122
123 # Pass the numbers to the page so they can be fed back
124 # when the hold is confirmed. TODO: Not necessary?
125 $template->param( biblionumbers => $biblionumbers );
126
127 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
128 my @biblionumbers = split /\//, $biblionumbers;
129 if (($#biblionumbers < 0) && (! $query->param('place_reserve'))) {
130     # TODO: New message?
131     $template->param(message=>1, no_biblionumber=>1);
132     output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
133     exit;
134 }
135
136
137 # pass the pickup branch along....
138 my $branch = $query->param('branch') || $patron->branchcode || C4::Context->userenv->{branch} || '' ;
139 $template->param( branch => $branch );
140
141 #
142 #
143 # Build hashes of the requested biblio(item)s and items.
144 #
145 #
146
147 my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record.
148 my %itemInfoHash; # Hash of itemnumber to item info.
149 foreach my $biblioNumber (@biblionumbers) {
150
151     my $biblioData = GetBiblioData($biblioNumber);
152     $biblioDataHash{$biblioNumber} = $biblioData;
153
154     my @itemInfos = GetItemsInfo($biblioNumber);
155
156     my $marcrecord= GetMarcBiblio({ biblionumber => $biblioNumber });
157
158     # flag indicating existence of at least one item linked via a host record
159     my $hostitemsflag;
160     # adding items linked via host biblios
161     my @hostitemInfos = GetHostItemsInfo($marcrecord);
162     if (@hostitemInfos){
163         $hostitemsflag =1;
164         push (@itemInfos,@hostitemInfos);
165     }
166
167     $biblioData->{itemInfos} = \@itemInfos;
168     foreach my $itemInfo (@itemInfos) {
169         $itemInfoHash{$itemInfo->{itemnumber}} = $itemInfo;
170     }
171
172     # Compute the priority rank.
173     my $biblio = Koha::Biblios->find( $biblioNumber );
174     next unless $biblio;
175
176     $biblioData->{object} = $biblio;
177     my $holds = $biblio->holds;
178     my $rank = $holds->count;
179     $biblioData->{reservecount} = 1;    # new reserve
180     while ( my $hold = $holds->next ) {
181         if ( $hold->is_waiting ) {
182             $rank--;
183         }
184         else {
185             $biblioData->{reservecount}++;
186         }
187     }
188     $biblioData->{rank} = $rank + 1;
189 }
190
191 #
192 #
193 # If this is the second time through this script, it
194 # means we are carrying out the hold request, possibly
195 # with a specific item for each biblionumber.
196 #
197 #
198 if ( $query->param('place_reserve') ) {
199     my $reserve_cnt = 0;
200     if ($maxreserves) {
201         $reserve_cnt = $patron->holds->count;
202     }
203
204     # List is composed of alternating biblio/item/branch
205     my $selectedItems = $query->param('selecteditems');
206
207     if ($query->param('reserve_mode') eq 'single') {
208         # This indicates non-JavaScript mode, so there was
209         # only a single biblio number selected.
210         my $bib = $query->param('single_bib');
211         my $item = $query->param("checkitem_$bib");
212         if ($item eq 'any') {
213             $item = '';
214         }
215         my $branch = $query->param('branch');
216         $selectedItems = "$bib/$item/$branch/";
217     }
218
219     $selectedItems =~ s!/$!!;
220     my @selectedItems = split /\//, $selectedItems, -1;
221
222     # Make sure there is a biblionum/itemnum/branch triplet for each item.
223     # The itemnum can be 'any', meaning next available.
224     my $selectionCount = @selectedItems;
225     if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
226         $template->param(message=>1, bad_data=>1);
227         output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
228         exit;
229     }
230
231     my $failed_holds = 0;
232     while (@selectedItems) {
233         my $biblioNum = shift(@selectedItems);
234         my $itemNum   = shift(@selectedItems);
235         my $branch    = shift(@selectedItems);    # i.e., branch code, not name
236
237         my $canreserve = 0;
238
239         my $singleBranchMode = Koha::Libraries->search->count == 1;
240         if ( $singleBranchMode || ! C4::Context->preference("OPACAllowUserToChooseBranch") )
241         {    # single branch mode or disabled user choosing
242             $branch = $patron->branchcode;
243         }
244
245         # When choosing a specific item, the default pickup library should be dictated by the default hold policy
246         if ( ! C4::Context->preference("OPACAllowUserToChooseBranch") && $itemNum ) {
247             my $item = Koha::Items->find( $itemNum );
248             my $type = $item->effective_itemtype;
249             my $rule = GetBranchItemRule( $patron->branchcode, $type );
250
251             if ( $rule->{hold_fulfillment_policy} eq 'any' || $rule->{hold_fulfillment_policy} eq 'patrongroup' ) {
252                 $branch = $patron->branchcode;
253             } elsif ( $rule->{hold_fulfillment_policy} eq 'holdgroup' ){
254                 $branch = $item->homebranch;
255             } else {
256                 my $policy = $rule->{hold_fulfillment_policy};
257                 $branch = $item->$policy;
258             }
259         }
260
261 #item may belong to a host biblio, if yes change biblioNum to hosts bilbionumber
262         if ( $itemNum ne '' ) {
263             my $item = Koha::Items->find( $itemNum );
264             my $hostbiblioNum = $item->biblio->biblionumber;
265             if ( $hostbiblioNum ne $biblioNum ) {
266                 $biblioNum = $hostbiblioNum;
267             }
268         }
269
270         my $biblioData = $biblioDataHash{$biblioNum};
271         my $found;
272
273         # Check for user supplied reserve date
274         my $startdate;
275         if (   C4::Context->preference('AllowHoldDateInFuture')
276             && C4::Context->preference('OPACAllowHoldDateInFuture') )
277         {
278             $startdate = $query->param("reserve_date_$biblioNum");
279         }
280
281         my $expiration_date = $query->param("expiration_date_$biblioNum");
282
283         my $rank = $biblioData->{rank};
284         if ( $itemNum ne '' ) {
285             $canreserve = 1 if CanItemBeReserved( $borrowernumber, $itemNum, $branch )->{status} eq 'OK';
286         }
287         else {
288             $canreserve = 1 if CanBookBeReserved( $borrowernumber, $biblioNum, $branch )->{status} eq 'OK';
289
290             # Inserts a null into the 'itemnumber' field of 'reserves' table.
291             $itemNum = undef;
292         }
293         my $notes = $query->param('notes_'.$biblioNum)||'';
294
295         if (   $maxreserves
296             && $reserve_cnt >= $maxreserves )
297         {
298             $canreserve = 0;
299         }
300
301         unless ( $can_place_hold_if_available_at_pickup ) {
302             my $items_in_this_library = Koha::Items->search({ biblionumber => $biblioNum, holdingbranch => $branch });
303             my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
304             my $nb_of_items_unavailable = $items_in_this_library->search({ -or => { lost => { '!=' => 0 }, damaged => { '!=' => 0 }, } });
305             if ( $items_in_this_library->count > $nb_of_items_issued + $nb_of_items_unavailable ) {
306                 $canreserve = 0
307             }
308         }
309
310         my $itemtype = $query->param('itemtype') || undef;
311         $itemtype = undef if $itemNum;
312
313         # Here we actually do the reserveration. Stage 3.
314         if ($canreserve) {
315             my $reserve_id = AddReserve(
316                 {
317                     branchcode       => $branch,
318                     borrowernumber   => $borrowernumber,
319                     biblionumber     => $biblioNum,
320                     priority         => $rank,
321                     reservation_date => $startdate,
322                     expiration_date  => $expiration_date,
323                     notes            => $notes,
324                     title            => $biblioData->{title},
325                     itemnumber       => $itemNum,
326                     found            => $found,
327                     itemtype         => $itemtype,
328                 }
329             );
330             $failed_holds++ unless $reserve_id;
331             ++$reserve_cnt;
332         }
333     }
334
335     print $query->redirect("/cgi-bin/koha/opac-user.pl?" . ( $failed_holds ? "failed_holds=$failed_holds" : q|| ) . "#opac-user-holds");
336     exit;
337 }
338
339 #
340 #
341 # Here we check that the borrower can actually make reserves Stage 1.
342 #
343 #
344 my $noreserves     = 0;
345 my $maxoutstanding = C4::Context->preference("maxoutstanding");
346 $template->param( noreserve => 1 ) unless $maxoutstanding;
347 my $amountoutstanding = $patron->account->balance;
348 if ( $amountoutstanding && ($amountoutstanding > $maxoutstanding) ) {
349     my $amount = sprintf "%.02f", $amountoutstanding;
350     $template->param( message => 1 );
351     $noreserves = 1;
352     $template->param( too_much_oweing => $amount );
353 }
354
355 if ( $patron->gonenoaddress && ($patron->gonenoaddress == 1) ) {
356     $noreserves = 1;
357     $template->param(
358         message => 1,
359         GNA     => 1
360     );
361 }
362
363 if ( $patron->lost && ($patron->lost == 1) ) {
364     $noreserves = 1;
365     $template->param(
366         message => 1,
367         lost    => 1
368     );
369 }
370
371 if ( $patron->is_debarred ) {
372     $noreserves = 1;
373     $template->param(
374         message          => 1,
375         debarred         => 1,
376         debarred_comment => $patron->debarredcomment,
377         debarred_date    => $patron->debarred,
378     );
379 }
380
381 my $holds = $patron->holds;
382 my $reserves_count = $holds->count;
383 $template->param( RESERVES => $holds->unblessed );
384 if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) {
385     $template->param( message => 1 );
386     $noreserves = 1;
387     $template->param( too_many_reserves => $holds->count );
388 }
389
390 unless ( $noreserves ) {
391     my $requested_reserves_count = scalar( @biblionumbers );
392     if ( $maxreserves && ( $reserves_count + $requested_reserves_count > $maxreserves ) ) {
393         $template->param( new_reserves_allowed => $maxreserves - $reserves_count );
394     }
395 }
396
397 unless ($noreserves) {
398     $template->param( select_item_types => 1 );
399 }
400
401
402 #
403 #
404 # Build the template parameters that will show the info
405 # and items for each biblionumber.
406 #
407 #
408
409 my $biblioLoop = [];
410 my $numBibsAvailable = 0;
411 my $itemdata_enumchron = 0;
412 my $itemdata_ccode = 0;
413 my $anyholdable = 0;
414 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
415 my $pickup_locations = Koha::Libraries->search({ pickup_location => 1 });
416 $template->param('item_level_itypes' => $itemLevelTypes);
417
418 foreach my $biblioNum (@biblionumbers) {
419
420     # Init the bib item with the choices for branch pickup
421     my %biblioLoopIter;
422
423     # Get relevant biblio data.
424     my $biblioData = $biblioDataHash{$biblioNum};
425     if (! $biblioData) {
426         $template->param(message=>1, bad_biblionumber=>$biblioNum);
427         output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
428         exit;
429     }
430
431     my @not_available_at = ();
432     my $biblio = $biblioData->{object};
433     foreach my $library ( $pickup_locations->as_list ) {
434         push( @not_available_at, $library->branchcode ) unless $biblio->can_be_transferred({ to => $library });
435     }
436
437     my $frameworkcode = GetFrameworkCode( $biblioData->{biblionumber} );
438     $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
439     $biblioLoopIter{title} = $biblioData->{title};
440     $biblioLoopIter{subtitle} = $biblioData->{'subtitle'};
441     $biblioLoopIter{medium} = $biblioData->{medium};
442     $biblioLoopIter{part_number} = $biblioData->{part_number};
443     $biblioLoopIter{part_name} = $biblioData->{part_name};
444     $biblioLoopIter{author} = $biblioData->{author};
445     $biblioLoopIter{rank} = $biblioData->{rank};
446     $biblioLoopIter{reservecount} = $biblioData->{reservecount};
447     $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
448     $biblioLoopIter{reqholdnotes}=0; #TODO: For future use
449
450     if (!$itemLevelTypes && $biblioData->{itemtype}) {
451         $biblioLoopIter{translated_description} = $itemtypes->{$biblioData->{itemtype}}{translated_description};
452         $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$biblioData->{itemtype}}{imageurl};
453     }
454
455     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
456         if ($itemLevelTypes && $itemInfo->{itype}) {
457             $itemInfo->{translated_description} = $itemtypes->{$itemInfo->{itype}}{translated_description};
458             $itemInfo->{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$itemInfo->{itype}}{imageurl};
459         }
460
461         if (!$itemInfo->{'notforloan'} && !($itemInfo->{'itemnotforloan'} > 0)) {
462             $biblioLoopIter{forloan} = 1;
463         }
464     }
465
466     my @notforloan_avs = Koha::AuthorisedValues->search_by_koha_field({ kohafield => 'items.notforloan', frameworkcode => $frameworkcode });
467     my $notforloan_label_of = { map { $_->authorised_value => $_->opac_description } @notforloan_avs };
468
469     my $visible_items = { map { $_->itemnumber => $_ } $biblio->items->filter_by_visible_in_opac( { patron => $patron } )->as_list };
470
471     # Only keep the items that are visible in the opac (i.e. those in %visible_items)
472     # FIXME: We should get rid of itemInfos altogether and use $visible_items
473     $biblioData->{itemInfos} = [ grep { $visible_items->{ $_->{itemnumber} } } @{ $biblioData->{itemInfos} } ];
474
475     $biblioLoopIter{itemLoop} = [];
476     my $numCopiesAvailable = 0;
477     my $numCopiesOPACAvailable = 0;
478     # iterating through all items first to check if any of them available
479     # to pass this value further inside down to IsAvailableForItemLevelRequest to
480     # it's complicated logic to analyse.
481     # (before this loop was inside that sub loop so it was O(n^2) )
482     my $items_any_available;
483     $items_any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblioNum, patron => $patron }) if $patron;
484     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
485         my $itemNum = $itemInfo->{itemnumber};
486         my $item = $visible_items->{$itemNum};
487         my $itemLoopIter = {};
488
489         $itemLoopIter->{itemnumber} = $itemNum;
490         $itemLoopIter->{barcode} = $itemInfo->{barcode};
491         $itemLoopIter->{homeBranchName} = $itemInfo->{homebranch};
492         $itemLoopIter->{callNumber} = $itemInfo->{itemcallnumber};
493         $itemLoopIter->{enumchron} = $itemInfo->{enumchron};
494         $itemLoopIter->{ccode} = $itemInfo->{ccode};
495         $itemLoopIter->{copynumber} = $itemInfo->{copynumber};
496         if ($itemLevelTypes) {
497             $itemLoopIter->{translated_description} = $itemInfo->{translated_description};
498             $itemLoopIter->{itype} = $itemInfo->{itype};
499             $itemLoopIter->{imageurl} = $itemInfo->{imageurl};
500         }
501
502         # If the holdingbranch is different than the homebranch, we show the
503         # holdingbranch of the document too.
504         if ( $itemInfo->{homebranch} ne $itemInfo->{holdingbranch} ) {
505             $itemLoopIter->{holdingBranchName} = $itemInfo->{holdingbranch};
506         }
507
508         # If the item is currently on loan, we display its return date and
509         # change the background color.
510         my $issue = Koha::Checkouts->find( { itemnumber => $itemNum } );
511         if ( $issue ) {
512             $itemLoopIter->{dateDue} = output_pref({ dt => dt_from_string($issue->date_due, 'sql'), as_due_date => 1 });
513             $itemLoopIter->{onloan} = 'onloan';
514         }
515
516         # checking reserve
517         my $holds = $item->current_holds;
518
519         if ( my $first_hold = $holds->next ) {
520             $itemLoopIter->{backgroundcolor} = 'reserved';
521             $itemLoopIter->{reservedate}     = output_pref({ dt => dt_from_string($first_hold->reservedate), dateonly => 1 }); # FIXME Should be formatted in the template
522             $itemLoopIter->{ExpectedAtLibrary}         = $first_hold->branchcode;
523             $itemLoopIter->{waitingdate} = $first_hold->waitingdate;
524         }
525
526         $itemLoopIter->{notforloan} = $itemInfo->{notforloan};
527         $itemLoopIter->{itemnotforloan} = $itemInfo->{itemnotforloan};
528
529         # Management of the notforloan document
530         if ( $itemLoopIter->{notforloan} || $itemLoopIter->{itemnotforloan}) {
531             $itemLoopIter->{backgroundcolor} = 'other';
532             $itemLoopIter->{notforloanvalue} =
533               $notforloan_label_of->{ $itemLoopIter->{notforloan} };
534         }
535
536         # Management of lost or long overdue items
537         if ( $itemInfo->{itemlost} ) {
538
539             # FIXME localized strings should never be in Perl code
540             $itemLoopIter->{message} =
541                 $itemInfo->{itemlost} == 1 ? "(lost)"
542               : $itemInfo->{itemlost} == 2 ? "(long overdue)"
543               : "";
544             $itemInfo->{backgroundcolor} = 'other';
545         }
546
547         # Check of the transferred documents
548         my ( $transfertwhen, $transfertfrom, $transfertto ) =
549           GetTransfers($itemNum);
550         if ( $transfertwhen && ($transfertwhen ne '') ) {
551             $itemLoopIter->{transfertwhen} = output_pref({ dt => dt_from_string($transfertwhen), dateonly => 1 });
552             $itemLoopIter->{transfertfrom} = $transfertfrom;
553             $itemLoopIter->{transfertto} = $transfertto;
554             $itemLoopIter->{nocancel} = 1;
555         }
556
557         # if the items belongs to a host record, show link to host record
558         if ( $itemInfo->{biblionumber} ne $biblioNum ) {
559             $biblioLoopIter{hostitemsflag}    = 1;
560             $itemLoopIter->{hostbiblionumber} = $itemInfo->{biblionumber};
561             $itemLoopIter->{hosttitle}        = Koha::Biblios->find( $itemInfo->{biblionumber} )->title;
562         }
563
564         # If there is no loan, return and transfer, we show a checkbox.
565         $itemLoopIter->{notforloan} = $itemLoopIter->{notforloan} || 0;
566
567         my $patron_unblessed = $patron->unblessed;
568         my $branch = GetReservesControlBranch( $itemInfo, $patron_unblessed );
569
570         my $policy_holdallowed = !$itemLoopIter->{already_reserved};
571         # items_any_available defined outside of the current loop,
572         # so we avoiding loop inside IsAvailableForItemLevelRequest:
573         $policy_holdallowed &&=
574             CanItemBeReserved( $borrowernumber, $itemNum )->{status} eq 'OK' &&
575             IsAvailableForItemLevelRequest($item, $patron, undef, $items_any_available);
576
577         if ($policy_holdallowed) {
578             my $opac_hold_policy = Koha::CirculationRules->get_opacitemholds_policy( { item => $item, patron => $patron } );
579             if ( $opac_hold_policy ne 'N' ) { # If Y or F
580                 $itemLoopIter->{available} = 1;
581                 $numCopiesOPACAvailable++;
582                 $biblioLoopIter{force_hold} = 1 if $opac_hold_policy eq 'F';
583             }
584             $numCopiesAvailable++;
585
586             unless ( $can_place_hold_if_available_at_pickup ) {
587                 my $items_in_this_library = Koha::Items->search({ biblionumber => $itemInfo->{biblionumber}, holdingbranch => $itemInfo->{holdingbranch} });
588                 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
589                 if ( $items_in_this_library->count > $nb_of_items_issued ) {
590                     push @not_available_at, $itemInfo->{holdingbranch};
591                 }
592             }
593         }
594
595         $itemLoopIter->{imageurl} = getitemtypeimagelocation( 'opac', $itemtypes->{ $itemInfo->{itype} }{imageurl} );
596
597     # Show serial enumeration when needed
598         if ($itemLoopIter->{enumchron}) {
599             $itemdata_enumchron = 1;
600         }
601     # Show collection when needed
602         if ($itemLoopIter->{ccode}) {
603             $itemdata_ccode = 1;
604         }
605
606         push @{$biblioLoopIter{itemLoop}}, $itemLoopIter;
607     }
608     $template->param(
609         itemdata_enumchron => $itemdata_enumchron,
610         itemdata_ccode     => $itemdata_ccode,
611     );
612
613     if ($numCopiesAvailable > 0) {
614         $numBibsAvailable++;
615         $biblioLoopIter{bib_available} = 1;
616         $biblioLoopIter{holdable} = 1;
617         $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable;
618     }
619     if ($biblioLoopIter{already_reserved}) {
620         $biblioLoopIter{holdable} = undef;
621         $biblioLoopIter{itemholdable} = undef;
622     }
623     if ( $biblioLoopIter{holdable} ) {
624         @not_available_at = uniq @not_available_at;
625         $biblioLoopIter{not_available_at} = \@not_available_at ;
626     }
627
628     unless ( $can_place_hold_if_available_at_pickup ) {
629         @not_available_at = uniq @not_available_at;
630         $biblioLoopIter{not_available_at} = \@not_available_at ;
631         # The record is not holdable is not available at any of the libraries
632         if ( Koha::Libraries->search->count == @not_available_at ) {
633             $biblioLoopIter{holdable} = 0;
634         }
635     }
636
637     my $status = CanBookBeReserved( $borrowernumber, $biblioNum )->{status};
638     $biblioLoopIter{holdable} &&= $status eq 'OK';
639     $biblioLoopIter{already_patron_possession} = $status eq 'alreadypossession';
640
641     # For multiple holds per record, if a patron has previously placed a hold,
642     # the patron can only place more holds of the same type. That is, if the
643     # patron placed a record level hold, all the holds the patron places must
644     # be record level. If the patron placed an item level hold, all holds
645     # the patron places must be item level
646     my $forced_hold_level = Koha::Holds->search(
647         {
648             borrowernumber => $borrowernumber,
649             biblionumber   => $biblioNum,
650             found          => undef,
651         }
652     )->forced_hold_level();
653     if ($forced_hold_level) {
654         $biblioLoopIter{force_hold}   = 1 if $forced_hold_level eq 'item';
655         $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'record';
656         $biblioLoopIter{forced_hold_level} = $forced_hold_level;
657     }
658
659
660     push @$biblioLoop, \%biblioLoopIter;
661
662     $anyholdable = 1 if $biblioLoopIter{holdable};
663 }
664
665 unless ($pickup_locations->count) {
666     $numBibsAvailable = 0;
667     $anyholdable = 0;
668     $template->param(
669         message => 1,
670         no_pickup_locations => 1
671     );
672 }
673
674 if ( $numBibsAvailable == 0 || $anyholdable == 0) {
675     $template->param( none_available => 1 );
676 }
677
678 if (scalar @biblionumbers > 1) {
679     $template->param( multi_hold => 1);
680 }
681
682 my $show_notes=C4::Context->preference('OpacHoldNotes');
683 $template->param(OpacHoldNotes=>$show_notes);
684
685 # display infos
686 $template->param(bibitemloop => $biblioLoop);
687 # can set reserve date in future
688 if (
689     C4::Context->preference( 'AllowHoldDateInFuture' ) &&
690     C4::Context->preference( 'OPACAllowHoldDateInFuture' )
691     ) {
692     $template->param(
693             reserve_in_future         => 1,
694     );
695 }
696
697 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };