Bug 27947: Add cancellation reason to article request
[koha.git] / reserve / request.pl
1 #!/usr/bin/perl
2
3
4 #written 2/1/00 by chris@katipo.oc.nz
5 # Copyright 2000-2002 Katipo Communications
6 # Parts Copyright 2011 Catalyst IT
7 #
8 # This file is part of Koha.
9 #
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22
23 =head1 request.pl
24
25 script to place reserves/requests
26
27 =cut
28
29 use Modern::Perl;
30
31 use CGI qw ( -utf8 );
32 use List::MoreUtils qw( uniq );
33 use Date::Calc qw( Date_to_Days );
34 use C4::Output qw( output_html_with_http_headers );
35 use C4::Auth qw( get_template_and_user );
36 use C4::Reserves qw( RevertWaitingStatus AlterPriority ToggleLowestPriority ToggleSuspend CanBookBeReserved GetMaxPatronHoldsForRecord ItemsAnyAvailableAndNotRestricted CanItemBeReserved IsAvailableForItemLevelRequest );
37 use C4::Items qw( get_hostitemnumbers_of );
38 use C4::Koha qw( getitemtypeimagelocation );
39 use C4::Serials qw( CountSubscriptionFromBiblionumber );
40 use C4::Circulation qw( GetTransfers _GetCircControlBranch GetBranchItemRule );
41 use Koha::DateUtils qw( dt_from_string output_pref );
42 use C4::Utils::DataTables::Members;
43 use C4::Search qw( enabled_staff_search_views );
44
45 use Koha::Biblios;
46 use Koha::DateUtils qw( dt_from_string output_pref );
47 use Koha::Checkouts;
48 use Koha::Holds;
49 use Koha::CirculationRules;
50 use Koha::Items;
51 use Koha::ItemTypes;
52 use Koha::Libraries;
53 use Koha::Patrons;
54 use Koha::Clubs;
55 use Koha::BackgroundJob::BatchCancelHold;
56
57 my $dbh = C4::Context->dbh;
58 my $input = CGI->new;
59 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
60     {
61         template_name   => "reserve/request.tt",
62         query           => $input,
63         type            => "intranet",
64         flagsrequired   => { reserveforothers => 'place_holds' },
65     }
66 );
67
68 my $showallitems = $input->param('showallitems');
69 my $pickup = $input->param('pickup');
70
71 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
72
73 # Select borrowers infos
74 my $findborrower = $input->param('findborrower');
75 $findborrower = '' unless defined $findborrower;
76 $findborrower =~ s|,| |g;
77 my $findclub = $input->param('findclub');
78 $findclub = '' unless defined $findclub && !$findborrower;
79 my $borrowernumber_hold = $input->param('borrowernumber') || '';
80 my $club_hold = $input->param('club')||'';
81 my $messageborrower;
82 my $messageclub;
83 my $warnings;
84 my $messages;
85 my $exceeded_maxreserves;
86 my $exceeded_holds_per_record;
87
88 my $date = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
89 my $action = $input->param('action');
90 $action ||= q{};
91
92 if ( $action eq 'move' ) {
93     my $where           = $input->param('where');
94     my $reserve_id      = $input->param('reserve_id');
95     my $prev_priority   = $input->param('prev_priority');
96     my $next_priority   = $input->param('next_priority');
97     my $first_priority  = $input->param('first_priority');
98     my $last_priority   = $input->param('last_priority');
99     my $hold_itemnumber = $input->param('itemnumber');
100     if ( $prev_priority == 0 && $next_priority == 1 ) {
101         C4::Reserves::RevertWaitingStatus( { itemnumber => $hold_itemnumber } );
102     }
103     else {
104         AlterPriority(
105             $where,         $reserve_id,     $prev_priority,
106             $next_priority, $first_priority, $last_priority
107         );
108     }
109 }
110 elsif ( $action eq 'cancel' ) {
111     my $reserve_id          = $input->param('reserve_id');
112     my $cancellation_reason = $input->param("cancellation-reason");
113     my $hold                = Koha::Holds->find($reserve_id);
114     $hold->cancel( { cancellation_reason => $cancellation_reason } ) if $hold;
115 }
116 elsif ( $action eq 'setLowestPriority' ) {
117     my $reserve_id = $input->param('reserve_id');
118     ToggleLowestPriority($reserve_id);
119 }
120 elsif ( $action eq 'toggleSuspend' ) {
121     my $reserve_id    = $input->param('reserve_id');
122     my $suspend_until = $input->param('suspend_until');
123     ToggleSuspend( $reserve_id, $suspend_until );
124 }
125 elsif ( $action eq 'cancelBulk' ) {
126     my $cancellation_reason = $input->param("cancellation-reason");
127     my @hold_ids            = split ',', $input->param("ids");
128     my $params              = {
129         reason   => $cancellation_reason,
130         hold_ids => \@hold_ids,
131     };
132     my $job_id = Koha::BackgroundJob::BatchCancelHold->new->enqueue($params);
133
134     $template->param(
135         enqueued => 1,
136         job_id   => $job_id
137     );
138 }
139
140 if ($findborrower) {
141     my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
142     if ( $patron ) {
143         $borrowernumber_hold = $patron->borrowernumber;
144     } else {
145         my $dt_params = { iDisplayLength => -1 };
146         my $results = C4::Utils::DataTables::Members::search(
147             {
148                 searchmember => $findborrower,
149                 dt_params => $dt_params,
150             }
151         );
152         my $borrowers = $results->{patrons};
153         if ( scalar @$borrowers == 1 ) {
154             $borrowernumber_hold = $borrowers->[0]->{borrowernumber};
155         } elsif ( @$borrowers ) {
156             $template->param( borrowers => $borrowers );
157         } else {
158             $messageborrower = "'$findborrower'";
159         }
160     }
161 }
162
163 if($findclub) {
164     my $club = Koha::Clubs->find( { name => $findclub } );
165     if( $club ) {
166         $club_hold = $club->id;
167     } else {
168         my @clubs = Koha::Clubs->search( [
169             { name => { like => '%'.$findclub.'%' } },
170             { description => { like => '%'.$findclub.'%' } }
171         ] );
172         if( scalar @clubs == 1 ) {
173             $club_hold = $clubs[0]->id;
174         } elsif ( @clubs ) {
175             $template->param( clubs => \@clubs );
176         } else {
177             $messageclub = "'$findclub'";
178         }
179     }
180 }
181
182 my @biblionumbers = ();
183 my $biblionumber = $input->param('biblionumber');
184 my $biblionumbers = $input->param('biblionumbers');
185 if ( $biblionumbers ) {
186     @biblionumbers = split '/', $biblionumbers;
187 } else {
188     push @biblionumbers, $input->multi_param('biblionumber');
189 }
190
191 my $multi_hold = @biblionumbers > 1;
192 $template->param(
193     multi_hold => $multi_hold,
194 );
195
196 # If we have the borrowernumber because we've performed an action, then we
197 # don't want to try to place another reserve.
198 if ($borrowernumber_hold && !$action) {
199     my $patron = Koha::Patrons->find( $borrowernumber_hold );
200     my $diffbranch;
201
202     # we check the reserves of the user, and if they can reserve a document
203     # FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
204
205     my $reserves_count = $patron->holds->count;
206
207     my $new_reserves_count = scalar( @biblionumbers );
208
209     my $maxreserves = C4::Context->preference('maxreserves');
210     $template->param( maxreserves => $maxreserves );
211
212     if ( $maxreserves
213         && ( $reserves_count + $new_reserves_count > $maxreserves ) )
214     {
215         my $new_reserves_allowed =
216             $maxreserves - $reserves_count > 0
217           ? $maxreserves - $reserves_count
218           : 0;
219         $warnings             = 1;
220         $exceeded_maxreserves = 1;
221         $template->param(
222             new_reserves_allowed => $new_reserves_allowed,
223             new_reserves_count   => $new_reserves_count,
224             reserves_count       => $reserves_count,
225             maxreserves          => $maxreserves,
226         );
227     }
228
229     # we check the date expiry of the borrower (only if there is an expiry date, otherwise, set to 1 (warn)
230     my $expiry_date = $patron->dateexpiry;
231     my $expiry = 0; # flag set if patron account has expired
232     if ($expiry_date and
233         Date_to_Days(split /-/,$date) > Date_to_Days(split /-/,$expiry_date)) {
234         $expiry = 1;
235     }
236
237     # check if the borrower make the reserv in a different branch
238     if ( $patron->branchcode ne C4::Context->userenv->{'branch'} ) {
239         $diffbranch = 1;
240     }
241
242     my $amount_outstanding = $patron->account->balance;
243     $template->param(
244                 patron              => $patron,
245                 expiry              => $expiry,
246                 diffbranch          => $diffbranch,
247                 messages            => $messages,
248                 warnings            => $warnings,
249                 amount_outstanding  => $amount_outstanding,
250     );
251 }
252
253 if ($club_hold && !$borrowernumber_hold && !$action) {
254     my $club = Koha::Clubs->find($club_hold);
255
256     my $enrollments = $club->club_enrollments;
257
258     my $maxreserves = C4::Context->preference('maxreserves');
259     my $new_reserves_count = scalar( @biblionumbers );
260
261     my @members;
262
263     while(my $enrollment = $enrollments->next) {
264         next if $enrollment->is_canceled;
265         my $member = { patron => $enrollment->patron->unblessed };
266         my $reserves_count = $enrollment->patron->holds->count;
267         if ( $maxreserves
268             && ( $reserves_count + $new_reserves_count > $maxreserves ) )
269         {
270             $member->{new_reserves_allowed} = $maxreserves - $reserves_count > 0
271                 ? $maxreserves - $reserves_count
272                 : 0;
273             $member->{exceeded_maxreserves} = 1;
274         }
275         my $expiry_date = $enrollment->patron->dateexpiry;
276         $member->{expiry} = 0; # flag set if patron account has expired
277         if ($expiry_date and
278             Date_to_Days(split /-/,$date) > Date_to_Days(split /-/,$expiry_date)) {
279             $member->{expiry} = 1;
280         }
281         $member->{amount_outstanding} = $enrollment->patron->account->balance;
282         if ( $enrollment->patron->branchcode ne C4::Context->userenv->{'branch'} ) {
283             $member->{diffbranch} = 1;
284         }
285
286         push @members, $member;
287     }
288
289     $template->param(
290         club                => $club,
291         members             => \@members,
292         maxreserves         => $maxreserves,
293         new_reserves_count  => $new_reserves_count
294     );
295 }
296
297 unless ( $club_hold or $borrowernumber_hold ) {
298     $template->param( clubcount => Koha::Clubs->search->count );
299 }
300
301 $template->param(
302     messageborrower => $messageborrower,
303     messageclub     => $messageclub
304 );
305
306 # FIXME launch another time GetMember perhaps until (Joubu: Why?)
307 my $patron = Koha::Patrons->find( $borrowernumber_hold );
308
309 if ( $patron && $multi_hold ) {
310     my @multi_pickup_locations =
311       Koha::Biblios->search( { biblionumber => \@biblionumbers } )
312       ->pickup_locations( { patron => $patron } );
313     $template->param( multi_pickup_locations => \@multi_pickup_locations );
314 }
315
316 my $logged_in_patron = Koha::Patrons->find( $borrowernumber );
317
318 my $wants_check;
319 if ($patron) {
320     $wants_check = $patron->wants_check_for_previous_checkout;
321 }
322 my $itemdata_enumchron = 0;
323 my $itemdata_ccode = 0;
324 my @biblioloop = ();
325 my $no_reserves_allowed = 0;
326 foreach my $biblionumber (@biblionumbers) {
327     next unless $biblionumber =~ m|^\d+$|;
328
329     my %biblioloopiter = ();
330
331     my $biblio = Koha::Biblios->find( $biblionumber );
332     unless ($biblio) {
333         $biblioloopiter{noitems} = 1;
334         $template->param('nobiblio' => 1);
335         last;
336     }
337
338     my $force_hold_level;
339     if ( $patron ) {
340         { # CanBookBeReserved
341             my $canReserve = CanBookBeReserved( $patron->borrowernumber, $biblionumber );
342             if ( $canReserve->{status} eq 'OK' ) {
343
344                 #All is OK and we can continue
345             }
346             elsif ( $canReserve->{status} eq 'noReservesAllowed' || $canReserve->{status} eq 'notReservable' ) {
347                 $no_reserves_allowed = 1;
348             }
349             elsif ( $canReserve->{status} eq 'tooManyReserves' ) {
350                 $exceeded_maxreserves = 1;
351                 $template->param( maxreserves => $canReserve->{limit} );
352             }
353             elsif ( $canReserve->{status} eq 'tooManyHoldsForThisRecord' ) {
354                 $exceeded_holds_per_record = 1;
355                 $biblioloopiter{ $canReserve->{status} } = 1;
356             }
357             elsif ( $canReserve->{status} eq 'ageRestricted' ) {
358                 $template->param( $canReserve->{status} => 1 );
359                 $biblioloopiter{ $canReserve->{status} } = 1;
360             }
361             elsif ( $canReserve->{status} eq 'alreadypossession' ) {
362                 $template->param( $canReserve->{status} => 1);
363                 $biblioloopiter{ $canReserve->{status} } = 1;
364             }
365             else {
366                 $biblioloopiter{ $canReserve->{status} } = 1;
367             }
368         }
369
370         # For multiple holds per record, if a patron has previously placed a hold,
371         # the patron can only place more holds of the same type. That is, if the
372         # patron placed a record level hold, all the holds the patron places must
373         # be record level. If the patron placed an item level hold, all holds
374         # the patron places must be item level
375         my $holds = Koha::Holds->search(
376             {
377                 borrowernumber => $patron->borrowernumber,
378                 biblionumber   => $biblionumber,
379                 found          => undef,
380             }
381         );
382         $force_hold_level = $holds->forced_hold_level();
383         $biblioloopiter{force_hold_level} = $force_hold_level;
384         $template->param( force_hold_level => $force_hold_level );
385
386         # For a librarian to be able to place multiple record holds for a patron for a record,
387         # we must find out what the maximum number of holds they can place for the patron is
388         my $max_holds_for_record = GetMaxPatronHoldsForRecord( $patron->borrowernumber, $biblionumber );
389         my $remaining_holds_for_record = $max_holds_for_record - $holds->count();
390         $biblioloopiter{remaining_holds_for_record} = $max_holds_for_record;
391         $template->param( max_holds_for_record => $max_holds_for_record );
392         $template->param( remaining_holds_for_record => $remaining_holds_for_record );
393     }
394
395
396     my $count = Koha::Holds->search( { biblionumber => $biblionumber } )->count();
397     my $totalcount = $count;
398
399     # adding a fixed value for priority options
400     my $fixedRank = $count+1;
401
402     my %itemnumbers_of_biblioitem;
403
404     my @hostitems = get_hostitemnumbers_of($biblionumber);
405     my @itemnumbers;
406     if (@hostitems){
407         $template->param('hostitemsflag' => 1);
408         push(@itemnumbers, @hostitems);
409     }
410
411     my $items = Koha::Items->search({ -or => { biblionumber => $biblionumber, itemnumber => { in => \@itemnumbers } } });
412
413     unless ( $items->count ) {
414         # FIXME Then why do we continue?
415         $template->param('noitems' => 1) unless ( $multi_hold );
416         $biblioloopiter{noitems} = 1;
417     }
418
419     ## Here we go backwards again to create hash of biblioitemnumber to itemnumbers
420     ## this is important when we have analytic items which may be on another record
421     my ( $iteminfos_of );
422     while ( my $item = $items->next ) {
423         $item = $item->unblessed;
424         my $biblioitemnumber = $item->{biblioitemnumber};
425         my $itemnumber = $item->{itemnumber};
426         push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
427         $iteminfos_of->{$itemnumber} = $item;
428     }
429
430     my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
431
432     my $biblioiteminfos_of = {
433         map {
434             my $biblioitem = $_;
435             ( $biblioitem->{biblioitemnumber} => $biblioitem )
436           } @{ Koha::Biblioitems->search(
437                 { biblioitemnumber => { -in => \@biblioitemnumbers } },
438                 { select => ['biblionumber', 'biblioitemnumber', 'publicationyear', 'itemtype']}
439             )->unblessed
440           }
441     };
442
443     my @bibitemloop;
444
445     my @available_itemtypes;
446     foreach my $biblioitemnumber (@biblioitemnumbers) {
447         my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
448         my $num_available = 0;
449         my $num_override  = 0;
450         my $hiddencount   = 0;
451         my $num_alreadyheld = 0;
452
453         $biblioitem->{force_hold_level} = $force_hold_level;
454
455         if ( $biblioitem->{biblioitemnumber} ne $biblionumber ) {
456             $biblioitem->{hostitemsflag} = 1;
457         }
458
459         $biblioloopiter{description} = $biblioitem->{description};
460         $biblioloopiter{itypename}   = $biblioitem->{description};
461         if ( $biblioitem->{itemtype} ) {
462
463             $biblioitem->{description} =
464               $itemtypes->{ $biblioitem->{itemtype} }{description};
465
466             $biblioloopiter{imageurl} =
467               getitemtypeimagelocation( 'intranet',
468                 $itemtypes->{ $biblioitem->{itemtype} }{imageurl} );
469         }
470
471         # iterating through all items first to check if any of them available
472         # to pass this value further inside down to IsAvailableForItemLevelRequest to
473         # it's complicated logic to analyse.
474         # (before this loop was inside that sub loop so it was O(n^2) )
475         my $items_any_available;
476         $items_any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblioitem->{biblionumber}, patron => $patron })
477             if $patron;
478
479         foreach my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } )    {
480             my $item = $iteminfos_of->{$itemnumber};
481             my $do_check;
482             if ( $patron ) {
483                 $do_check = $patron->do_check_for_previous_checkout($item) if $wants_check;
484                 if ( $do_check && $wants_check ) {
485                     $item->{checked_previously} = $do_check;
486                     if ( $multi_hold ) {
487                         $biblioloopiter{checked_previously} = $do_check;
488                     } else {
489                         $template->param( checked_previously => $do_check );
490                     }
491                 }
492             }
493             $item->{force_hold_level} = $force_hold_level;
494
495             unless (C4::Context->preference('item-level_itypes')) {
496                 $item->{itype} = $biblioitem->{itemtype};
497             }
498
499             $item->{itypename} = $itemtypes->{ $item->{itype} }{description};
500             $item->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $item->{itype} }{imageurl} );
501             $item->{homebranch} = $item->{homebranch};
502
503             # if the holdingbranch is different than the homebranch, we show the
504             # holdingbranch of the document too
505             if ( $item->{homebranch} ne $item->{holdingbranch} ) {
506                 $item->{holdingbranch} = $item->{holdingbranch};
507             }
508
509             if($item->{biblionumber} ne $biblionumber){
510                 $item->{hostitemsflag} = 1;
511                 $item->{hosttitle} = Koha::Biblios->find( $item->{biblionumber} )->title;
512             }
513
514             # if the item is currently on loan, we display its return date and
515             # change the background color
516             my $issue = Koha::Checkouts->find( { itemnumber => $itemnumber } );
517             if ( $issue ) {
518                 $item->{date_due} = $issue->date_due;
519                 $item->{backgroundcolor} = 'onloan';
520             }
521
522             # checking reserve
523             my $item_object = Koha::Items->find( $itemnumber );
524             my $holds = $item_object->current_holds;
525             if ( my $first_hold = $holds->next ) {
526                 my $p = Koha::Patrons->find( $first_hold->borrowernumber );
527
528                 $item->{backgroundcolor} = 'reserved';
529                 $item->{reservedate}     = output_pref({ dt => dt_from_string( $first_hold->reservedate ), dateonly => 1 }); # FIXME Should be formatted in the template
530                 $item->{ReservedFor}     = $p;
531                 $item->{ExpectedAtLibrary}     = $first_hold->branchcode;
532                 $item->{waitingdate} = $first_hold->waitingdate;
533             }
534
535             # Management of the notforloan document
536             if ( $item->{notforloan} ) {
537                 $item->{backgroundcolor} = 'other';
538             }
539
540             # Management of lost or long overdue items
541             if ( $item->{itemlost} ) {
542                 $item->{backgroundcolor} = 'other';
543                 if ($logged_in_patron->category->hidelostitems && !$showallitems) {
544                     $item->{hide} = 1;
545                     $hiddencount++;
546                 }
547             }
548
549             # Check the transit status
550             my ( $transfertwhen, $transfertfrom, $transfertto ) =
551               GetTransfers($itemnumber);
552
553             if ( defined $transfertwhen && $transfertwhen ne '' ) {
554                 $item->{transfertwhen} = output_pref({ dt => dt_from_string( $transfertwhen ), dateonly => 1 });
555                 $item->{transfertfrom} = $transfertfrom;
556                 $item->{transfertto} = $transfertto;
557                 $item->{nocancel} = 1;
558             }
559
560             # If there is no loan, return and transfer, we show a checkbox.
561             $item->{notforloan} ||= 0;
562
563             # if independent branches is on we need to check if the person can reserve
564             # for branches they arent logged in to
565             if ( C4::Context->preference("IndependentBranches") ) {
566                 if (! C4::Context->preference("canreservefromotherbranches")){
567                     # can't reserve items so need to check if item homebranch and userenv branch match if not we can't reserve
568                     my $userenv = C4::Context->userenv;
569                     unless ( C4::Context->IsSuperLibrarian ) {
570                         $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
571                     }
572                 }
573             }
574
575             if ( $patron ) {
576                 my $patron_unblessed = $patron->unblessed;
577                 my $branch = C4::Circulation::_GetCircControlBranch($item, $patron_unblessed);
578
579                 my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} );
580
581                 $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
582
583                 my $can_item_be_reserved = CanItemBeReserved( $patron->borrowernumber, $itemnumber )->{status};
584                 $item->{not_holdable} = $can_item_be_reserved unless ( $can_item_be_reserved eq 'OK' );
585
586                 $item->{item_level_holds} = Koha::CirculationRules->get_opacitemholds_policy( { item => $item_object, patron => $patron } );
587
588                 if (
589                        !$item->{cantreserve}
590                     && !$exceeded_maxreserves
591                     && $can_item_be_reserved eq 'OK'
592                     # items_any_available defined outside of the current loop,
593                     # so we avoiding loop inside IsAvailableForItemLevelRequest:
594                     && IsAvailableForItemLevelRequest($item_object, $patron, undef, $items_any_available)
595                   )
596                 {
597                     # Send the pickup locations count to the UI, the pickup locations will be pulled using the API
598                     my $pickup_locations = $item_object->pickup_locations({ patron => $patron });
599                     $item->{pickup_locations_count} = $pickup_locations->count;
600                     if ( $item->{pickup_locations_count} > 0 ) {
601                         $num_available++;
602                         $item->{available} = 1;
603                         # pass the holding branch for use as default
604                         my $default_pickup_location = $pickup_locations->search({ branchcode => $item->{holdingbranch} })->next;
605                         $item->{default_pickup_location} = $default_pickup_location;
606                     }
607                     else {
608                         $item->{available} = 0;
609                         $item->{not_holdable} = "no_valid_pickup_location";
610                     }
611
612                     push( @available_itemtypes, $item->{itype} );
613                 }
614                 elsif ( C4::Context->preference('AllowHoldPolicyOverride') ) {
615                     # If AllowHoldPolicyOverride is set, it should override EVERY restriction, not just branch item rules
616                     # with the exception of itemAlreadyOnHold because, you know, the item is already on hold
617                     if ( $can_item_be_reserved ne 'itemAlreadyOnHold' ) {
618                         $item->{override} = 1;
619                         $num_override++;
620                     } else { $num_alreadyheld++ }
621
622                     push( @available_itemtypes, $item->{itype} );
623                 }
624
625                 # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
626
627                 # Show serial enumeration when needed
628                 if ($item->{enumchron}) {
629                     $itemdata_enumchron = 1;
630                 }
631                 # Show collection when needed
632                 if ($item->{ccode}) {
633                     $itemdata_ccode = 1;
634                 }
635             }
636
637             push @{ $biblioitem->{itemloop} }, $item;
638         }
639
640         # While we can't override an alreay held item, we should be able to override the others
641         # Unless all items are already held
642         if ( $num_override > 0 && ($num_override + $num_alreadyheld) == scalar( @{ $biblioitem->{itemloop} } ) ) {
643         # That is, if all items require an override
644             $template->param( override_required => 1 );
645         } elsif ( $num_available == 0 ) {
646             $template->param( none_available => 1 );
647             $biblioloopiter{warn} = 1;
648             $biblioloopiter{none_avail} = 1;
649         }
650         $template->param( hiddencount => $hiddencount);
651
652         push @bibitemloop, $biblioitem;
653     }
654
655     @available_itemtypes = uniq( @available_itemtypes );
656     $template->param( available_itemtypes => \@available_itemtypes );
657
658     # existingreserves building
659     my @reserveloop;
660     my @reserves = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } );
661     foreach my $res (
662         sort {
663             my $a_found = $a->found() || '';
664             my $b_found = $a->found() || '';
665             $a_found cmp $b_found;
666         } @reserves
667       )
668     {
669         my %reserve;
670         if ( $res->is_found() ) {
671             $reserve{'holdingbranch'} = $res->item()->holdingbranch();
672             $reserve{'biblionumber'}  = $res->item()->biblionumber();
673             $reserve{'barcodenumber'} = $res->item()->barcode();
674             $reserve{'wbrcode'}       = $res->branchcode();
675             $reserve{'itemnumber'}    = $res->itemnumber();
676             $reserve{'wbrname'}       = $res->branch()->branchname();
677             $reserve{'atdestination'} = $res->is_at_destination();
678             $reserve{'desk_name'}     = ( $res->desk() ) ? $res->desk()->desk_name() : '' ;
679             $reserve{'found'}     = $res->is_found();
680             $reserve{'inprocessing'} = $res->is_in_processing();
681             $reserve{'intransit'} = $res->is_in_transit();
682         }
683         elsif ( $res->priority() > 0 ) {
684             if ( my $item = $res->item() )  {
685                 $reserve{'itemnumber'}      = $item->id();
686                 $reserve{'barcodenumber'}   = $item->barcode();
687                 $reserve{'item_level_hold'} = 1;
688             }
689         }
690
691         $reserve{'expirationdate'} = $res->expirationdate;
692         $reserve{'date'}           = $res->reservedate;
693         $reserve{'borrowernumber'} = $res->borrowernumber();
694         $reserve{'biblionumber'}   = $res->biblionumber();
695         $reserve{'patron'}         = $res->borrower;
696         $reserve{'notes'}          = $res->reservenotes();
697         $reserve{'waiting_date'}   = $res->waitingdate();
698         $reserve{'ccode'}          = $res->item() ? $res->item()->ccode() : undef;
699         $reserve{'barcode'}        = $res->item() ? $res->item()->barcode() : undef;
700         $reserve{'priority'}       = $res->priority();
701         $reserve{'lowestPriority'} = $res->lowestPriority();
702         $reserve{'suspend'}        = $res->suspend();
703         $reserve{'suspend_until'}  = $res->suspend_until();
704         $reserve{'reserve_id'}     = $res->reserve_id();
705         $reserve{itemtype}         = $res->itemtype();
706         $reserve{branchcode}       = $res->branchcode();
707         $reserve{non_priority}     = $res->non_priority();
708         $reserve{object}           = $res;
709
710         push( @reserveloop, \%reserve );
711     }
712
713     # get the time for the form name...
714     my $time = time();
715
716     $template->param(
717                      time        => $time,
718                      fixedRank   => $fixedRank,
719                     );
720
721     # display infos
722     $template->param(
723                      bibitemloop       => \@bibitemloop,
724                      itemdata_enumchron => $itemdata_enumchron,
725                      itemdata_ccode    => $itemdata_ccode,
726                      date              => $date,
727                      biblionumber      => $biblionumber,
728                      findborrower      => $findborrower,
729                      biblio            => $biblio,
730                      holdsview         => 1,
731                      C4::Search::enabled_staff_search_views,
732                     );
733
734     $biblioloopiter{biblionumber} = $biblionumber;
735     $biblioloopiter{title} = $biblio->title;
736     $biblioloopiter{rank} = $fixedRank;
737     $biblioloopiter{reserveloop} = \@reserveloop;
738
739     if (@reserveloop) {
740         $template->param( reserveloop => \@reserveloop );
741     }
742
743     if ( $patron ) {
744         # Add the valid pickup locations
745         my @pickup_locations = $biblio->pickup_locations({ patron => $patron });
746         $biblioloopiter{pickup_locations} = \@pickup_locations;
747         $biblioloopiter{pickup_locations_codes} = [ map { $_->branchcode } @pickup_locations ];
748     }
749
750     push @biblioloop, \%biblioloopiter;
751 }
752
753 $template->param( biblioloop => \@biblioloop );
754 $template->param( no_reserves_allowed => $no_reserves_allowed );
755 $template->param( biblionumbers => join('/', @biblionumbers) );
756 $template->param( exceeded_maxreserves => $exceeded_maxreserves );
757 $template->param( exceeded_holds_per_record => $exceeded_holds_per_record );
758 $template->param( subscriptionsnumber => CountSubscriptionFromBiblionumber($biblionumber));
759
760 # pass the userenv branch if no pickup location selected
761 $template->param( pickup => $pickup || C4::Context->userenv->{branch} );
762
763 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
764     $template->param( reserve_in_future => 1 );
765 }
766
767 $template->param(
768     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
769     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
770 );
771
772 # printout the page
773 output_html_with_http_headers $input, $cookie, $template->output;
774
775 sub sort_borrowerlist {
776     my $borrowerslist = shift;
777     my $ref           = [];
778     push @{$ref}, sort {
779         uc( $a->{surname} . $a->{firstname} ) cmp
780           uc( $b->{surname} . $b->{firstname} )
781     } @{$borrowerslist};
782     return $ref;
783 }