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