Bug 29660: Remove hostitemsflag
[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 use Koha::BackgroundJob::BatchCancelHold;
56
57 my $dbh = C4::Context->dbh;
58 my $input = CGI->new;
59 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
60     {
61         template_name   => "reserve/request.tt",
62         query           => $input,
63         type            => "intranet",
64         flagsrequired   => { reserveforothers => 'place_holds' },
65     }
66 );
67
68 my $showallitems = $input->param('showallitems');
69 my $pickup = $input->param('pickup');
70
71 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
72
73 # Select borrowers infos
74 my $findborrower = $input->param('findborrower');
75 $findborrower = '' unless defined $findborrower;
76 $findborrower =~ s|,| |g;
77 my $findclub = $input->param('findclub');
78 $findclub = '' unless defined $findclub && !$findborrower;
79 my $borrowernumber_hold = $input->param('borrowernumber') || '';
80 my $club_hold = $input->param('club')||'';
81 my $messageborrower;
82 my $messageclub;
83 my $warnings;
84 my $messages;
85 my $exceeded_maxreserves;
86 my $exceeded_holds_per_record;
87
88 my $date = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
89 my $action = $input->param('action');
90 $action ||= q{};
91
92 if ( $action eq 'move' ) {
93     my $where           = $input->param('where');
94     my $reserve_id      = $input->param('reserve_id');
95     my $prev_priority   = $input->param('prev_priority');
96     my $next_priority   = $input->param('next_priority');
97     my $first_priority  = $input->param('first_priority');
98     my $last_priority   = $input->param('last_priority');
99     my $hold_itemnumber = $input->param('itemnumber');
100     if ( $prev_priority == 0 && $next_priority == 1 ) {
101         C4::Reserves::RevertWaitingStatus( { itemnumber => $hold_itemnumber } );
102     }
103     else {
104         AlterPriority(
105             $where,         $reserve_id,     $prev_priority,
106             $next_priority, $first_priority, $last_priority
107         );
108     }
109 }
110 elsif ( $action eq 'cancel' ) {
111     my $reserve_id          = $input->param('reserve_id');
112     my $cancellation_reason = $input->param("cancellation-reason");
113     my $hold                = Koha::Holds->find($reserve_id);
114     $hold->cancel( { cancellation_reason => $cancellation_reason } ) if $hold;
115 }
116 elsif ( $action eq 'setLowestPriority' ) {
117     my $reserve_id = $input->param('reserve_id');
118     ToggleLowestPriority($reserve_id);
119 }
120 elsif ( $action eq 'toggleSuspend' ) {
121     my $reserve_id    = $input->param('reserve_id');
122     my $suspend_until = $input->param('suspend_until');
123     ToggleSuspend( $reserve_id, $suspend_until );
124 }
125 elsif ( $action eq 'cancelBulk' ) {
126     my $cancellation_reason = $input->param("cancellation-reason");
127     my @hold_ids            = split ',', $input->param("ids");
128     my $params              = {
129         reason   => $cancellation_reason,
130         hold_ids => \@hold_ids,
131     };
132     my $job_id = Koha::BackgroundJob::BatchCancelHold->new->enqueue($params);
133
134     $template->param(
135         enqueued => 1,
136         job_id   => $job_id
137     );
138 }
139
140 if ($findborrower) {
141     my $patron = Koha::Patrons->find( { cardnumber => $findborrower } );
142     if ( $patron ) {
143         $borrowernumber_hold = $patron->borrowernumber;
144     } else {
145         my $dt_params = { iDisplayLength => -1 };
146         my $results = C4::Utils::DataTables::Members::search(
147             {
148                 searchmember => $findborrower,
149                 dt_params => $dt_params,
150             }
151         );
152         my $borrowers = $results->{patrons};
153         if ( scalar @$borrowers == 1 ) {
154             $borrowernumber_hold = $borrowers->[0]->{borrowernumber};
155         } elsif ( @$borrowers ) {
156             $template->param( borrowers => $borrowers );
157         } else {
158             $messageborrower = "'$findborrower'";
159         }
160     }
161 }
162
163 if($findclub) {
164     my $club = Koha::Clubs->find( { name => $findclub } );
165     if( $club ) {
166         $club_hold = $club->id;
167     } else {
168         my @clubs = Koha::Clubs->search(
169             [
170                 { name        => { like => '%' . $findclub . '%' } },
171                 { description => { like => '%' . $findclub . '%' } }
172             ]
173         )->filter_out_empty->as_list;
174
175         if( scalar @clubs == 1 ) {
176             $club_hold = $clubs[0]->id;
177         } elsif ( @clubs ) {
178             $template->param( clubs => \@clubs );
179         } else {
180             $messageclub = "'$findclub'";
181         }
182     }
183 }
184
185 my @biblionumbers = ();
186 my $biblionumber = $input->param('biblionumber');
187 my $biblionumbers = $input->param('biblionumbers');
188 if ( $biblionumbers ) {
189     @biblionumbers = split '/', $biblionumbers;
190 } else {
191     push @biblionumbers, $input->multi_param('biblionumber');
192 }
193
194 my $multi_hold = @biblionumbers > 1;
195 $template->param(
196     multi_hold => $multi_hold,
197 );
198
199 # If we are coming from the search result and only 1 is selected
200 $biblionumber ||= $biblionumbers[0] unless $multi_hold;
201
202 # If we have the borrowernumber because we've performed an action, then we
203 # don't want to try to place another reserve.
204 if ($borrowernumber_hold && !$action) {
205     my $patron = Koha::Patrons->find( $borrowernumber_hold );
206     my $diffbranch;
207
208     # we check the reserves of the user, and if they can reserve a document
209     # FIXME At this time we have a simple count of reservs, but, later, we could improve the infos "title" ...
210
211     my $reserves_count = $patron->holds->count;
212
213     my $new_reserves_count = scalar( @biblionumbers );
214
215     my $maxreserves = C4::Context->preference('maxreserves');
216     $template->param( maxreserves => $maxreserves );
217
218     if ( $maxreserves
219         && ( $reserves_count + $new_reserves_count > $maxreserves ) )
220     {
221         my $new_reserves_allowed =
222             $maxreserves - $reserves_count > 0
223           ? $maxreserves - $reserves_count
224           : 0;
225         $warnings             = 1;
226         $exceeded_maxreserves = 1;
227         $template->param(
228             new_reserves_allowed => $new_reserves_allowed,
229             new_reserves_count   => $new_reserves_count,
230             reserves_count       => $reserves_count,
231             maxreserves          => $maxreserves,
232         );
233     }
234
235     # check if the borrower make the reserv in a different branch
236     if ( $patron->branchcode ne C4::Context->userenv->{'branch'} ) {
237         $diffbranch = 1;
238     }
239
240     my $amount_outstanding = $patron->account->balance;
241     $template->param(
242                 patron              => $patron,
243                 diffbranch          => $diffbranch,
244                 messages            => $messages,
245                 warnings            => $warnings,
246                 amount_outstanding  => $amount_outstanding,
247     );
248 }
249
250 if ($club_hold && !$borrowernumber_hold && !$action) {
251     my $club = Koha::Clubs->find($club_hold);
252
253     my $enrollments = $club->club_enrollments;
254
255     my $maxreserves = C4::Context->preference('maxreserves');
256     my $new_reserves_count = scalar( @biblionumbers );
257
258     my @members;
259
260     while(my $enrollment = $enrollments->next) {
261         next if $enrollment->is_canceled;
262         my $member = { patron => $enrollment->patron };
263         my $reserves_count = $enrollment->patron->holds->count;
264         if ( $maxreserves
265             && ( $reserves_count + $new_reserves_count > $maxreserves ) )
266         {
267             $member->{new_reserves_allowed} = $maxreserves - $reserves_count > 0
268                 ? $maxreserves - $reserves_count
269                 : 0;
270             $member->{exceeded_maxreserves} = 1;
271         }
272         $member->{amount_outstanding} = $enrollment->patron->account->balance;
273         if ( $enrollment->patron->branchcode ne C4::Context->userenv->{'branch'} ) {
274             $member->{diffbranch} = 1;
275         }
276
277         push @members, $member;
278     }
279
280     $template->param(
281         club                => $club,
282         members             => \@members,
283         maxreserves         => $maxreserves,
284         new_reserves_count  => $new_reserves_count
285     );
286 }
287
288 unless ( $club_hold or $borrowernumber_hold ) {
289     $template->param( clubcount => Koha::Clubs->search->count );
290 }
291
292 $template->param(
293     messageborrower => $messageborrower,
294     messageclub     => $messageclub
295 );
296
297 # Load the hold list if
298 #  - we are searching for a patron or club and found one
299 #  - we are not searching for anything
300 if (   ( $findborrower && $borrowernumber_hold || $findclub && $club_hold )
301     || ( !$findborrower && !$findclub ) )
302 {
303     # FIXME launch another time GetMember perhaps until (Joubu: Why?)
304     my $patron = Koha::Patrons->find( $borrowernumber_hold );
305
306     if ( $patron && $multi_hold ) {
307         my @multi_pickup_locations =
308           Koha::Biblios->search( { biblionumber => \@biblionumbers } )
309           ->pickup_locations( { patron => $patron } )->as_list;
310         $template->param( multi_pickup_locations => \@multi_pickup_locations );
311     }
312
313     my $logged_in_patron = Koha::Patrons->find( $borrowernumber );
314
315     my $wants_check;
316     if ($patron) {
317         $wants_check = $patron->wants_check_for_previous_checkout;
318     }
319     my $itemdata_enumchron = 0;
320     my $itemdata_ccode = 0;
321     my @biblioloop = ();
322     my $no_reserves_allowed = 0;
323     foreach my $biblionumber (@biblionumbers) {
324         next unless $biblionumber =~ m|^\d+$|;
325
326         my %biblioloopiter = ();
327
328         my $biblio = Koha::Biblios->find( $biblionumber );
329         unless ($biblio) {
330             $biblioloopiter{noitems} = 1;
331             $template->param('nobiblio' => 1);
332             last;
333         }
334
335         my $force_hold_level;
336         if ( $patron ) {
337             { # CanBookBeReserved
338                 my $canReserve = CanBookBeReserved( $patron->borrowernumber, $biblionumber );
339                 if ( $canReserve->{status} eq 'OK' ) {
340
341                     #All is OK and we can continue
342                 }
343                 elsif ( $canReserve->{status} eq 'noReservesAllowed' || $canReserve->{status} eq 'notReservable' ) {
344                     $no_reserves_allowed = 1;
345                 }
346                 elsif ( $canReserve->{status} eq 'tooManyReserves' ) {
347                     $exceeded_maxreserves = 1;
348                     $template->param( maxreserves => $canReserve->{limit} );
349                 }
350                 elsif ( $canReserve->{status} eq 'tooManyHoldsForThisRecord' ) {
351                     $exceeded_holds_per_record = 1;
352                     $biblioloopiter{ $canReserve->{status} } = 1;
353                 }
354                 elsif ( $canReserve->{status} eq 'ageRestricted' ) {
355                     $template->param( $canReserve->{status} => 1 );
356                     $biblioloopiter{ $canReserve->{status} } = 1;
357                 }
358                 elsif ( $canReserve->{status} eq 'alreadypossession' ) {
359                     $template->param( $canReserve->{status} => 1);
360                     $biblioloopiter{ $canReserve->{status} } = 1;
361                 }
362                 else {
363                     $biblioloopiter{ $canReserve->{status} } = 1;
364                 }
365             }
366
367             # For multiple holds per record, if a patron has previously placed a hold,
368             # the patron can only place more holds of the same type. That is, if the
369             # patron placed a record level hold, all the holds the patron places must
370             # be record level. If the patron placed an item level hold, all holds
371             # the patron places must be item level
372             my $holds = Koha::Holds->search(
373                 {
374                     borrowernumber => $patron->borrowernumber,
375                     biblionumber   => $biblionumber,
376                     found          => undef,
377                 }
378             );
379             $force_hold_level = $holds->forced_hold_level();
380             $biblioloopiter{force_hold_level} = $force_hold_level;
381             $template->param( force_hold_level => $force_hold_level );
382
383             # For a librarian to be able to place multiple record holds for a patron for a record,
384             # we must find out what the maximum number of holds they can place for the patron is
385             my $max_holds_for_record = GetMaxPatronHoldsForRecord( $patron->borrowernumber, $biblionumber );
386             my $remaining_holds_for_record = $max_holds_for_record - $holds->count();
387             $biblioloopiter{remaining_holds_for_record} = $max_holds_for_record;
388             $template->param( max_holds_for_record => $max_holds_for_record );
389             $template->param( remaining_holds_for_record => $remaining_holds_for_record );
390         }
391
392
393         my $count = Koha::Holds->search( { biblionumber => $biblionumber } )->count();
394         my $totalcount = $count;
395
396         # adding a fixed value for priority options
397         my $fixedRank = $count+1;
398
399         my %itemnumbers_of_biblioitem;
400
401         my @hostitems = get_hostitemnumbers_of($biblionumber);
402         my @itemnumbers;
403         if (@hostitems){
404             push(@itemnumbers, @hostitems);
405         }
406
407         my $items = Koha::Items->search({ -or => { biblionumber => $biblionumber, itemnumber => { in => \@itemnumbers } } });
408
409         unless ( $items->count ) {
410             # FIXME Then why do we continue?
411             $template->param('noitems' => 1) unless ( $multi_hold );
412             $biblioloopiter{noitems} = 1;
413         }
414
415         ## Here we go backwards again to create hash of biblioitemnumber to itemnumbers
416         ## this is important when we have analytic items which may be on another record
417         my ( $iteminfos_of );
418         while ( my $item = $items->next ) {
419             $item = $item->unblessed;
420             my $biblioitemnumber = $item->{biblioitemnumber};
421             my $itemnumber = $item->{itemnumber};
422             push( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} }, $itemnumber );
423             $iteminfos_of->{$itemnumber} = $item;
424         }
425
426         my @biblioitemnumbers = keys %itemnumbers_of_biblioitem;
427
428         my $biblioiteminfos_of = {
429             map {
430                 my $biblioitem = $_;
431                 ( $biblioitem->{biblioitemnumber} => $biblioitem )
432               } @{ Koha::Biblioitems->search(
433                     { biblioitemnumber => { -in => \@biblioitemnumbers } },
434                     { select => ['biblionumber', 'biblioitemnumber', 'publicationyear', 'itemtype']}
435                 )->unblessed
436               }
437         };
438
439         if ( $club_hold or $borrowernumber_hold ) {
440             my @bibitemloop;
441
442             my @available_itemtypes;
443             foreach my $biblioitemnumber (@biblioitemnumbers) {
444                 my $biblioitem = $biblioiteminfos_of->{$biblioitemnumber};
445                 my $num_available = 0;
446                 my $num_override  = 0;
447                 my $hiddencount   = 0;
448                 my $num_alreadyheld = 0;
449
450                 $biblioitem->{force_hold_level} = $force_hold_level;
451
452                 $biblioloopiter{description} = $biblioitem->{description};
453                 $biblioloopiter{itypename}   = $biblioitem->{description};
454                 if ( $biblioitem->{itemtype} ) {
455
456                     $biblioitem->{description} =
457                       $itemtypes->{ $biblioitem->{itemtype} }{description};
458
459                     $biblioloopiter{imageurl} =
460                       getitemtypeimagelocation( 'intranet',
461                         $itemtypes->{ $biblioitem->{itemtype} }{imageurl} );
462                 }
463
464                 # iterating through all items first to check if any of them available
465                 # to pass this value further inside down to IsAvailableForItemLevelRequest to
466                 # it's complicated logic to analyse.
467                 # (before this loop was inside that sub loop so it was O(n^2) )
468                 my $items_any_available;
469                 $items_any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblioitem->{biblionumber}, patron => $patron })
470                     if $patron;
471
472                 foreach my $itemnumber ( @{ $itemnumbers_of_biblioitem{$biblioitemnumber} } )    {
473                     my $item = $iteminfos_of->{$itemnumber};
474                     my $do_check;
475                     if ( $patron ) {
476                         $do_check = $patron->do_check_for_previous_checkout($item) if $wants_check;
477                         if ( $do_check && $wants_check ) {
478                             $item->{checked_previously} = $do_check;
479                             if ( $multi_hold ) {
480                                 $biblioloopiter{checked_previously} = $do_check;
481                             } else {
482                                 $template->param( checked_previously => $do_check );
483                             }
484                         }
485                     }
486                     $item->{force_hold_level} = $force_hold_level;
487
488                     unless (C4::Context->preference('item-level_itypes')) {
489                         $item->{itype} = $biblioitem->{itemtype};
490                     }
491
492                     $item->{itypename} = $itemtypes->{ $item->{itype} }{description};
493                     $item->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $item->{itype} }{imageurl} );
494                     $item->{homebranch} = $item->{homebranch};
495
496                     # if the holdingbranch is different than the homebranch, we show the
497                     # holdingbranch of the document too
498                     if ( $item->{homebranch} ne $item->{holdingbranch} ) {
499                         $item->{holdingbranch} = $item->{holdingbranch};
500                     }
501
502                     if($item->{biblionumber} ne $biblionumber){
503                         $item->{hosttitle} = Koha::Biblios->find( $item->{biblionumber} )->title;
504                     }
505
506                     # if the item is currently on loan, we display its return date and
507                     # change the background color
508                     my $issue = Koha::Checkouts->find( { itemnumber => $itemnumber } );
509                     if ( $issue ) {
510                         $item->{date_due} = $issue->date_due;
511                         $item->{backgroundcolor} = 'onloan';
512                     }
513
514                     # checking reserve
515                     my $item_object = Koha::Items->find( $itemnumber );
516                     my $holds = $item_object->current_holds;
517                     if ( my $first_hold = $holds->next ) {
518                         my $p = Koha::Patrons->find( $first_hold->borrowernumber );
519
520                         $item->{backgroundcolor} = 'reserved';
521                         $item->{reservedate}     = output_pref({ dt => dt_from_string( $first_hold->reservedate ), dateonly => 1 }); # FIXME Should be formatted in the template
522                         $item->{ReservedFor}     = $p;
523                         $item->{ExpectedAtLibrary}     = $first_hold->branchcode;
524                         $item->{waitingdate} = $first_hold->waitingdate;
525                     }
526
527                     # Management of the notforloan document
528                     if ( $item->{notforloan} ) {
529                         $item->{backgroundcolor} = 'other';
530                     }
531
532                     # Management of lost or long overdue items
533                     if ( $item->{itemlost} ) {
534                         $item->{backgroundcolor} = 'other';
535                         if ($logged_in_patron->category->hidelostitems && !$showallitems) {
536                             $item->{hide} = 1;
537                             $hiddencount++;
538                         }
539                     }
540
541                     # Check the transit status
542                     my ( $transfertwhen, $transfertfrom, $transfertto ) =
543                       GetTransfers($itemnumber);
544
545                     if ( defined $transfertwhen && $transfertwhen ne '' ) {
546                         $item->{transfertwhen} = output_pref({ dt => dt_from_string( $transfertwhen ), dateonly => 1 });
547                         $item->{transfertfrom} = $transfertfrom;
548                         $item->{transfertto} = $transfertto;
549                         $item->{nocancel} = 1;
550                     }
551
552                     # If there is no loan, return and transfer, we show a checkbox.
553                     $item->{notforloan} ||= 0;
554
555                     # if independent branches is on we need to check if the person can reserve
556                     # for branches they arent logged in to
557                     if ( C4::Context->preference("IndependentBranches") ) {
558                         if (! C4::Context->preference("canreservefromotherbranches")){
559                             # can't reserve items so need to check if item homebranch and userenv branch match if not we can't reserve
560                             my $userenv = C4::Context->userenv;
561                             unless ( C4::Context->IsSuperLibrarian ) {
562                                 $item->{cantreserve} = 1 if ( $item->{homebranch} ne $userenv->{branch} );
563                             }
564                         }
565                     }
566
567                     if ( $patron ) {
568                         my $patron_unblessed = $patron->unblessed;
569                         my $branch = C4::Circulation::_GetCircControlBranch($item, $patron_unblessed);
570
571                         my $branchitemrule = GetBranchItemRule( $branch, $item->{'itype'} );
572
573                         $item->{'holdallowed'} = $branchitemrule->{'holdallowed'};
574
575                         my $can_item_be_reserved = CanItemBeReserved( $patron, $item_object )->{status};
576                         $item->{not_holdable} = $can_item_be_reserved unless ( $can_item_be_reserved eq 'OK' );
577
578                         $item->{item_level_holds} = Koha::CirculationRules->get_opacitemholds_policy( { item => $item_object, patron => $patron } );
579
580                         if (
581                                !$item->{cantreserve}
582                             && !$exceeded_maxreserves
583                             && $can_item_be_reserved eq 'OK'
584                             # items_any_available defined outside of the current loop,
585                             # so we avoiding loop inside IsAvailableForItemLevelRequest:
586                             && IsAvailableForItemLevelRequest($item_object, $patron, undef, $items_any_available)
587                           )
588                         {
589                             # Send the pickup locations count to the UI, the pickup locations will be pulled using the API
590                             my @pickup_locations = $item_object->pickup_locations({ patron => $patron })->as_list;
591                             $item->{pickup_locations_count} = scalar @pickup_locations;
592
593                             if ( @pickup_locations ) {
594                                 $num_available++;
595                                 $item->{available} = 1;
596
597                                 my $default_pickup_location;
598
599                                 # Default to logged-in, if valid
600                                 if ( C4::Context->userenv->{branch} ) {
601                                     ($default_pickup_location) = grep { $_->branchcode eq C4::Context->userenv->{branch} } @pickup_locations;
602                                 }
603
604                                 $item->{default_pickup_location} = $default_pickup_location;
605                             }
606                             else {
607                                 $item->{available} = 0;
608                                 $item->{not_holdable} = "no_valid_pickup_location";
609                             }
610
611                             push( @available_itemtypes, $item->{itype} );
612                         }
613                         elsif ( C4::Context->preference('AllowHoldPolicyOverride') ) {
614                             # If AllowHoldPolicyOverride is set, it should override EVERY restriction, not just branch item rules
615                             # with the exception of itemAlreadyOnHold because, you know, the item is already on hold
616                             if ( $can_item_be_reserved ne 'itemAlreadyOnHold' ) {
617                                 # Send the pickup locations count to the UI, the pickup locations will be pulled using the API
618                                 my $pickup_locations = $item_object->pickup_locations({ patron => $patron });
619                                 $item->{pickup_locations_count} = $pickup_locations->count;
620                                 if ( $item->{pickup_locations_count} > 0 ) {
621                                     $item->{override} = 1;
622                                     $num_override++;
623                                     # pass the holding branch for use as default
624                                     my $default_pickup_location = $pickup_locations->search({ branchcode => $item->{holdingbranch} })->next;
625                                     $item->{default_pickup_location} = $default_pickup_location;
626                                 }
627                                 else {
628                                     $item->{available} = 0;
629                                     $item->{not_holdable} = "no_valid_pickup_location";
630                                 }
631                             } else { $num_alreadyheld++ }
632
633                             push( @available_itemtypes, $item->{itype} );
634                         }
635
636                         # If none of the conditions hold true, then neither override nor available is set and the item cannot be checked
637
638                         # Show serial enumeration when needed
639                         if ($item->{enumchron}) {
640                             $itemdata_enumchron = 1;
641                         }
642                         # Show collection when needed
643                         if ($item->{ccode}) {
644                             $itemdata_ccode = 1;
645                         }
646                     }
647
648                     push @{ $biblioitem->{itemloop} }, $item;
649                 }
650
651                 # While we can't override an alreay held item, we should be able to override the others
652                 # Unless all items are already held
653                 if ( $num_override > 0 && ($num_override + $num_alreadyheld) == scalar( @{ $biblioitem->{itemloop} } ) ) {
654                 # That is, if all items require an override
655                     $template->param( override_required => 1 );
656                 } elsif ( $num_available == 0 ) {
657                     $template->param( none_available => 1 );
658                     $biblioloopiter{warn} = 1;
659                     $biblioloopiter{none_avail} = 1;
660                 }
661                 $template->param( hiddencount => $hiddencount);
662
663                 push @bibitemloop, $biblioitem;
664             }
665
666             @available_itemtypes = uniq( @available_itemtypes );
667             $template->param(
668                 bibitemloop         => \@bibitemloop,
669                 available_itemtypes => \@available_itemtypes
670             );
671         }
672
673         # existingreserves building
674         my @reserveloop;
675         my $always_show_holds = $input->cookie('always_show_holds');
676         $template->param( always_show_holds => $always_show_holds );
677         my $show_holds_now = $input->param('show_holds_now');
678         unless( (defined $always_show_holds && $always_show_holds eq 'DONT') && !$show_holds_now ){
679             my @reserves = Koha::Holds->search( { biblionumber => $biblionumber }, { order_by => 'priority' } )->as_list;
680             foreach my $res (
681                 sort {
682                     my $a_found = $a->found() || '';
683                     my $b_found = $a->found() || '';
684                     $a_found cmp $b_found;
685                 } @reserves
686               )
687             {
688                 my %reserve;
689                 if ( $res->is_found() ) {
690                     $reserve{'holdingbranch'} = $res->item()->holdingbranch();
691                     $reserve{'biblionumber'}  = $res->item()->biblionumber();
692                     $reserve{'barcodenumber'} = $res->item()->barcode();
693                     $reserve{'wbrcode'}       = $res->branchcode();
694                     $reserve{'itemnumber'}    = $res->itemnumber();
695                     $reserve{'wbrname'}       = $res->branch()->branchname();
696                     $reserve{'atdestination'} = $res->is_at_destination();
697                     $reserve{'desk_name'}     = ( $res->desk() ) ? $res->desk()->desk_name() : '' ;
698                     $reserve{'found'}     = $res->is_found();
699                     $reserve{'inprocessing'} = $res->is_in_processing();
700                     $reserve{'intransit'} = $res->is_in_transit();
701                 }
702                 elsif ( $res->priority() > 0 ) {
703                     if ( my $item = $res->item() )  {
704                         $reserve{'itemnumber'}      = $item->id();
705                         $reserve{'barcodenumber'}   = $item->barcode();
706                         $reserve{'item_level_hold'} = 1;
707                     }
708                 }
709
710                 $reserve{'expirationdate'} = $res->expirationdate;
711                 $reserve{'date'}           = $res->reservedate;
712                 $reserve{'borrowernumber'} = $res->borrowernumber();
713                 $reserve{'biblionumber'}   = $res->biblionumber();
714                 $reserve{'patron'}         = $res->borrower;
715                 $reserve{'notes'}          = $res->reservenotes();
716                 $reserve{'waiting_date'}   = $res->waitingdate();
717                 $reserve{'ccode'}          = $res->item() ? $res->item()->ccode() : undef;
718                 $reserve{'barcode'}        = $res->item() ? $res->item()->barcode() : undef;
719                 $reserve{'priority'}       = $res->priority();
720                 $reserve{'lowestPriority'} = $res->lowestPriority();
721                 $reserve{'suspend'}        = $res->suspend();
722                 $reserve{'suspend_until'}  = $res->suspend_until();
723                 $reserve{'reserve_id'}     = $res->reserve_id();
724                 $reserve{itemtype}         = $res->itemtype();
725                 $reserve{branchcode}       = $res->branchcode();
726                 $reserve{non_priority}     = $res->non_priority();
727                 $reserve{object}           = $res;
728
729                 push( @reserveloop, \%reserve );
730             }
731         }
732
733         # get the time for the form name...
734         my $time = time();
735
736         $template->param(
737                          time        => $time,
738                          fixedRank   => $fixedRank,
739                         );
740
741         # display infos
742         $template->param(
743                          itemdata_enumchron => $itemdata_enumchron,
744                          itemdata_ccode    => $itemdata_ccode,
745                          date              => $date,
746                          biblionumber      => $biblionumber,
747                          findborrower      => $findborrower,
748                          biblio            => $biblio,
749                          holdsview         => 1,
750                          C4::Search::enabled_staff_search_views,
751                         );
752
753         $biblioloopiter{biblionumber} = $biblionumber;
754         $biblioloopiter{title}  = $biblio->title;
755         $biblioloopiter{author} = $biblio->author;
756         $biblioloopiter{rank} = $fixedRank;
757         $biblioloopiter{reserveloop} = \@reserveloop;
758
759         if (@reserveloop) {
760             $template->param( reserveloop => \@reserveloop );
761         }
762
763         if ( $patron ) {
764             # Add the valid pickup locations
765             my @pickup_locations = $biblio->pickup_locations({ patron => $patron })->as_list;
766             $biblioloopiter{pickup_locations} = \@pickup_locations;
767             $biblioloopiter{pickup_locations_codes} = [ map { $_->branchcode } @pickup_locations ];
768         }
769
770         push @biblioloop, \%biblioloopiter;
771     }
772
773     $template->param( biblioloop => \@biblioloop );
774     $template->param( no_reserves_allowed => $no_reserves_allowed );
775     $template->param( exceeded_maxreserves => $exceeded_maxreserves );
776     $template->param( exceeded_holds_per_record => $exceeded_holds_per_record );
777     $template->param( subscriptionsnumber => CountSubscriptionFromBiblionumber($biblionumber));
778 } elsif ( ! $multi_hold ) {
779     my $biblio = Koha::Biblios->find( $biblionumber );
780     $template->param( biblio => $biblio );
781 }
782
783 if ( $multi_hold ) {
784     $template->param( biblionumbers => join('/', @biblionumbers) );
785 } else {
786     $template->param( biblionumber => $biblionumber || $biblionumbers[0] );
787 }
788
789 # pass the userenv branch if no pickup location selected
790 $template->param( pickup => $pickup || C4::Context->userenv->{branch} );
791
792 if ( C4::Context->preference( 'AllowHoldDateInFuture' ) ) {
793     $template->param( reserve_in_future => 1 );
794 }
795
796 $template->param(
797     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
798     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
799 );
800
801 # printout the page
802 output_html_with_http_headers $input, $cookie, $template->output;
803
804 sub sort_borrowerlist {
805     my $borrowerslist = shift;
806     my $ref           = [];
807     push @{$ref}, sort {
808         uc( $a->{surname} . $a->{firstname} ) cmp
809           uc( $b->{surname} . $b->{firstname} )
810     } @{$borrowerslist};
811     return $ref;
812 }