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