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