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