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