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