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