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