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