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