Bug 28057: (follow-up) Get the biblionumber column
[koha.git] / reserve / request.pl
1 #!/usr/bin/perl
2
3
4 #written 2/1/00 by chris@katipo.oc.nz
5 # Copyright 2000-2002 Katipo Communications
6 # Parts Copyright 2011 Catalyst IT
7 #
8 # This file is part of Koha.
9 #
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
14 #
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22
23 =head1 request.pl
24
25 script to place reserves/requests
26
27 =cut
28
29 use Modern::Perl;
30
31 use CGI qw ( -utf8 );
32 use List::MoreUtils qw( uniq );
33 use Date::Calc qw( Date_to_Days );
34 use C4::Output qw( output_html_with_http_headers );
35 use C4::Auth qw( get_template_and_user );
36 use C4::Reserves qw( RevertWaitingStatus AlterPriority ToggleLowestPriority ToggleSuspend CanBookBeReserved GetMaxPatronHoldsForRecord ItemsAnyAvailableAndNotRestricted CanItemBeReserved IsAvailableForItemLevelRequest );
37 use C4::Items qw( get_hostitemnumbers_of );
38 use C4::Koha qw( getitemtypeimagelocation );
39 use C4::Serials qw( CountSubscriptionFromBiblionumber );
40 use C4::Circulation qw( GetTransfers _GetCircControlBranch GetBranchItemRule );
41 use Koha::DateUtils qw( dt_from_string output_pref );
42 use C4::Utils::DataTables::Members;
43 use C4::Search qw( enabled_staff_search_views );
44
45 use Koha::Biblios;
46 use Koha::DateUtils qw( dt_from_string output_pref );
47 use Koha::Checkouts;
48 use Koha::Holds;
49 use Koha::CirculationRules;
50 use Koha::Items;
51 use Koha::ItemTypes;
52 use Koha::Libraries;
53 use Koha::Patrons;
54 use Koha::Clubs;
55
56 my $dbh = C4::Context->dbh;
57 my $input = CGI->new;
58 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
59     {
60         template_name   => "reserve/request.tt",
61         query           => $input,
62         type            => "intranet",
63         flagsrequired   => { reserveforothers => 'place_holds' },
64     }
65 );
66
67 my $showallitems = $input->param('showallitems');
68 my $pickup = $input->param('pickup');
69
70 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
71
72 # Select borrowers infos
73 my $findborrower = $input->param('findborrower');
74 $findborrower = '' unless defined $findborrower;
75 $findborrower =~ s|,| |g;
76 my $findclub = $input->param('findclub');
77 $findclub = '' unless defined $findclub && !$findborrower;
78 my $borrowernumber_hold = $input->param('borrowernumber') || '';
79 my $club_hold = $input->param('club')||'';
80 my $messageborrower;
81 my $messageclub;
82 my $warnings;
83 my $messages;
84 my $exceeded_maxreserves;
85 my $exceeded_holds_per_record;
86
87 my $date = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
88 my $action = $input->param('action');
89 $action ||= q{};
90
91 if ( $action eq 'move' ) {
92   my $where           = $input->param('where');
93   my $reserve_id      = $input->param('reserve_id');
94   my $prev_priority   = $input->param('prev_priority');
95   my $next_priority   = $input->param('next_priority');
96   my $first_priority  = $input->param('first_priority');
97   my $last_priority   = $input->param('last_priority');
98   my $hold_itemnumber = $input->param('itemnumber');
99   if ( $prev_priority == 0 && $next_priority == 1 ){
100       C4::Reserves::RevertWaitingStatus({ itemnumber => $hold_itemnumber });
101   } else {
102       AlterPriority( $where, $reserve_id, $prev_priority, $next_priority, $first_priority, $last_priority );
103   }
104 } elsif ( $action eq 'cancel' ) {
105   my $reserve_id = $input->param('reserve_id');
106   my $cancellation_reason = $input->param("cancellation-reason");
107   my $hold = Koha::Holds->find( $reserve_id );
108   $hold->cancel({ cancellation_reason => $cancellation_reason }) if $hold;
109 } elsif ( $action eq 'setLowestPriority' ) {
110   my $reserve_id = $input->param('reserve_id');
111   ToggleLowestPriority( $reserve_id );
112 } elsif ( $action eq 'toggleSuspend' ) {
113   my $reserve_id = $input->param('reserve_id');
114   my $suspend_until  = $input->param('suspend_until');
115   ToggleSuspend( $reserve_id, $suspend_until );
116 }
117
118 if ($findborrower) {
119     my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
120     if ( $patron ) {
121         $borrowernumber_hold = $patron->borrowernumber;
122     } else {
123         my $dt_params = { iDisplayLength => -1 };
124         my $results = C4::Utils::DataTables::Members::search(
125             {
126                 searchmember => $findborrower,
127                 dt_params => $dt_params,
128             }
129         );
130         my $borrowers = $results->{patrons};
131         if ( scalar @$borrowers == 1 ) {
132             $borrowernumber_hold = $borrowers->[0]->{borrowernumber};
133         } elsif ( @$borrowers ) {
134             $template->param( borrowers => $borrowers );
135         } else {
136             $messageborrower = "'$findborrower'";
137         }
138     }
139 }
140
141 if($findclub) {
142     my $club = Koha::Clubs->find( { name => $findclub } );
143     if( $club ) {
144         $club_hold = $club->id;
145     } else {
146         my @clubs = Koha::Clubs->search( [
147             { name => { like => '%'.$findclub.'%' } },
148             { description => { like => '%'.$findclub.'%' } }
149         ] );
150         if( scalar @clubs == 1 ) {
151             $club_hold = $clubs[0]->id;
152         } elsif ( @clubs ) {
153             $template->param( clubs => \@clubs );
154         } else {
155             $messageclub = "'$findclub'";
156         }
157     }
158 }
159
160 my @biblionumbers = ();
161 my $biblionumber = $input->param('biblionumber');
162 my $biblionumbers = $input->param('biblionumbers');
163 if ( $biblionumbers ) {
164     @biblionumbers = split '/', $biblionumbers;
165 } else {
166     push @biblionumbers, $input->multi_param('biblionumber');
167 }
168
169 my $multi_hold = @biblionumbers > 1;
170 $template->param(
171     multi_hold => $multi_hold,
172 );
173
174 # If we have the borrowernumber because we've performed an action, then we
175 # don't want to try to place another reserve.
176 if ($borrowernumber_hold && !$action) {
177     my $patron = Koha::Patrons->find( $borrowernumber_hold );
178     my $diffbranch;
179
180     # we check the reserves of the user, and if they can reserve a document
181     # FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
182
183     my $reserves_count = $patron->holds->count;
184
185     my $new_reserves_count = scalar( @biblionumbers );
186
187     my $maxreserves = C4::Context->preference('maxreserves');
188     $template->param( maxreserves => $maxreserves );
189
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 if ( $patron && $multi_hold ) {
288     my @multi_pickup_locations =
289       Koha::Biblios->search( { biblionumber => \@biblionumbers } )
290       ->pickup_locations( { patron => $patron } );
291     $template->param( multi_pickup_locations => \@multi_pickup_locations );
292 }
293
294 my $logged_in_patron = Koha::Patrons->find( $borrowernumber );
295
296 my $wants_check;
297 if ($patron) {
298     $wants_check = $patron->wants_check_for_previous_checkout;
299 }
300 my $itemdata_enumchron = 0;
301 my $itemdata_ccode = 0;
302 my @biblioloop = ();
303 my $no_reserves_allowed = 0;
304 foreach my $biblionumber (@biblionumbers) {
305     next unless $biblionumber =~ m|^\d+$|;
306
307     my %biblioloopiter = ();
308
309     my $biblio = Koha::Biblios->find( $biblionumber );
310
311     my $force_hold_level;
312     if ( $patron ) {
313         { # CanBookBeReserved
314             my $canReserve = CanBookBeReserved( $patron->borrowernumber, $biblionumber );
315             if ( $canReserve->{status} eq 'OK' ) {
316
317                 #All is OK and we can continue
318             }
319             elsif ( $canReserve->{status} eq 'noReservesAllowed' || $canReserve->{status} eq 'notReservable' ) {
320                 $no_reserves_allowed = 1;
321             }
322             elsif ( $canReserve->{status} eq 'tooManyReserves' ) {
323                 $exceeded_maxreserves = 1;
324                 $template->param( maxreserves => $canReserve->{limit} );
325             }
326             elsif ( $canReserve->{status} eq 'tooManyHoldsForThisRecord' ) {
327                 $exceeded_holds_per_record = 1;
328                 $biblioloopiter{ $canReserve->{status} } = 1;
329             }
330             elsif ( $canReserve->{status} eq 'ageRestricted' ) {
331                 $template->param( $canReserve->{status} => 1 );
332                 $biblioloopiter{ $canReserve->{status} } = 1;
333             }
334             elsif ( $canReserve->{status} eq 'alreadypossession' ) {
335                 $template->param( $canReserve->{status} => 1);
336                 $biblioloopiter{ $canReserve->{status} } = 1;
337             }
338             else {
339                 $biblioloopiter{ $canReserve->{status} } = 1;
340             }
341         }
342
343         # For multiple holds per record, if a patron has previously placed a hold,
344         # the patron can only place more holds of the same type. That is, if the
345         # patron placed a record level hold, all the holds the patron places must
346         # be record level. If the patron placed an item level hold, all holds
347         # the patron places must be item level
348         my $holds = Koha::Holds->search(
349             {
350                 borrowernumber => $patron->borrowernumber,
351                 biblionumber   => $biblionumber,
352                 found          => undef,
353             }
354         );
355         $force_hold_level = $holds->forced_hold_level();
356         $biblioloopiter{force_hold_level} = $force_hold_level;
357         $template->param( force_hold_level => $force_hold_level );
358
359         # For a librarian to be able to place multiple record holds for a patron for a record,
360         # we must find out what the maximum number of holds they can place for the patron is
361         my $max_holds_for_record = GetMaxPatronHoldsForRecord( $patron->borrowernumber, $biblionumber );
362         my $remaining_holds_for_record = $max_holds_for_record - $holds->count();
363         $biblioloopiter{remaining_holds_for_record} = $max_holds_for_record;
364         $template->param( max_holds_for_record => $max_holds_for_record );
365         $template->param( remaining_holds_for_record => $remaining_holds_for_record );
366     }
367
368
369     my $count = Koha::Holds->search( { biblionumber => $biblionumber } )->count();
370     my $totalcount = $count;
371
372     # FIXME think @optionloop, is maybe obsolete, or  must be switchable by a systeme preference fixed rank or not
373     # make priorities options
374
375     my @optionloop;
376     for ( 1 .. $count + 1 ) {
377         push(
378              @optionloop,
379              {
380               num      => $_,
381               selected => ( $_ == $count + 1 ),
382              }
383             );
384     }
385     # adding a fixed value for priority options
386     my $fixedRank = $count+1;
387
388     my %itemnumbers_of_biblioitem;
389
390     my @hostitems = get_hostitemnumbers_of($biblionumber);
391     my @itemnumbers;
392     if (@hostitems){
393         $template->param('hostitemsflag' => 1);
394         push(@itemnumbers, @hostitems);
395     }
396
397     my $items = Koha::Items->search({ -or => { biblionumber => $biblionumber, itemnumber => { in => \@itemnumbers } } });
398
399     unless ( $items->count ) {
400         # FIXME Then why do we continue?
401         $template->param('noitems' => 1);
402         $biblioloopiter{noitems} = 1;
403     }
404
405     ## Here we go backwards again to create hash of biblioitemnumber to itemnumbers
406     ## this is important when we have analytic items which may be on another record
407     my ( $iteminfos_of );
408     while ( my $item = $items->next ) {
409         $item = $item->unblessed;
410         my $biblioitemnumber = $item->{biblioitemnumber};
411         my $itemnumber = $item->{itemnumber};
412         push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
413         $iteminfos_of->{$itemnumber} = $item;
414     }
415
416     my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
417
418     my $biblioiteminfos_of = {
419         map {
420             my $biblioitem = $_;
421             ( $biblioitem->{biblioitemnumber} => $biblioitem )
422           } @{ Koha::Biblioitems->search(
423                 { biblioitemnumber => { -in => \@biblioitemnumbers } },
424                 { select => ['biblionumber', 'biblioitemnumber', 'publicationyear', 'itemtype']}
425             )->unblessed
426           }
427     };
428
429     my @bibitemloop;
430
431     my @available_itemtypes;
432     foreach my $biblioitemnumber (@biblioitemnumbers) {
433         my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
434         my $num_available = 0;
435         my $num_override  = 0;
436         my $hiddencount   = 0;
437         my $num_alreadyheld = 0;
438
439         $biblioitem->{force_hold_level} = $force_hold_level;
440
441         if ( $biblioitem->{biblioitemnumber} ne $biblionumber ) {
442             $biblioitem->{hostitemsflag} = 1;
443         }
444
445         $biblioloopiter{description} = $biblioitem->{description};
446         $biblioloopiter{itypename}   = $biblioitem->{description};
447         if ( $biblioitem->{itemtype} ) {
448
449             $biblioitem->{description} =
450               $itemtypes->{ $biblioitem->{itemtype} }{description};
451
452             $biblioloopiter{imageurl} =
453               getitemtypeimagelocation( 'intranet',
454                 $itemtypes->{ $biblioitem->{itemtype} }{imageurl} );
455         }
456
457         # iterating through all items first to check if any of them available
458         # to pass this value further inside down to IsAvailableForItemLevelRequest to
459         # it's complicated logic to analyse.
460         # (before this loop was inside that sub loop so it was O(n^2) )
461         my $items_any_available;
462         $items_any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblioitem->{biblionumber}, patron => $patron })
463             if $patron;
464
465         foreach my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } )    {
466             my $item = $iteminfos_of->{$itemnumber};
467             my $do_check;
468             if ( $patron ) {
469                 $do_check = $patron->do_check_for_previous_checkout($item) if $wants_check;
470                 if ( $do_check && $wants_check ) {
471                     $item->{checked_previously} = $do_check;
472                     if ( $multi_hold ) {
473                         $biblioloopiter{checked_previously} = $do_check;
474                     } else {
475                         $template->param( checked_previously => $do_check );
476                     }
477                 }
478             }
479             $item->{force_hold_level} = $force_hold_level;
480
481             unless (C4::Context->preference('item-level_itypes')) {
482                 $item->{itype} = $biblioitem->{itemtype};
483             }
484
485             $item->{itypename} = $itemtypes->{ $item->{itype} }{description};
486             $item->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $item->{itype} }{imageurl} );
487             $item->{homebranch} = $item->{homebranch};
488
489             # if the holdingbranch is different than the homebranch, we show the
490             # holdingbranch of the document too
491             if ( $item->{homebranch} ne $item->{holdingbranch} ) {
492                 $item->{holdingbranch} = $item->{holdingbranch};
493             }
494
495             if($item->{biblionumber} ne $biblionumber){
496                 $item->{hostitemsflag} = 1;
497                 $item->{hosttitle} = Koha::Biblios->find( $item->{biblionumber} )->title;
498             }
499
500             # if the item is currently on loan, we display its return date and
501             # change the background color
502             my $issue = Koha::Checkouts->find( { itemnumber => $itemnumber } );
503             if ( $issue ) {
504                 $item->{date_due} = $issue->date_due;
505                 $item->{backgroundcolor} = 'onloan';
506             }
507
508             # checking reserve
509             my $item_object = Koha::Items->find( $itemnumber );
510             my $holds = $item_object->current_holds;
511             if ( my $first_hold = $holds->next ) {
512                 my $p = Koha::Patrons->find( $first_hold->borrowernumber );
513
514                 $item->{backgroundcolor} = 'reserved';
515                 $item->{reservedate}     = output_pref({ dt => dt_from_string( $first_hold->reservedate ), dateonly => 1 }); # FIXME Should be formatted in the template
516                 $item->{ReservedFor}     = $p;
517                 $item->{ExpectedAtLibrary}     = $first_hold->branchcode;
518                 $item->{waitingdate} = $first_hold->waitingdate;
519             }
520
521             # Management of the notforloan document
522             if ( $item->{notforloan} ) {
523                 $item->{backgroundcolor} = 'other';
524             }
525
526             # Management of lost or long overdue items
527             if ( $item->{itemlost} ) {
528                 $item->{backgroundcolor} = 'other';
529                 if ($logged_in_patron->category->hidelostitems && !$showallitems) {
530                     $item->{hide} = 1;
531                     $hiddencount++;
532                 }
533             }
534
535             # Check the transit status
536             my ( $transfertwhen, $transfertfrom, $transfertto ) =
537               GetTransfers($itemnumber);
538
539             if ( defined $transfertwhen && $transfertwhen ne '' ) {
540                 $item->{transfertwhen} = output_pref({ dt => dt_from_string( $transfertwhen ), dateonly => 1 });
541                 $item->{transfertfrom} = $transfertfrom;
542                 $item->{transfertto} = $transfertto;
543                 $item->{nocancel} = 1;
544             }
545
546             # If there is no loan, return and transfer, we show a checkbox.
547             $item->{notforloan} ||= 0;
548
549             # if independent branches is on we need to check if the person can reserve
550             # for branches they arent logged in to
551             if ( C4::Context->preference("IndependentBranches") ) {
552                 if (! C4::Context->preference("canreservefromotherbranches")){
553                     # can't reserve items so need to check if item homebranch and userenv branch match if not we can't reserve
554                     my $userenv = C4::Context->userenv;
555                     unless ( C4::Context->IsSuperLibrarian ) {
556                         $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
557                     }
558                 }
559             }
560
561             if ( $patron ) {
562                 my $patron_unblessed = $patron->unblessed;
563                 my $branch = C4::Circulation::_GetCircControlBranch($item, $patron_unblessed);
564
565                 my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} );
566
567                 $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
568
569                 my $can_item_be_reserved = CanItemBeReserved( $patron->borrowernumber, $itemnumber )->{status};
570                 $item->{not_holdable} = $can_item_be_reserved unless ( $can_item_be_reserved eq 'OK' );
571
572                 $item->{item_level_holds} = Koha::CirculationRules->get_opacitemholds_policy( { item => $item_object, patron => $patron } );
573
574                 if (
575                        !$item->{cantreserve}
576                     && !$exceeded_maxreserves
577                     && $can_item_be_reserved eq 'OK'
578                     # items_any_available defined outside of the current loop,
579                     # so we avoiding loop inside IsAvailableForItemLevelRequest:
580                     && IsAvailableForItemLevelRequest($item_object, $patron, undef, $items_any_available)
581                   )
582                 {
583                     # Send the pickup locations count to the UI, the pickup locations will be pulled using the API
584                     my $pickup_locations = $item_object->pickup_locations({ patron => $patron });
585                     $item->{pickup_locations_count} = $pickup_locations->count;
586                     if ( $item->{pickup_locations_count} > 0 ) {
587                         $num_available++;
588                         $item->{available} = 1;
589                         # pass the holding branch for use as default
590                         my $default_pickup_location = $pickup_locations->search({ branchcode => $item->{holdingbranch} })->next;
591                         $item->{default_pickup_location} = $default_pickup_location;
592                     }
593                     else {
594                         $item->{available} = 0;
595                         $item->{not_holdable} = "no_valid_pickup_location";
596                     }
597
598                     push( @available_itemtypes, $item->{itype} );
599                 }
600                 elsif ( C4::Context->preference('AllowHoldPolicyOverride') ) {
601                     # If AllowHoldPolicyOverride is set, it should override EVERY restriction, not just branch item rules
602                     # with the exception of itemAlreadyOnHold because, you know, the item is already on hold
603                     if ( $can_item_be_reserved ne 'itemAlreadyOnHold' ) {
604                         $item->{override} = 1;
605                         $num_override++;
606                     } else { $num_alreadyheld++ }
607
608                     push( @available_itemtypes, $item->{itype} );
609                 }
610
611                 # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
612
613                 # Show serial enumeration when needed
614                 if ($item->{enumchron}) {
615                     $itemdata_enumchron = 1;
616                 }
617                 # Show collection when needed
618                 if ($item->{ccode}) {
619                     $itemdata_ccode = 1;
620                 }
621             }
622
623             push @{ $biblioitem->{itemloop} }, $item;
624         }
625
626         # While we can't override an alreay held item, we should be able to override the others
627         # Unless all items are already held
628         if ( $num_override > 0 && ($num_override + $num_alreadyheld) == scalar( @{ $biblioitem->{itemloop} } ) ) {
629         # That is, if all items require an override
630             $template->param( override_required => 1 );
631         } elsif ( $num_available == 0 ) {
632             $template->param( none_available => 1 );
633             $biblioloopiter{warn} = 1;
634             $biblioloopiter{none_avail} = 1;
635         }
636         $template->param( hiddencount => $hiddencount);
637
638         push @bibitemloop, $biblioitem;
639     }
640
641     @available_itemtypes = uniq( @available_itemtypes );
642     $template->param( available_itemtypes => \@available_itemtypes );
643
644     # existingreserves building
645     my @reserveloop;
646     my @reserves = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } );
647     foreach my $res (
648         sort {
649             my $a_found = $a->found() || '';
650             my $b_found = $a->found() || '';
651             $a_found cmp $b_found;
652         } @reserves
653       )
654     {
655         my $priority = $res->priority();
656         my %reserve;
657         my @optionloop;
658         for ( my $i = 1 ; $i <= $totalcount ; $i++ ) {
659             push(
660                 @optionloop,
661                 {
662                     num      => $i,
663                     selected => ( $i == $priority ),
664                 }
665             );
666         }
667
668         if ( $res->is_found() ) {
669             $reserve{'holdingbranch'} = $res->item()->holdingbranch();
670             $reserve{'biblionumber'}  = $res->item()->biblionumber();
671             $reserve{'barcodenumber'} = $res->item()->barcode();
672             $reserve{'wbrcode'}       = $res->branchcode();
673             $reserve{'itemnumber'}    = $res->itemnumber();
674             $reserve{'wbrname'}       = $res->branch()->branchname();
675             $reserve{'atdestination'} = $res->is_at_destination();
676             $reserve{'desk_name'}     = ( $res->desk() ) ? $res->desk()->desk_name() : '' ;
677             $reserve{'found'}     = $res->is_found();
678             $reserve{'inprocessing'} = $res->is_in_processing();
679             $reserve{'intransit'} = $res->is_in_transit();
680         }
681         elsif ( $res->priority() > 0 ) {
682             if ( my $item = $res->item() )  {
683                 $reserve{'itemnumber'}      = $item->id();
684                 $reserve{'barcodenumber'}   = $item->barcode();
685                 $reserve{'item_level_hold'} = 1;
686             }
687         }
688
689         $reserve{'expirationdate'} = $res->expirationdate;
690         $reserve{'date'}           = $res->reservedate;
691         $reserve{'borrowernumber'} = $res->borrowernumber();
692         $reserve{'biblionumber'}   = $res->biblionumber();
693         $reserve{'patron'}         = $res->borrower;
694         $reserve{'notes'}          = $res->reservenotes();
695         $reserve{'waiting_date'}   = $res->waitingdate();
696         $reserve{'ccode'}          = $res->item() ? $res->item()->ccode() : undef;
697         $reserve{'barcode'}        = $res->item() ? $res->item()->barcode() : undef;
698         $reserve{'priority'}       = $res->priority();
699         $reserve{'lowestPriority'} = $res->lowestPriority();
700         $reserve{'optionloop'}     = \@optionloop;
701         $reserve{'suspend'}        = $res->suspend();
702         $reserve{'suspend_until'}  = $res->suspend_until();
703         $reserve{'reserve_id'}     = $res->reserve_id();
704         $reserve{itemtype}         = $res->itemtype();
705         $reserve{branchcode}       = $res->branchcode();
706         $reserve{non_priority}     = $res->non_priority();
707         $reserve{object}           = $res;
708
709         push( @reserveloop, \%reserve );
710     }
711
712     # get the time for the form name...
713     my $time = time();
714
715     $template->param(
716                      time        => $time,
717                      fixedRank   => $fixedRank,
718                     );
719
720     # display infos
721     $template->param(
722                      optionloop        => \@optionloop,
723                      bibitemloop       => \@bibitemloop,
724                      itemdata_enumchron => $itemdata_enumchron,
725                      itemdata_ccode    => $itemdata_ccode,
726                      date              => $date,
727                      biblionumber      => $biblionumber,
728                      findborrower      => $findborrower,
729                      biblio            => $biblio,
730                      holdsview         => 1,
731                      C4::Search::enabled_staff_search_views,
732                     );
733
734     $biblioloopiter{biblionumber} = $biblionumber;
735     $biblioloopiter{title} = $biblio->title;
736     $biblioloopiter{rank} = $fixedRank;
737     $biblioloopiter{reserveloop} = \@reserveloop;
738
739     if (@reserveloop) {
740         $template->param( reserveloop => \@reserveloop );
741     }
742
743     if ( $patron ) {
744         # Add the valid pickup locations
745         my @pickup_locations = $biblio->pickup_locations({ patron => $patron });
746         $biblioloopiter{pickup_locations} = \@pickup_locations;
747         $biblioloopiter{pickup_locations_codes} = [ map { $_->branchcode } @pickup_locations ];
748     }
749
750     push @biblioloop, \%biblioloopiter;
751 }
752
753 $template->param( biblioloop => \@biblioloop );
754 $template->param( no_reserves_allowed => $no_reserves_allowed );
755 $template->param( biblionumbers => join('/', @biblionumbers) );
756 $template->param( exceeded_maxreserves => $exceeded_maxreserves );
757 $template->param( exceeded_holds_per_record => $exceeded_holds_per_record );
758 $template->param( subscriptionsnumber => CountSubscriptionFromBiblionumber($biblionumber));
759
760 # pass the userenv branch if no pickup location selected
761 $template->param( pickup => $pickup || C4::Context->userenv->{branch} );
762
763 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
764     $template->param( reserve_in_future => 1 );
765 }
766
767 $template->param(
768     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
769     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
770 );
771
772 # printout the page
773 output_html_with_http_headers $input, $cookie, $template->output;
774
775 sub sort_borrowerlist {
776     my $borrowerslist = shift;
777     my $ref           = [];
778     push @{$ref}, sort {
779         uc( $a->{surname} . $a->{firstname} ) cmp
780           uc( $b->{surname} . $b->{firstname} )
781     } @{$borrowerslist};
782     return $ref;
783 }