Bug 34972: (QA follow-up) Remove some ModReserveCancelAll imports
[koha.git] / circ / returns.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #           2006 SAN-OP
5 #           2007-2010 BibLibre, Paul POULAIN
6 #           2010 Catalyst IT
7 #           2011 PTFS-Europe Ltd.
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it
12 # under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # Koha is distributed in the hope that it will be useful, but
17 # WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23
24 =head1 returns.pl
25
26 script to execute returns of books
27
28 =cut
29
30 use Modern::Perl;
31
32 # FIXME There are weird things going on with $patron and $borrowernumber in this script
33
34 use CGI qw ( -utf8 );
35 use DateTime;
36
37 use C4::Auth qw( get_template_and_user get_session haspermission );
38 use C4::Circulation qw( barcodedecode GetBranchItemRule AddReturn updateWrongTransfer LostItem );
39 use C4::Context;
40 use C4::Items qw( ModItemTransfer );
41 use C4::Members::Messaging;
42 use C4::Members;
43 use C4::Output qw( output_html_with_http_headers );
44 use C4::Reserves qw( ModReserve ModReserveAffect CheckReserves );
45 use C4::RotatingCollections;
46 use Koha::AuthorisedValues;
47 use Koha::BiblioFrameworks;
48 use Koha::Calendar;
49 use Koha::Checkouts;
50 use Koha::CirculationRules;
51 use Koha::DateUtils qw( dt_from_string );
52 use Koha::Holds;
53 use Koha::Item::Transfers;
54 use Koha::Items;
55 use Koha::Patrons;
56 use Koha::Recalls;
57
58 my $query = CGI->new;
59
60 #getting the template
61 my ( $template, $librarian, $cookie, $flags ) = get_template_and_user(
62     {
63         template_name   => "circ/returns.tt",
64         query           => $query,
65         type            => "intranet",
66         flagsrequired   => { circulate => "circulate_remaining_permissions" },
67     }
68 );
69
70 my $sessionID = $query->cookie("CGISESSID");
71 my $session = get_session($sessionID);
72 my $desk_id = C4::Context->userenv->{"desk_id"} || '';
73
74 # Print a reserve slip on this page
75 if ( $query->param('print_slip') ) {
76     $template->param(
77         print_slip     => 1,
78         reserve_id => scalar $query->param('reserve_id'),
79     );
80 }
81
82 # print a recall slip
83 if ( $query->param('recall_slip') ) {
84     $template->param(
85         recall_slip => 1,
86         recall_id => scalar $query->param('recall_id'),
87     );
88 }
89
90
91 #####################
92 #Global vars
93 my $userenv = C4::Context->userenv;
94 my $userenv_branch = $userenv->{'branch'} // '';
95 my $forgivemanualholdsexpire = $query->param('forgivemanualholdsexpire');
96
97 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') eq 'production');
98
99 #set up so only the last 8 returned items display (make for faster loading pages)
100 my $returned_counter = C4::Context->preference('numReturnedItemsToShow') || 8;
101
102 # Set up the item stack ....
103 my %returneditems;
104 my %riduedate;
105 my %riborrowernumber;
106 my @inputloop;
107 foreach ( $query->param ) {
108     my $counter;
109     if (/ri-(\d*)/) {
110         $counter = $1;
111         if ($counter > $returned_counter) {
112             next;
113         }
114     }
115     else {
116         next;
117     }
118
119     my %input;
120     my $barcode        = $query->param("ri-$counter");
121     my $duedate        = $query->param("dd-$counter");
122     my $borrowernumber = $query->param("bn-$counter");
123     $counter++;
124
125     # decode barcode    ## Didn't we already decode them before passing them back last time??
126     $barcode = barcodedecode($barcode) if $barcode;
127
128     ######################
129     #Are these lines still useful ?
130     $returneditems{$counter}    = $barcode;
131     $riduedate{$counter}        = $duedate;
132     $riborrowernumber{$counter} = $borrowernumber;
133
134     #######################
135     $input{counter}        = $counter;
136     $input{barcode}        = $barcode;
137     $input{duedate}        = $duedate;
138     $input{borrowernumber} = $borrowernumber;
139     push( @inputloop, \%input );
140 }
141
142 my $op          = $query->param('op');
143
144 ############
145 # Deal with the requests....
146 my $itemnumber = $query->param('itemnumber');
147 if ( $query->param('reserve_id') && $op eq 'cud-affect_reserve') {
148     my $borrowernumber = $query->param('borrowernumber');
149     my $reserve_id     = $query->param('reserve_id');
150     my $diffBranchReturned = $query->param('diffBranch');
151     my $cancel_reserve = $query->param('cancel_reserve');
152     my $cancel_reason = $query->param('cancel_reason');
153
154     # fix up item type for display
155     my $item = Koha::Items->find( $itemnumber );
156     my $biblio = $item->biblio;
157
158     if ( $cancel_reserve ) {
159         my $hold = Koha::Holds->find( $reserve_id );
160         if ( $hold ) {
161             $hold->cancel( { charge_cancel_fee => !$forgivemanualholdsexpire, cancellation_reason => $cancel_reason} );
162         } # FIXME else?
163     } else {
164         my $diffBranchSend = ($userenv_branch ne $diffBranchReturned) ? $diffBranchReturned : undef;
165
166         # diffBranchSend tells ModReserveAffect whether document is expected in this library or not,
167         # i.e., whether to apply waiting status
168         ModReserveAffect( $itemnumber, $borrowernumber, $diffBranchSend, $reserve_id, $desk_id );
169
170         if ($diffBranchSend) {
171             ModItemTransfer( $itemnumber, $userenv_branch, $diffBranchSend, 'Reserve' );
172         }
173     }
174     # check if we have other reserves for this document, if we have a result send the message of transfer
175     # FIXME do we need to do this if we didn't take the cancel_reserve branch above?
176     my ( undef, $nextreservinfo, undef ) = CheckReserves($item);
177
178     my $patron = Koha::Patrons->find( $nextreservinfo->{'borrowernumber'} );
179     if ( $userenv_branch ne $nextreservinfo->{'branchcode'} ) {
180         $template->param(
181             itemtitle      => $biblio->title,
182             itembiblionumber => $biblio->biblionumber,
183             iteminfo       => $biblio->author,
184             patron         => $patron,
185             diffbranch     => 1,
186         );
187     }
188 }
189
190 if ( $query->param('recall_id') && $op eq 'cud-affect_recall' ) {
191     my $recall = Koha::Recalls->find( scalar $query->param('recall_id') );
192     my $itemnumber = $query->param('itemnumber');
193     my $return_branch = $query->param('returnbranch');
194
195     if ($recall) {
196         my $item;
197         if ( !$recall->item_level ) {
198             $item = Koha::Items->find( $itemnumber );
199         }
200
201         if ( $recall->pickup_library_id ne $return_branch ) {
202             $recall->start_transfer({ item => $item }) if !$recall->in_transit;
203         } else {
204             my $expirationdate = $recall->calc_expirationdate;
205             $recall->set_waiting({ item => $item, expirationdate => $expirationdate }) if !$recall->waiting;
206         }
207     }
208 }
209
210 my $borrower;
211 my $returned = 0;
212 my $messages;
213 my $issue;
214 my $barcode     = $query->param('barcode');
215 my $exemptfine  = $query->param('exemptfine');
216 if (
217   $exemptfine &&
218   !C4::Auth::haspermission(C4::Context->userenv->{'id'}, {'updatecharges' => 'writeoff'})
219 ) {
220     # silently prevent unauthorized operator from forgiving overdue
221     # fines by manually tweaking form parameters
222     undef $exemptfine;
223 }
224 my $dropboxmode = $query->param('dropboxmode');
225 my $canceltransfer = $query->param('canceltransfer');
226 my $transit = $query->param('transit');
227 my $dest = $query->param('dest');
228 #dropbox: get last open day (today - 1)
229 my $dropboxdate = Koha::Checkouts::calculate_dropbox_date();
230
231 my $return_date_override = $query->param('return_date_override') || q{};
232 if ($return_date_override) {
233     if ( C4::Context->preference('SpecifyReturnDate') ) {
234
235         # note that we've overriden the return date
236         $template->param( return_date_was_overriden => 1 );
237
238         my $return_date_override_remember =
239           $query->param('return_date_override_remember');
240
241         # Save the original format if we are remembering for this series
242         $template->param(
243             return_date_override          => $return_date_override,
244             return_date_override_remember => 1
245         ) if ($return_date_override_remember);
246     }
247 }
248
249 if ( $op eq 'cud-dotransfer'){
250 # An item has been returned to a branch other than the homebranch, and the librarian has chosen to initiate a transfer
251     my $transferitem = $query->param('transferitem');
252     my $tobranch     = $query->param('tobranch');
253     my $trigger      = $query->param('trigger');
254     ModItemTransfer($transferitem, $userenv_branch, $tobranch, $trigger);
255 }
256
257 if ($transit && $op eq 'cud-transfer') {
258     my $transfer = Koha::Item::Transfers->find($transit);
259     if ( $canceltransfer ) {
260         $transfer->cancel({ reason => 'Manual', force => 1});
261         if ( C4::Context->preference('UseRecalls') ) {
262             my $recall_transfer_deleted = Koha::Recalls->find({ item_id => $itemnumber, status => 'in_transit' });
263             if ( defined $recall_transfer_deleted ) {
264                 $recall_transfer_deleted->revert_transfer;
265             }
266         }
267         $template->param( transfercancelled => 1);
268     } else {
269         $transfer->transit;
270     }
271 } elsif ($canceltransfer){
272     my $item = Koha::Items->find($itemnumber);
273     my $transfer = $item->get_transfer;
274     $transfer->cancel({ reason => 'Manual', force => 1});
275     if ( C4::Context->preference('UseRecalls') ) {
276         my $recall_transfer_deleted = Koha::Recalls->find({ item_id => $itemnumber, status => 'in_transit' });
277         if ( defined $recall_transfer_deleted ) {
278             $recall_transfer_deleted->revert_transfer;
279         }
280     }
281     if($dest eq "ttr"){
282         print $query->redirect("/cgi-bin/koha/circ/transferstoreceive.pl");
283         exit;
284     } else {
285         $template->param( transfercancelled => 1);
286     }
287 }
288
289
290 # actually return book and prepare item table.....
291 my $returnbranch;
292 if ($barcode && $op eq 'cud-checkin') {
293     $barcode = barcodedecode($barcode) if $barcode;
294     my $item = Koha::Items->find({ barcode => $barcode });
295
296     if ( $item ) {
297         $itemnumber = $item->itemnumber;
298         # Check if we should display a checkin message, based on the the item
299         # type of the checked in item
300         my $itemtype = Koha::ItemTypes->find( $item->effective_itemtype );
301         if ( $itemtype && $itemtype->checkinmsg ) {
302             $template->param(
303                 checkinmsg     => $itemtype->checkinmsg,
304                 checkinmsgtype => $itemtype->checkinmsgtype,
305             );
306         }
307
308         # make sure return branch respects home branch circulation rules, default to homebranch
309         my $hbr = Koha::CirculationRules->get_return_branch_policy($item);
310         my $validate_float =
311             Koha::Libraries->find( $item->homebranch )->validate_float_sibling( { branchcode => $userenv_branch } );
312
313         # get the proper branch to which to return the item
314         # if library isn't in same the float group, transfer item to homelibrary
315         $returnbranch =
316               $hbr eq 'noreturn'
317             ? $userenv_branch
318             : $hbr eq 'returnbylibrarygroup' ? $validate_float
319                 ? $userenv_branch
320                 : $item->homebranch
321             : $item->$hbr;
322         my $materials = $item->materials;
323         my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield =>'items.materials', authorised_value => $materials });
324         $materials = $descriptions->{lib} // $materials;
325
326         my $checkout = $item->checkout;
327         my $biblio   = $item->biblio;
328         $template->param(
329             title                => $biblio->title,
330             returnbranch         => $returnbranch,
331             author               => $biblio->author,
332             itembiblionumber     => $biblio->biblionumber,
333             biblionumber         => $biblio->biblionumber,
334             additional_materials => $materials,
335             issue                => $checkout,
336             item                 => $item,
337         );
338     } # FIXME else we should not call AddReturn but set BadBarcode directly instead
339
340     my %input = (
341         counter => 0,
342         first   => 1,
343         barcode => $barcode,
344     );
345
346     my $return_date =
347         $dropboxmode
348       ? $dropboxdate
349       : dt_from_string( $return_date_override );
350
351     # Block return if multi-part and confirm has not been received
352     my $needs_confirm =
353          C4::Context->preference("CircConfirmItemParts")
354       && $item
355       && $item->materials
356       && !$query->param('multiple_confirm');
357     $template->param( 'multiple_confirmed' => 1 )
358       if $query->param('multiple_confirm');
359
360     # Block return if bundle and confirm has not been received
361     my $bundle_confirm =
362          $item
363       && $item->is_bundle
364       && !$query->param('confirm_items_bundle_return');
365     $template->param( 'confirm_items_bundle_returned' => 1 )
366       if $query->param('confirm_items_bundle_return');
367
368     # is there a waiting hold for the item, for which cancellation
369     # has been requested?
370     if ($item) {
371         my $waiting_holds_to_be_cancelled = $item->holds->waiting->filter_by_has_cancellation_requests;
372         while ( my $hold = $waiting_holds_to_be_cancelled->next ) {
373             $hold->cancel;
374         }
375     }
376
377     # do the return
378     ( $returned, $messages, $issue, $borrower ) =
379       AddReturn( $barcode, $userenv_branch, $exemptfine, $return_date )
380           unless ( $needs_confirm || $bundle_confirm );
381
382     if ($returned) {
383         my $time_now = dt_from_string()->truncate( to => 'minute');
384         my $date_due_dt = dt_from_string( $issue->date_due, 'sql' );
385         my $duedate = $date_due_dt->strftime('%Y-%m-%d %H:%M');
386         $returneditems{0}      = $barcode;
387         $riborrowernumber{0}   = $borrower->{'borrowernumber'};
388         $riduedate{0}          = $duedate;
389         $input{borrowernumber} = $borrower->{'borrowernumber'};
390         $input{duedate}        = $duedate;
391         unless ( $dropboxmode ) {
392             $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, dt_from_string()) == -1);
393         } else {
394             $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, $dropboxdate) == -1);
395         }
396         push( @inputloop, \%input );
397
398         if ( C4::Context->preference("FineNotifyAtCheckin") ) {
399             my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
400             my $balance = $patron->account->balance;
401
402             if ($balance > 0) {
403                 $template->param( fines => sprintf("%.2f", $balance) );
404                 $template->param( fineborrowernumber => $borrower->{'borrowernumber'} );
405             }
406         }
407
408         if (C4::Context->preference("WaitingNotifyAtCheckin") ) {
409             #Check for waiting holds
410             my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
411             my $waiting_holds = $patron->holds->search({ found => 'W', branchcode => $userenv_branch })->count;
412             if ($waiting_holds > 0) {
413                 $template->param(
414                     waiting_holds       => $waiting_holds,
415                     holdsborrowernumber => $borrower->{'borrowernumber'},
416                     holdsfirstname => $borrower->{'firstname'},
417                     holdssurname => $borrower->{'surname'},
418                 );
419             }
420         }
421
422     } elsif ( C4::Context->preference('ShowAllCheckins') and !$messages->{'BadBarcode'} and !$needs_confirm and !$bundle_confirm ) {
423         my $duedate = 0;
424         if ($issue) {
425             my $date_due_dt = dt_from_string( $issue->date_due, 'sql' );
426             $duedate               = $date_due_dt->strftime('%Y-%m-%d %H:%M');
427             $input{borrowernumber} = $issue->borrowernumber;
428             $riborrowernumber{0}   = $borrower->{'borrowernumber'};
429         }
430         $input{duedate}      = $duedate;
431         $input{not_returned} = 1;
432         $returneditems{0}    = $barcode;
433         $riduedate{0}        = $duedate;
434         push( @inputloop, \%input );
435     }
436     $template->param( privacy => $borrower->{privacy} );
437
438     if ( $needs_confirm ) {
439         $template->param( needs_confirm => $needs_confirm );
440     }
441
442     if ( $bundle_confirm ) {
443         $template->param(
444             items_bundle_return_confirmation => 1,
445         );
446     }
447
448     # Mark missing bundle items as lost and report unexpected items
449     if ( $item && $item->is_bundle && $query->param('confirm_items_bundle_return') && !$query->param('do_not_verify_items_bundle_contents') ) {
450         my $BundleLostValue = C4::Context->preference('BundleLostValue');
451         my $barcodes = $query->param('verify-items-bundle-contents-barcodes');
452         my @barcodes = map { s/^\s+|\s+$//gr } ( split /\n/, $barcodes );
453         my $expected_items = { map { $_->barcode => $_ } $item->bundle_items->as_list };
454         my $verify_items = Koha::Items->search( { barcode => { 'in' => \@barcodes } } );
455         my @unexpected_items;
456         my @missing_items;
457         my @bundle_items;
458         while ( my $verify_item = $verify_items->next ) {
459             # Fix and lost statuses
460             $verify_item->itemlost(0);
461
462             # Update last_seen
463             $verify_item->datelastseen( dt_from_string() );
464
465             # Update last_borrowed if actual checkin
466             $verify_item->datelastborrowed( dt_from_string()->ymd() ) if $issue;
467
468             # Expected item, remove from lookup table
469             if ( delete $expected_items->{$verify_item->barcode} ) {
470                 push @bundle_items, $verify_item;
471             }
472             # Unexpected item, warn and remove from bundle
473             else {
474                 $verify_item->remove_from_bundle;
475                 push @unexpected_items, $verify_item;
476             }
477
478             # Store results
479             $verify_item->store();
480         }
481         for my $missing_item ( keys %{$expected_items} ) {
482             my $bundle_item = $expected_items->{$missing_item};
483             # Mark as lost if it's not already lost
484             if ( !$bundle_item->itemlost ) {
485                 $bundle_item->itemlost($BundleLostValue)->store();
486
487                 # Add return_claim record if this is an actual checkin
488                 if ($issue) {
489                     $bundle_item->_result->create_related(
490                         'return_claims',
491                         {
492                             issue_id       => $issue->issue_id,
493                             itemnumber     => $bundle_item->itemnumber,
494                             borrowernumber => $issue->borrowernumber,
495                             created_by     => C4::Context->userenv()->{number},
496                             created_on     => dt_from_string
497                         }
498                     );
499                 }
500                 push @missing_items, $bundle_item;
501
502                 # NOTE: We cannot use C4::LostItem here because the item itself doesn't have a checkout
503                 # and thus would not get charged.. it's checked out as part of the bundle.
504                 if ( C4::Context->preference('WhenLostChargeReplacementFee') && $issue ) {
505                     C4::Accounts::chargelostitem(
506                         $issue->borrowernumber,
507                         $bundle_item->itemnumber,
508                         $bundle_item->replacementprice,
509                         sprintf( "%s %s %s",
510                             $bundle_item->biblio->title  || q{},
511                             $bundle_item->barcode        || q{},
512                             $bundle_item->itemcallnumber || q{},
513                         ),
514                     );
515                 }
516             }
517         }
518         $template->param(
519             unexpected_items => \@unexpected_items,
520             missing_items    => \@missing_items,
521             bundle_items     => \@bundle_items
522         );
523     }
524 }
525 $template->param( inputloop => \@inputloop );
526
527 my $found    = 0;
528 my $waiting  = 0;
529 my $reserved = 0;
530 my $recalled = 0;
531
532 # new op dev : we check if the document must be returned to his homebranch directly,
533 #  if the document is transferred, we have warning message .
534
535 if ( $messages->{'WasTransfered'} ) {
536     $template->param(
537         found          => 1,
538         transfer       => $messages->{'WasTransfered'},
539         trigger        => $messages->{'TransferTrigger'},
540         itemnumber     => $itemnumber,
541     );
542 }
543
544 if ( $messages->{'NeedsTransfer'} ){
545     $template->param(
546         found          => 1,
547         needstransfer  => $messages->{'NeedsTransfer'},
548         trigger        => $messages->{'TransferTrigger'},
549     );
550 }
551
552 if ( $messages->{'Wrongbranch'} ){
553     $template->param(
554         wrongbranch => 1,
555         rightbranch => $messages->{'Wrongbranch'}->{'Rightbranch'},
556     );
557 }
558
559 # case of wrong transfert, if the document wasn't transferred to the right library (according to branchtransfer (tobranch) BDD)
560
561 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
562
563     # Trigger modal to prompt librarian
564     $template->param(
565         WrongTransfer  => 1,
566         TransferWaitingAt => $messages->{'WrongTransfer'},
567         WrongTransferItem => $messages->{'WrongTransferItem'},
568         trigger           => $messages->{'TransferTrigger'},
569     );
570
571     # Update the transfer to reflect the new item holdingbranch
572     my $new_transfer = updateWrongTransfer($messages->{'WrongTransferItem'},$messages->{'WrongTransfer'}, $userenv_branch);
573     $template->param(
574         NewTransfer => $new_transfer->id
575     );
576
577     my $reserve    = $messages->{'ResFound'};
578     if ( $reserve ) {
579         my $patron = Koha::Patrons->find( $reserve->{'borrowernumber'} );
580         $template->param(
581             patron => $patron,
582         );
583     }
584 }
585
586 #
587 # reserve found and item arrived at the expected branch
588 #
589 if ( $messages->{'ResFound'} ) {
590     my $reserve    = $messages->{'ResFound'};
591     my $patron = Koha::Patrons->find( $reserve->{borrowernumber} );
592     my $holdmsgpreferences =  C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $reserve->{'borrowernumber'}, message_name   => 'Hold_Filled' } );
593     my $branchCheck = ( $userenv_branch eq $reserve->{branchcode} );
594     if ( $reserve->{'ResFound'} eq "Waiting" ) {
595         $template->param(
596             waiting      => $branchCheck ? 1 : undef,
597         );
598     } elsif ( C4::Context->preference('HoldsAutoFill') ) {
599         my $item = Koha::Items->find( $itemnumber );
600         my $biblio = $item->biblio;
601
602         my $diffBranchSend = !$branchCheck ? $reserve->{branchcode} : undef;
603         ModReserveAffect( $itemnumber, $reserve->{borrowernumber}, $diffBranchSend, $reserve->{reserve_id}, $desk_id );
604
605         if ($diffBranchSend) {
606             ModItemTransfer( $itemnumber, $item->holdingbranch, $reserve->{branchcode}, 'Reserve' );
607         }
608
609         $template->param(
610             hold_auto_filled => 1,
611             print_slip       => C4::Context->preference('HoldsAutoFillPrintSlip'),
612             reserve_id       => $reserve->{reserve_id},
613         );
614
615         if ($diffBranchSend) {
616             $template->param(
617                 itemtitle        => $biblio->title,
618                 itembiblionumber => $biblio->biblionumber,
619                 iteminfo         => $biblio->author,
620                 diffbranch       => 1,
621             );
622         }
623     } else {
624         $template->param(
625             intransit    => $branchCheck ? undef : 1,
626             transfertodo => $branchCheck ? undef : 1,
627             reserve_id   => $reserve->{reserve_id},
628             reserved     => 1,
629         );
630     }
631
632     # same params for Waiting or Reserved
633     $template->param(
634         found          => 1,
635         patron         => $patron,
636         barcode        => $barcode,
637         destbranch     => $reserve->{'branchcode'},
638         reservenotes   => $reserve->{'reservenotes'},
639         reserve_id     => $reserve->{reserve_id},
640         bormessagepref => $holdmsgpreferences->{'transports'},
641     );
642 }
643
644 if ( $messages->{RecallFound} ) {
645     my $recall = $messages->{RecallFound};
646     if ( dt_from_string( $recall->timestamp ) == dt_from_string ) {
647         # we just updated this recall
648         $template->param( recall => $recall );
649     } else {
650         my $transferbranch = $messages->{RecallNeedsTransfer};
651         my $transfertodo = ( !$transferbranch or $transferbranch eq $recall->library->branchcode ) ? undef : 1;
652         $template->param(
653             found => 1,
654             recall => $recall,
655             recalled => $recall->waiting ? 0 : 1,
656             transfertodo => $transfertodo,
657             waitingrecall => $recall->waiting ? 1 : 0,
658         );
659     }
660 }
661
662 if ( $messages->{TransferredRecall} ) {
663     my $recall = $messages->{TransferredRecall};
664
665     # confirm transfer has arrived at the branch
666     my $transfer = Koha::Item::Transfers->search({ datearrived => { '!=' => undef }, itemnumber => $recall->item_id }, { order_by => { -desc => 'datearrived' } })->next;
667
668     # if transfer has completed, show popup to confirm as waiting
669     if ( defined $transfer and $transfer->tobranch eq $recall->pickup_library_id ) {
670         $template->param(
671             found => 1,
672             recall => $recall,
673             recalled => 1,
674         );
675     }
676 }
677
678 # Error Messages
679 my @errmsgloop;
680 foreach my $code ( keys %$messages ) {
681     my %err;
682     if ( $code eq 'BadBarcode' ) {
683         $err{badbarcode} = 1;
684         $err{msg}        = $messages->{'BadBarcode'};
685     }
686     elsif ( $code eq 'NotIssued' ) {
687         $err{notissued} = 1;
688         $err{msg} = '';
689     }
690     elsif ( $code eq 'LocalUse' ) {
691         $err{localuse} = 1;
692     }
693     elsif ( $code eq 'WasLost' ) {
694         $err{waslost} = 1;
695     }
696     elsif ( $code eq 'LostItemFeeRefunded' ) {
697         $template->param( LostItemFeeRefunded => 1 );
698     }
699     elsif ( $code eq 'LostItemFeeCharged' ) {
700         $template->param( LostItemFeeCharged => 1 );
701     }
702     elsif ( $code eq 'LostItemFeeRestored' ) {
703         $template->param( LostItemFeeRestored => 1 );
704     }
705     elsif ( $code eq 'ProcessingFeeRefunded' ) {
706         $template->param( ProcessingFeeRefunded => 1 );
707     }
708     elsif ( $code eq 'ResFound' ) {
709         ;    # FIXME... anything to do here?
710     }
711     elsif ( $code eq 'WasReturned' ) {
712         ;    # FIXME... anything to do here?
713     }
714     elsif ( $code eq 'WasTransfered' ) {
715         ;    # FIXME... anything to do here?
716     }
717     elsif ( $code eq 'withdrawn' ) {
718         $err{withdrawn} = 1;
719     }
720     elsif ( $code eq 'WrongTransfer' ) {
721         ;    # FIXME... anything to do here?
722     }
723     elsif ( $code eq 'WrongTransferItem' ) {
724         ;    # FIXME... anything to do here?
725     }
726     elsif ( $code eq 'NeedsTransfer' ) {
727     }
728     elsif ( $code eq 'TransferTrigger' ) {
729         ;    # Handled alongside NeedsTransfer
730     }
731     elsif ( $code eq 'TransferArrived' ) {
732         $err{transferred} = $messages->{'TransferArrived'};
733     }
734     elsif ( $code eq 'Wrongbranch' ) {
735     }
736     elsif ( $code eq 'Debarred' ) {
737         $err{debarred}            = $messages->{'Debarred'};
738         $err{debarcardnumber}     = $borrower->{cardnumber};
739         $err{debarborrowernumber} = $borrower->{borrowernumber};
740         $err{debarname}           = "$borrower->{firstname} $borrower->{surname}";
741     }
742     elsif ( $code eq 'PrevDebarred' ) {
743         $err{prevdebarred}        = $messages->{'PrevDebarred'};
744     }
745     elsif ( $code eq 'ForeverDebarred' ) {
746         $err{foreverdebarred}        = $messages->{'ForeverDebarred'};
747     }
748     elsif ( $code eq 'ItemLocationUpdated' ) {
749         $err{ItemLocationUpdated} = $messages->{ItemLocationUpdated};
750     }
751     elsif ( $code eq 'NotForLoanStatusUpdated' ) {
752         $err{NotForLoanStatusUpdated} = $messages->{NotForLoanStatusUpdated};
753     }
754     elsif ( $code eq 'DataCorrupted' ) {
755         $err{data_corrupted} = 1;
756     }
757     elsif ( $code eq 'ReturnClaims' ) {
758         $template->param( ReturnClaims => $messages->{ReturnClaims} );
759     }
760       elsif ( $code eq 'ClaimAutoResolved' ) {
761           $template->param( ClaimAutoResolved => $messages->{ClaimAutoResolved} );
762     } elsif ( $code eq 'RecallFound' ) {
763         ;
764     } elsif ( $code eq 'RecallNeedsTransfer' ) {
765         ;
766     } elsif ( $code eq 'TransferredRecall' ) {
767         ;
768     } elsif ( $code eq 'InBundle' ) {
769         $template->param( InBundle => $messages->{InBundle} );
770     } else {
771         die "Unknown error code $code";    # note we need all the (empty) elsif's above, or we die.
772         # This forces the issue of staying in sync w/ Circulation.pm
773     }
774     if (%err) {
775         push( @errmsgloop, \%err );
776     }
777 }
778 $template->param( errmsgloop => \@errmsgloop );
779
780 my $count = 0;
781 my @riloop;
782 my $shelflocations =
783   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
784 foreach ( sort { $a <=> $b } keys %returneditems ) {
785     my %ri;
786     if ( $count++ < $returned_counter ) {
787         my $bar_code = $returneditems{$_};
788         if ($riduedate{$_}) {
789             my $duedate = dt_from_string( $riduedate{$_}, 'sql');
790             $ri{year}  = $duedate->year();
791             $ri{month} = $duedate->month();
792             $ri{day}   = $duedate->day();
793             $ri{hour}   = $duedate->hour();
794             $ri{minute}   = $duedate->minute();
795             $ri{duedate} = $duedate;
796             my $patron = Koha::Patrons->find( $riborrowernumber{$_} );
797             unless ( $dropboxmode ) {
798                 $ri{return_overdue} = 1 if (DateTime->compare($duedate, dt_from_string()) == -1);
799             } else {
800                 $ri{return_overdue} = 1 if (DateTime->compare($duedate, $dropboxdate) == -1);
801             }
802             $ri{patron} = $patron,
803             $ri{borissuescount} = $patron->checkouts->count;
804         }
805         else {
806             $ri{borrowernumber} = $riborrowernumber{$_};
807         }
808
809         my $item = Koha::Items->find({ barcode => $bar_code });
810         next unless $item; # FIXME The item has been deleted in the meantime,
811                            # we could handle that better displaying a message in the template
812
813
814         $ri{not_returned} = 1 unless $returned;
815         my $biblio = $item->biblio;
816         # FIXME pass $item to the template and we are done here...
817         $ri{itembiblionumber}    = $biblio->biblionumber;
818         $ri{itemtitle}           = $biblio->title;
819         $ri{subtitle}            = $biblio->subtitle;
820         $ri{part_name}           = $biblio->part_name;
821         $ri{part_number}         = $biblio->part_number;
822         $ri{itemauthor}          = $biblio->author;
823         $ri{itemcallnumber}      = $item->itemcallnumber;
824         $ri{dateaccessioned}     = $item->dateaccessioned;
825         $ri{recordtype}          = $biblio->itemtype;
826         $ri{itemtype}            = $item->itype;
827         $ri{itemnote}            = $item->itemnotes;
828         $ri{itemnotes_nonpublic} = $item->itemnotes_nonpublic;
829         $ri{ccode}               = $item->ccode;
830         $ri{enumchron}           = $item->enumchron;
831         $ri{itemnumber}          = $item->itemnumber;
832         $ri{barcode}             = $bar_code;
833         $ri{homebranch}          = $item->homebranch;
834         $ri{transferbranch}      = $item->get_transfer ? $item->get_transfer->tobranch : '';
835         $ri{damaged}             = $item->damaged;
836         $ri{withdrawn}           = $item->withdrawn;
837         $ri{transferreason}      = $item->get_transfer ? $item->get_transfer->reason : '';
838
839         $ri{location} = $item->location;
840         my $shelfcode = $ri{'location'};
841         $ri{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
842
843     }
844     else {
845         last;
846     }
847     push @riloop, \%ri;
848 }
849
850 $template->param(
851     riloop         => \@riloop,
852     errmsgloop     => \@errmsgloop,
853     exemptfine     => $exemptfine,
854     dropboxmode    => $dropboxmode,
855     dropboxdate    => $dropboxdate,
856     forgivemanualholdsexpire => $forgivemanualholdsexpire,
857     overduecharges => $overduecharges,
858     AudioAlerts        => C4::Context->preference("AudioAlerts"),
859 );
860
861 if ( $barcode ) {
862     my $item_from_barcode = Koha::Items->find({barcode => $barcode }); # How many times do we fetch this item?!?
863     if ( $item_from_barcode ) {
864         $itemnumber = $item_from_barcode->itemnumber;
865         my ( $holdingBranch, $collectionBranch ) = GetCollectionItemBranches( $itemnumber );
866         if ( $holdingBranch and $collectionBranch ) {
867             $holdingBranch //= '';
868             $collectionBranch //= $returnbranch;
869             if ( ! ( $holdingBranch eq $collectionBranch ) ) {
870                 $template->param(
871                   collectionItemNeedsTransferred => 1,
872                   collectionBranch => $collectionBranch,
873                 );
874             }
875         }
876     }
877 }
878
879 $template->param( itemnumber => $itemnumber );
880
881 # Checking if there is a Fast Cataloging Framework
882 $template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' );
883
884 # actually print the page!
885 output_html_with_http_headers $query, $cookie, $template->output;