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