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