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