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