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