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