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