Bug 29736: Restore searching
[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             [
170                 { name        => { like => '%' . $findclub . '%' } },
171                 { description => { like => '%' . $findclub . '%' } }
172             ]
173         )->filter_out_empty->as_list;
174
175         if( scalar @clubs == 1 ) {
176             $club_hold = $clubs[0]->id;
177         } elsif ( @clubs ) {
178             $template->param( clubs => \@clubs );
179         } else {
180             $messageclub = "'$findclub'";
181         }
182     }
183 }
184
185 my @biblionumbers = ();
186 my $biblionumber = $input->param('biblionumber');
187 my $biblionumbers = $input->param('biblionumbers');
188 if ( $biblionumbers ) {
189     @biblionumbers = split '/', $biblionumbers;
190 } else {
191     push @biblionumbers, $input->multi_param('biblionumber');
192 }
193
194 my $multi_hold = @biblionumbers > 1;
195 $template->param(
196     multi_hold => $multi_hold,
197 );
198
199 # If we have the borrowernumber because we've performed an action, then we
200 # don't want to try to place another reserve.
201 if ($borrowernumber_hold && !$action) {
202     my $patron = Koha::Patrons->find( $borrowernumber_hold );
203     my $diffbranch;
204
205     # we check the reserves of the user, and if they can reserve a document
206     # FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
207
208     my $reserves_count = $patron->holds->count;
209
210     my $new_reserves_count = scalar( @biblionumbers );
211
212     my $maxreserves = C4::Context->preference('maxreserves');
213     $template->param( maxreserves => $maxreserves );
214
215     if ( $maxreserves
216         && ( $reserves_count + $new_reserves_count > $maxreserves ) )
217     {
218         my $new_reserves_allowed =
219             $maxreserves - $reserves_count > 0
220           ? $maxreserves - $reserves_count
221           : 0;
222         $warnings             = 1;
223         $exceeded_maxreserves = 1;
224         $template->param(
225             new_reserves_allowed => $new_reserves_allowed,
226             new_reserves_count   => $new_reserves_count,
227             reserves_count       => $reserves_count,
228             maxreserves          => $maxreserves,
229         );
230     }
231
232     # check if the borrower make the reserv in a different branch
233     if ( $patron->branchcode ne C4::Context->userenv->{'branch'} ) {
234         $diffbranch = 1;
235     }
236
237     my $amount_outstanding = $patron->account->balance;
238     $template->param(
239                 patron              => $patron,
240                 diffbranch          => $diffbranch,
241                 messages            => $messages,
242                 warnings            => $warnings,
243                 amount_outstanding  => $amount_outstanding,
244     );
245 }
246
247 if ($club_hold && !$borrowernumber_hold && !$action) {
248     my $club = Koha::Clubs->find($club_hold);
249
250     my $enrollments = $club->club_enrollments;
251
252     my $maxreserves = C4::Context->preference('maxreserves');
253     my $new_reserves_count = scalar( @biblionumbers );
254
255     my @members;
256
257     while(my $enrollment = $enrollments->next) {
258         next if $enrollment->is_canceled;
259         my $member = { patron => $enrollment->patron };
260         my $reserves_count = $enrollment->patron->holds->count;
261         if ( $maxreserves
262             && ( $reserves_count + $new_reserves_count > $maxreserves ) )
263         {
264             $member->{new_reserves_allowed} = $maxreserves - $reserves_count > 0
265                 ? $maxreserves - $reserves_count
266                 : 0;
267             $member->{exceeded_maxreserves} = 1;
268         }
269         $member->{amount_outstanding} = $enrollment->patron->account->balance;
270         if ( $enrollment->patron->branchcode ne C4::Context->userenv->{'branch'} ) {
271             $member->{diffbranch} = 1;
272         }
273
274         push @members, $member;
275     }
276
277     $template->param(
278         club                => $club,
279         members             => \@members,
280         maxreserves         => $maxreserves,
281         new_reserves_count  => $new_reserves_count
282     );
283 }
284
285 unless ( $club_hold or $borrowernumber_hold ) {
286     $template->param( clubcount => Koha::Clubs->search->count );
287 }
288
289 $template->param(
290     messageborrower => $messageborrower,
291     messageclub     => $messageclub
292 );
293
294 # FIXME launch another time GetMember perhaps until (Joubu: Why?)
295 my $patron = Koha::Patrons->find( $borrowernumber_hold );
296
297 if ( $patron && $multi_hold ) {
298     my @multi_pickup_locations =
299       Koha::Biblios->search( { biblionumber => \@biblionumbers } )
300       ->pickup_locations( { patron => $patron } );
301     $template->param( multi_pickup_locations => \@multi_pickup_locations );
302 }
303
304 my $logged_in_patron = Koha::Patrons->find( $borrowernumber );
305
306 my $wants_check;
307 if ($patron) {
308     $wants_check = $patron->wants_check_for_previous_checkout;
309 }
310 my $itemdata_enumchron = 0;
311 my $itemdata_ccode = 0;
312 my @biblioloop = ();
313 my $no_reserves_allowed = 0;
314 foreach my $biblionumber (@biblionumbers) {
315     next unless $biblionumber =~ m|^\d+$|;
316
317     my %biblioloopiter = ();
318
319     my $biblio = Koha::Biblios->find( $biblionumber );
320     unless ($biblio) {
321         $biblioloopiter{noitems} = 1;
322         $template->param('nobiblio' => 1);
323         last;
324     }
325
326     my $force_hold_level;
327     if ( $patron ) {
328         { # CanBookBeReserved
329             my $canReserve = CanBookBeReserved( $patron->borrowernumber, $biblionumber );
330             if ( $canReserve->{status} eq 'OK' ) {
331
332                 #All is OK and we can continue
333             }
334             elsif ( $canReserve->{status} eq 'noReservesAllowed' || $canReserve->{status} eq 'notReservable' ) {
335                 $no_reserves_allowed = 1;
336             }
337             elsif ( $canReserve->{status} eq 'tooManyReserves' ) {
338                 $exceeded_maxreserves = 1;
339                 $template->param( maxreserves => $canReserve->{limit} );
340             }
341             elsif ( $canReserve->{status} eq 'tooManyHoldsForThisRecord' ) {
342                 $exceeded_holds_per_record = 1;
343                 $biblioloopiter{ $canReserve->{status} } = 1;
344             }
345             elsif ( $canReserve->{status} eq 'ageRestricted' ) {
346                 $template->param( $canReserve->{status} => 1 );
347                 $biblioloopiter{ $canReserve->{status} } = 1;
348             }
349             elsif ( $canReserve->{status} eq 'alreadypossession' ) {
350                 $template->param( $canReserve->{status} => 1);
351                 $biblioloopiter{ $canReserve->{status} } = 1;
352             }
353             else {
354                 $biblioloopiter{ $canReserve->{status} } = 1;
355             }
356         }
357
358         # For multiple holds per record, if a patron has previously placed a hold,
359         # the patron can only place more holds of the same type. That is, if the
360         # patron placed a record level hold, all the holds the patron places must
361         # be record level. If the patron placed an item level hold, all holds
362         # the patron places must be item level
363         my $holds = Koha::Holds->search(
364             {
365                 borrowernumber => $patron->borrowernumber,
366                 biblionumber   => $biblionumber,
367                 found          => undef,
368             }
369         );
370         $force_hold_level = $holds->forced_hold_level();
371         $biblioloopiter{force_hold_level} = $force_hold_level;
372         $template->param( force_hold_level => $force_hold_level );
373
374         # For a librarian to be able to place multiple record holds for a patron for a record,
375         # we must find out what the maximum number of holds they can place for the patron is
376         my $max_holds_for_record = GetMaxPatronHoldsForRecord( $patron->borrowernumber, $biblionumber );
377         my $remaining_holds_for_record = $max_holds_for_record - $holds->count();
378         $biblioloopiter{remaining_holds_for_record} = $max_holds_for_record;
379         $template->param( max_holds_for_record => $max_holds_for_record );
380         $template->param( remaining_holds_for_record => $remaining_holds_for_record );
381     }
382
383
384     my $count = Koha::Holds->search( { biblionumber => $biblionumber } )->count();
385     my $totalcount = $count;
386
387     # adding a fixed value for priority options
388     my $fixedRank = $count+1;
389
390     my %itemnumbers_of_biblioitem;
391
392     my @hostitems = get_hostitemnumbers_of($biblionumber);
393     my @itemnumbers;
394     if (@hostitems){
395         $template->param('hostitemsflag' => 1);
396         push(@itemnumbers, @hostitems);
397     }
398
399     my $items = Koha::Items->search({ -or => { biblionumber => $biblionumber, itemnumber => { in => \@itemnumbers } } });
400
401     unless ( $items->count ) {
402         # FIXME Then why do we continue?
403         $template->param('noitems' => 1) unless ( $multi_hold );
404         $biblioloopiter{noitems} = 1;
405     }
406
407     ## Here we go backwards again to create hash of biblioitemnumber to itemnumbers
408     ## this is important when we have analytic items which may be on another record
409     my ( $iteminfos_of );
410     while ( my $item = $items->next ) {
411         $item = $item->unblessed;
412         my $biblioitemnumber = $item->{biblioitemnumber};
413         my $itemnumber = $item->{itemnumber};
414         push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
415         $iteminfos_of->{$itemnumber} = $item;
416     }
417
418     my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
419
420     my $biblioiteminfos_of = {
421         map {
422             my $biblioitem = $_;
423             ( $biblioitem->{biblioitemnumber} => $biblioitem )
424           } @{ Koha::Biblioitems->search(
425                 { biblioitemnumber => { -in => \@biblioitemnumbers } },
426                 { select => ['biblionumber', 'biblioitemnumber', 'publicationyear', 'itemtype']}
427             )->unblessed
428           }
429     };
430
431     my @bibitemloop;
432
433     my @available_itemtypes;
434     foreach my $biblioitemnumber (@biblioitemnumbers) {
435         my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
436         my $num_available = 0;
437         my $num_override  = 0;
438         my $hiddencount   = 0;
439         my $num_alreadyheld = 0;
440
441         $biblioitem->{force_hold_level} = $force_hold_level;
442
443         if ( $biblioitem->{biblioitemnumber} ne $biblionumber ) {
444             $biblioitem->{hostitemsflag} = 1;
445         }
446
447         $biblioloopiter{description} = $biblioitem->{description};
448         $biblioloopiter{itypename}   = $biblioitem->{description};
449         if ( $biblioitem->{itemtype} ) {
450
451             $biblioitem->{description} =
452               $itemtypes->{ $biblioitem->{itemtype} }{description};
453
454             $biblioloopiter{imageurl} =
455               getitemtypeimagelocation( 'intranet',
456                 $itemtypes->{ $biblioitem->{itemtype} }{imageurl} );
457         }
458
459         # iterating through all items first to check if any of them available
460         # to pass this value further inside down to IsAvailableForItemLevelRequest to
461         # it's complicated logic to analyse.
462         # (before this loop was inside that sub loop so it was O(n^2) )
463         my $items_any_available;
464         $items_any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblioitem->{biblionumber}, patron => $patron })
465             if $patron;
466
467         foreach my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } )    {
468             my $item = $iteminfos_of->{$itemnumber};
469             my $do_check;
470             if ( $patron ) {
471                 $do_check = $patron->do_check_for_previous_checkout($item) if $wants_check;
472                 if ( $do_check && $wants_check ) {
473                     $item->{checked_previously} = $do_check;
474                     if ( $multi_hold ) {
475                         $biblioloopiter{checked_previously} = $do_check;
476                     } else {
477                         $template->param( checked_previously => $do_check );
478                     }
479                 }
480             }
481             $item->{force_hold_level} = $force_hold_level;
482
483             unless (C4::Context->preference('item-level_itypes')) {
484                 $item->{itype} = $biblioitem->{itemtype};
485             }
486
487             $item->{itypename} = $itemtypes->{ $item->{itype} }{description};
488             $item->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $item->{itype} }{imageurl} );
489             $item->{homebranch} = $item->{homebranch};
490
491             # if the holdingbranch is different than the homebranch, we show the
492             # holdingbranch of the document too
493             if ( $item->{homebranch} ne $item->{holdingbranch} ) {
494                 $item->{holdingbranch} = $item->{holdingbranch};
495             }
496
497             if($item->{biblionumber} ne $biblionumber){
498                 $item->{hostitemsflag} = 1;
499                 $item->{hosttitle} = Koha::Biblios->find( $item->{biblionumber} )->title;
500             }
501
502             # if the item is currently on loan, we display its return date and
503             # change the background color
504             my $issue = Koha::Checkouts->find( { itemnumber => $itemnumber } );
505             if ( $issue ) {
506                 $item->{date_due} = $issue->date_due;
507                 $item->{backgroundcolor} = 'onloan';
508             }
509
510             # checking reserve
511             my $item_object = Koha::Items->find( $itemnumber );
512             my $holds = $item_object->current_holds;
513             if ( my $first_hold = $holds->next ) {
514                 my $p = Koha::Patrons->find( $first_hold->borrowernumber );
515
516                 $item->{backgroundcolor} = 'reserved';
517                 $item->{reservedate}     = output_pref({ dt => dt_from_string( $first_hold->reservedate ), dateonly => 1 }); # FIXME Should be formatted in the template
518                 $item->{ReservedFor}     = $p;
519                 $item->{ExpectedAtLibrary}     = $first_hold->branchcode;
520                 $item->{waitingdate} = $first_hold->waitingdate;
521             }
522
523             # Management of the notforloan document
524             if ( $item->{notforloan} ) {
525                 $item->{backgroundcolor} = 'other';
526             }
527
528             # Management of lost or long overdue items
529             if ( $item->{itemlost} ) {
530                 $item->{backgroundcolor} = 'other';
531                 if ($logged_in_patron->category->hidelostitems && !$showallitems) {
532                     $item->{hide} = 1;
533                     $hiddencount++;
534                 }
535             }
536
537             # Check the transit status
538             my ( $transfertwhen, $transfertfrom, $transfertto ) =
539               GetTransfers($itemnumber);
540
541             if ( defined $transfertwhen && $transfertwhen ne '' ) {
542                 $item->{transfertwhen} = output_pref({ dt => dt_from_string( $transfertwhen ), dateonly => 1 });
543                 $item->{transfertfrom} = $transfertfrom;
544                 $item->{transfertto} = $transfertto;
545                 $item->{nocancel} = 1;
546             }
547
548             # If there is no loan, return and transfer, we show a checkbox.
549             $item->{notforloan} ||= 0;
550
551             # if independent branches is on we need to check if the person can reserve
552             # for branches they arent logged in to
553             if ( C4::Context->preference("IndependentBranches") ) {
554                 if (! C4::Context->preference("canreservefromotherbranches")){
555                     # can't reserve items so need to check if item homebranch and userenv branch match if not we can't reserve
556                     my $userenv = C4::Context->userenv;
557                     unless ( C4::Context->IsSuperLibrarian ) {
558                         $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
559                     }
560                 }
561             }
562
563             if ( $patron ) {
564                 my $patron_unblessed = $patron->unblessed;
565                 my $branch = C4::Circulation::_GetCircControlBranch($item, $patron_unblessed);
566
567                 my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} );
568
569                 $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
570
571                 my $can_item_be_reserved = CanItemBeReserved( $patron->borrowernumber, $itemnumber )->{status};
572                 $item->{not_holdable} = $can_item_be_reserved unless ( $can_item_be_reserved eq 'OK' );
573
574                 $item->{item_level_holds} = Koha::CirculationRules->get_opacitemholds_policy( { item => $item_object, patron => $patron } );
575
576                 if (
577                        !$item->{cantreserve}
578                     && !$exceeded_maxreserves
579                     && $can_item_be_reserved eq 'OK'
580                     # items_any_available defined outside of the current loop,
581                     # so we avoiding loop inside IsAvailableForItemLevelRequest:
582                     && IsAvailableForItemLevelRequest($item_object, $patron, undef, $items_any_available)
583                   )
584                 {
585                     # Send the pickup locations count to the UI, the pickup locations will be pulled using the API
586                     my @pickup_locations = $item_object->pickup_locations({ patron => $patron })->as_list;
587                     $item->{pickup_locations_count} = scalar @pickup_locations;
588
589                     if ( @pickup_locations ) {
590                         $num_available++;
591                         $item->{available} = 1;
592
593                         my $default_pickup_location;
594
595                         # Default to logged-in, if valid
596                         if ( C4::Context->userenv->{branch} ) {
597                             ($default_pickup_location) = grep { $_->branchcode eq C4::Context->userenv->{branch} } @pickup_locations;
598                         }
599
600                         $item->{default_pickup_location} = $default_pickup_location;
601                     }
602                     else {
603                         $item->{available} = 0;
604                         $item->{not_holdable} = "no_valid_pickup_location";
605                     }
606
607                     push( @available_itemtypes, $item->{itype} );
608                 }
609                 elsif ( C4::Context->preference('AllowHoldPolicyOverride') ) {
610                     # If AllowHoldPolicyOverride is set, it should override EVERY restriction, not just branch item rules
611                     # with the exception of itemAlreadyOnHold because, you know, the item is already on hold
612                     if ( $can_item_be_reserved ne 'itemAlreadyOnHold' ) {
613                         # Send the pickup locations count to the UI, the pickup locations will be pulled using the API
614                         my $pickup_locations = $item_object->pickup_locations({ patron => $patron });
615                         $item->{pickup_locations_count} = $pickup_locations->count;
616                         if ( $item->{pickup_locations_count} > 0 ) {
617                             $item->{override} = 1;
618                             $num_override++;
619                             # pass the holding branch for use as default
620                             my $default_pickup_location = $pickup_locations->search({ branchcode => $item->{holdingbranch} })->next;
621                             $item->{default_pickup_location} = $default_pickup_location;
622                         }
623                         else {
624                             $item->{available} = 0;
625                             $item->{not_holdable} = "no_valid_pickup_location";
626                         }
627                     } else { $num_alreadyheld++ }
628
629                     push( @available_itemtypes, $item->{itype} );
630                 }
631
632                 # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
633
634                 # Show serial enumeration when needed
635                 if ($item->{enumchron}) {
636                     $itemdata_enumchron = 1;
637                 }
638                 # Show collection when needed
639                 if ($item->{ccode}) {
640                     $itemdata_ccode = 1;
641                 }
642             }
643
644             push @{ $biblioitem->{itemloop} }, $item;
645         }
646
647         # While we can't override an alreay held item, we should be able to override the others
648         # Unless all items are already held
649         if ( $num_override > 0 && ($num_override + $num_alreadyheld) == scalar( @{ $biblioitem->{itemloop} } ) ) {
650         # That is, if all items require an override
651             $template->param( override_required => 1 );
652         } elsif ( $num_available == 0 ) {
653             $template->param( none_available => 1 );
654             $biblioloopiter{warn} = 1;
655             $biblioloopiter{none_avail} = 1;
656         }
657         $template->param( hiddencount => $hiddencount);
658
659         push @bibitemloop, $biblioitem;
660     }
661
662     @available_itemtypes = uniq( @available_itemtypes );
663     $template->param( available_itemtypes => \@available_itemtypes );
664
665     # existingreserves building
666     my @reserveloop;
667     my @reserves = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } );
668     foreach my $res (
669         sort {
670             my $a_found = $a->found() || '';
671             my $b_found = $a->found() || '';
672             $a_found cmp $b_found;
673         } @reserves
674       )
675     {
676         my %reserve;
677         if ( $res->is_found() ) {
678             $reserve{'holdingbranch'} = $res->item()->holdingbranch();
679             $reserve{'biblionumber'}  = $res->item()->biblionumber();
680             $reserve{'barcodenumber'} = $res->item()->barcode();
681             $reserve{'wbrcode'}       = $res->branchcode();
682             $reserve{'itemnumber'}    = $res->itemnumber();
683             $reserve{'wbrname'}       = $res->branch()->branchname();
684             $reserve{'atdestination'} = $res->is_at_destination();
685             $reserve{'desk_name'}     = ( $res->desk() ) ? $res->desk()->desk_name() : '' ;
686             $reserve{'found'}     = $res->is_found();
687             $reserve{'inprocessing'} = $res->is_in_processing();
688             $reserve{'intransit'} = $res->is_in_transit();
689         }
690         elsif ( $res->priority() > 0 ) {
691             if ( my $item = $res->item() )  {
692                 $reserve{'itemnumber'}      = $item->id();
693                 $reserve{'barcodenumber'}   = $item->barcode();
694                 $reserve{'item_level_hold'} = 1;
695             }
696         }
697
698         $reserve{'expirationdate'} = $res->expirationdate;
699         $reserve{'date'}           = $res->reservedate;
700         $reserve{'borrowernumber'} = $res->borrowernumber();
701         $reserve{'biblionumber'}   = $res->biblionumber();
702         $reserve{'patron'}         = $res->borrower;
703         $reserve{'notes'}          = $res->reservenotes();
704         $reserve{'waiting_date'}   = $res->waitingdate();
705         $reserve{'ccode'}          = $res->item() ? $res->item()->ccode() : undef;
706         $reserve{'barcode'}        = $res->item() ? $res->item()->barcode() : undef;
707         $reserve{'priority'}       = $res->priority();
708         $reserve{'lowestPriority'} = $res->lowestPriority();
709         $reserve{'suspend'}        = $res->suspend();
710         $reserve{'suspend_until'}  = $res->suspend_until();
711         $reserve{'reserve_id'}     = $res->reserve_id();
712         $reserve{itemtype}         = $res->itemtype();
713         $reserve{branchcode}       = $res->branchcode();
714         $reserve{non_priority}     = $res->non_priority();
715         $reserve{object}           = $res;
716
717         push( @reserveloop, \%reserve );
718     }
719
720     # get the time for the form name...
721     my $time = time();
722
723     $template->param(
724                      time        => $time,
725                      fixedRank   => $fixedRank,
726                     );
727
728     # display infos
729     $template->param(
730                      bibitemloop       => \@bibitemloop,
731                      itemdata_enumchron => $itemdata_enumchron,
732                      itemdata_ccode    => $itemdata_ccode,
733                      date              => $date,
734                      biblionumber      => $biblionumber,
735                      findborrower      => $findborrower,
736                      biblio            => $biblio,
737                      holdsview         => 1,
738                      C4::Search::enabled_staff_search_views,
739                     );
740
741     $biblioloopiter{biblionumber} = $biblionumber;
742     $biblioloopiter{title} = $biblio->title;
743     $biblioloopiter{rank} = $fixedRank;
744     $biblioloopiter{reserveloop} = \@reserveloop;
745
746     if (@reserveloop) {
747         $template->param( reserveloop => \@reserveloop );
748     }
749
750     if ( $patron ) {
751         # Add the valid pickup locations
752         my @pickup_locations = $biblio->pickup_locations({ patron => $patron });
753         $biblioloopiter{pickup_locations} = \@pickup_locations;
754         $biblioloopiter{pickup_locations_codes} = [ map { $_->branchcode } @pickup_locations ];
755     }
756
757     push @biblioloop, \%biblioloopiter;
758 }
759
760 $template->param( biblioloop => \@biblioloop );
761 $template->param( no_reserves_allowed => $no_reserves_allowed );
762 $template->param( biblionumbers => join('/', @biblionumbers) );
763 $template->param( exceeded_maxreserves => $exceeded_maxreserves );
764 $template->param( exceeded_holds_per_record => $exceeded_holds_per_record );
765 $template->param( subscriptionsnumber => CountSubscriptionFromBiblionumber($biblionumber));
766
767 # pass the userenv branch if no pickup location selected
768 $template->param( pickup => $pickup || C4::Context->userenv->{branch} );
769
770 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
771     $template->param( reserve_in_future => 1 );
772 }
773
774 $template->param(
775     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
776     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
777 );
778
779 # printout the page
780 output_html_with_http_headers $input, $cookie, $template->output;
781
782 sub sort_borrowerlist {
783     my $borrowerslist = shift;
784     my $ref           = [];
785     push @{$ref}, sort {
786         uc( $a->{surname} . $a->{firstname} ) cmp
787           uc( $b->{surname} . $b->{firstname} )
788     } @{$borrowerslist};
789     return $ref;
790 }