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