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