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