3 # Copyright 2000-2002 Katipo Communications
5 # 2007-2010 BibLibre, Paul POULAIN
7 # 2011 PTFS-Europe Ltd.
9 # This file is part of Koha.
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.
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.
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>.
26 script to execute returns of books
32 # FIXME There are weird things going on with $patron and $borrowernumber in this script
37 use C4::Auth qw( get_template_and_user get_session haspermission );
38 use C4::Circulation qw( barcodedecode GetBranchItemRule AddReturn updateWrongTransfer LostItem );
40 use C4::Items qw( ModItemTransfer );
41 use C4::Members::Messaging;
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;
50 use Koha::DateUtils qw( dt_from_string output_pref );
53 use Koha::Item::Transfers;
60 my ( $template, $librarian, $cookie, $flags ) = get_template_and_user(
62 template_name => "circ/returns.tt",
65 flagsrequired => { circulate => "circulate_remaining_permissions" },
69 my $sessionID = $query->cookie("CGISESSID");
70 my $session = get_session($sessionID);
71 my $desk_id = C4::Context->userenv->{"desk_id"} || '';
73 # Print a reserve slip on this page
74 if ( $query->param('print_slip') ) {
77 reserve_id => scalar $query->param('reserve_id'),
82 if ( $query->param('recall_slip') ) {
85 recall_id => scalar $query->param('recall_id'),
92 my $userenv = C4::Context->userenv;
93 my $userenv_branch = $userenv->{'branch'} // '';
94 my $forgivemanualholdsexpire = $query->param('forgivemanualholdsexpire');
96 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') eq 'production');
98 # Set up the item stack ....
101 my %riborrowernumber;
103 foreach ( $query->param ) {
116 my $barcode = $query->param("ri-$counter");
117 my $duedate = $query->param("dd-$counter");
118 my $borrowernumber = $query->param("bn-$counter");
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;
125 ######################
126 #Are these lines still useful ?
127 $returneditems{$counter} = $barcode;
128 $riduedate{$counter} = $duedate;
129 $riborrowernumber{$counter} = $borrowernumber;
131 #######################
132 $input{counter} = $counter;
133 $input{barcode} = $barcode;
134 $input{duedate} = $duedate;
135 $input{borrowernumber} = $borrowernumber;
136 push( @inputloop, \%input );
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;
151 if ( $cancel_reserve ) {
152 my $hold = Koha::Holds->find( $reserve_id );
154 $hold->cancel( { charge_cancel_fee => !$forgivemanualholdsexpire } );
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 );
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);
165 my $patron = Koha::Patrons->find( $nextreservinfo );
166 if ( $messages->{'transfert'} ) {
168 itemtitle => $biblio->title,
169 itembiblionumber => $biblio->biblionumber,
170 iteminfo => $biblio->author,
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');
184 if ( !$recall->item_level_recall ) {
185 $item = Koha::Items->find( $itemnumber );
188 if ( $recall->branchcode ne $return_branch ) {
189 $recall->start_transfer({ item => $item }) if !$recall->in_transit;
191 my $expirationdate = $recall->calc_expirationdate;
192 $recall->set_waiting({ item => $item, expirationdate => $expirationdate }) if !$recall->waiting;
201 my $barcode = $query->param('barcode');
202 my $exemptfine = $query->param('exemptfine');
205 !C4::Auth::haspermission(C4::Context->userenv->{'id'}, {'updatecharges' => 'writeoff'})
207 # silently prevent unauthorized operator from forgiving overdue
208 # fines by manually tweaking form parameters
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();
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
231 return_date_override => $return_date_override,
232 return_date_override_remember => 1
233 ) if ($return_date_override_remember);
235 $return_date_override =
236 DateTime::Format::MySQL->format_datetime( $return_date_override_dt );
240 $return_date_override = q{};
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);
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;
262 $template->param( transfercancelled => 1);
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;
277 print $query->redirect("/cgi-bin/koha/circ/transferstoreceive.pl");
280 $template->param( transfercancelled => 1);
285 # actually return book and prepare item table.....
288 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
289 $barcode = barcodedecode($barcode) if $barcode;
290 my $item = Koha::Items->find({ barcode => $barcode });
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 ) {
299 checkinmsg => $itemtype->checkinmsg,
300 checkinmsgtype => $itemtype->checkinmsgtype,
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
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;
312 my $checkout = $item->checkout;
313 my $biblio = $item->biblio;
315 title => $biblio->title,
316 returnbranch => $returnbranch,
317 author => $biblio->author,
318 itembiblionumber => $biblio->biblionumber,
319 biblionumber => $biblio->biblionumber,
320 additional_materials => $materials,
324 } # FIXME else we should not call AddReturn but set BadBarcode directly instead
332 my $return_date = $dropboxmode ? $dropboxdate : $return_date_override_dt;
334 # Block return if multi-part and confirm has not been received
336 C4::Context->preference("CircConfirmItemParts")
339 && !$query->param('multiple_confirm');
340 $template->param( 'multiple_confirmed' => 1 )
341 if $query->param('multiple_confirm');
344 ( $returned, $messages, $issue, $borrower ) =
345 AddReturn( $barcode, $userenv_branch, $exemptfine, $return_date )
346 unless $needs_confirm;
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);
360 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, $dropboxdate) == -1);
362 push( @inputloop, \%input );
364 if ( C4::Context->preference("FineNotifyAtCheckin") ) {
365 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
366 my $balance = $patron->account->balance;
369 $template->param( fines => sprintf("%.2f", $balance) );
370 $template->param( fineborrowernumber => $borrower->{'borrowernumber'} );
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) {
380 waiting_holds => $waiting_holds,
381 holdsborrowernumber => $borrower->{'borrowernumber'},
382 holdsfirstname => $borrower->{'firstname'},
383 holdssurname => $borrower->{'surname'},
387 } elsif ( C4::Context->preference('ShowAllCheckins') and !$messages->{'BadBarcode'} and !$needs_confirm ) {
389 $returneditems{0} = $barcode;
391 push( @inputloop, \%input );
393 $template->param( privacy => $borrower->{privacy} );
395 if ( $needs_confirm ) {
396 $template->param( needs_confirm => $needs_confirm );
399 $template->param( inputloop => \@inputloop );
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 .
409 if ( $messages->{'WasTransfered'} ) {
412 transfer => $messages->{'WasTransfered'},
413 trigger => $messages->{'TransferTrigger'},
414 itemnumber => $itemnumber,
418 if ( $messages->{'NeedsTransfer'} ){
421 needstransfer => $messages->{'NeedsTransfer'},
422 trigger => $messages->{'TransferTrigger'},
426 if ( $messages->{'Wrongbranch'} ){
429 rightbranch => $messages->{'Wrongbranch'}->{'Rightbranch'},
433 # case of wrong transfert, if the document wasn't transferred to the right library (according to branchtransfer (tobranch) BDD)
435 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
437 # Trigger modal to prompt librarian
440 TransferWaitingAt => $messages->{'WrongTransfer'},
441 WrongTransferItem => $messages->{'WrongTransferItem'},
442 trigger => $messages->{'TransferTrigger'},
445 # Update the transfer to reflect the new item holdingbranch
446 my $new_transfer = updateWrongTransfer($messages->{'WrongTransferItem'},$messages->{'WrongTransfer'}, $userenv_branch);
448 NewTransfer => $new_transfer->id
451 my $reserve = $messages->{'ResFound'};
453 my $patron = Koha::Patrons->find( $reserve->{'borrowernumber'} );
461 # reserve found and item arrived at the expected branch
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" ) {
470 waiting => $branchCheck ? 1 : undef,
472 } elsif ( C4::Context->preference('HoldsAutoFill') ) {
473 my $item = Koha::Items->find( $itemnumber );
474 my $biblio = $item->biblio;
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});
481 hold_auto_filled => 1,
482 print_slip => C4::Context->preference('HoldsAutoFillPrintSlip'),
483 reserve_id => $nextreservinfo->{reserve_id},
486 if ( $messages->{'transfert'} ) {
488 itemtitle => $biblio->title,
489 itembiblionumber => $biblio->biblionumber,
490 iteminfo => $biblio->author,
496 intransit => $branchCheck ? undef : 1,
497 transfertodo => $branchCheck ? undef : 1,
498 reserve_id => $reserve->{reserve_id},
503 # same params for Waiting or Reserved
508 destbranch => $reserve->{'branchcode'},
509 reservenotes => $reserve->{'reservenotes'},
510 reserve_id => $reserve->{reserve_id},
511 bormessagepref => $holdmsgpreferences->{'transports'},
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 );
521 my $transferbranch = $messages->{RecallNeedsTransfer};
522 my $transfertodo = ( !$transferbranch or $transferbranch eq $recall->library->branchcode ) ? undef : 1;
526 recalled => $recall->waiting ? 0 : 1,
527 transfertodo => $transfertodo,
528 waitingrecall => $recall->waiting ? 1 : 0,
533 if ( $messages->{TransferredRecall} ) {
534 my $recall = $messages->{TransferredRecall};
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;
539 # if transfer has completed, show popup to confirm as waiting
540 if ( defined $transfer and $transfer->tobranch eq $recall->branchcode ) {
551 foreach my $code ( keys %$messages ) {
553 my $exit_required_p = 0;
554 if ( $code eq 'BadBarcode' ) {
555 $err{badbarcode} = 1;
556 $err{msg} = $messages->{'BadBarcode'};
558 elsif ( $code eq 'NotIssued' ) {
562 elsif ( $code eq 'LocalUse' ) {
565 elsif ( $code eq 'WasLost' ) {
567 $exit_required_p = 1 if C4::Context->preference("BlockReturnOfLostItems");
569 elsif ( $code eq 'LostItemFeeRefunded' ) {
570 $template->param( LostItemFeeRefunded => 1 );
572 elsif ( $code eq 'LostItemFeeCharged' ) {
573 $template->param( LostItemFeeCharged => 1 );
575 elsif ( $code eq 'LostItemFeeRestored' ) {
576 $template->param( LostItemFeeRestored => 1 );
578 elsif ( $code eq 'ResFound' ) {
579 ; # FIXME... anything to do here?
581 elsif ( $code eq 'WasReturned' ) {
582 ; # FIXME... anything to do here?
584 elsif ( $code eq 'WasTransfered' ) {
585 ; # FIXME... anything to do here?
587 elsif ( $code eq 'withdrawn' ) {
589 $exit_required_p = 1 if C4::Context->preference("BlockReturnOfWithdrawnItems");
591 elsif ( $code eq 'WrongTransfer' ) {
592 ; # FIXME... anything to do here?
594 elsif ( $code eq 'WrongTransferItem' ) {
595 ; # FIXME... anything to do here?
597 elsif ( $code eq 'NeedsTransfer' ) {
599 elsif ( $code eq 'TransferTrigger' ) {
600 ; # Handled alongside NeedsTransfer
602 elsif ( $code eq 'TransferArrived' ) {
603 $err{transferred} = $messages->{'TransferArrived'};
605 elsif ( $code eq 'Wrongbranch' ) {
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}";
613 elsif ( $code eq 'PrevDebarred' ) {
614 $err{prevdebarred} = $messages->{'PrevDebarred'};
616 elsif ( $code eq 'ForeverDebarred' ) {
617 $err{foreverdebarred} = $messages->{'ForeverDebarred'};
619 elsif ( $code eq 'ItemLocationUpdated' ) {
620 $err{ItemLocationUpdated} = $messages->{ItemLocationUpdated};
622 elsif ( $code eq 'NotForLoanStatusUpdated' ) {
623 $err{NotForLoanStatusUpdated} = $messages->{NotForLoanStatusUpdated};
625 elsif ( $code eq 'DataCorrupted' ) {
626 $err{data_corrupted} = 1;
628 elsif ( $code eq 'ReturnClaims' ) {
629 $template->param( ReturnClaims => $messages->{ReturnClaims} );
630 } elsif ( $code eq 'RecallFound' ) {
632 } elsif ( $code eq 'RecallNeedsTransfer' ) {
634 } elsif ( $code eq 'TransferredRecall' ) {
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
641 push( @errmsgloop, \%err );
643 last if $exit_required_p;
645 $template->param( errmsgloop => \@errmsgloop );
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;
652 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
653 foreach ( sort { $a <=> $b } keys %returneditems ) {
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);
669 $ri{return_overdue} = 1 if (DateTime->compare($duedate, $dropboxdate) == -1);
671 $ri{patron} = $patron,
672 $ri{borissuescount} = $patron->checkouts->count;
675 $ri{borrowernumber} = $riborrowernumber{$_};
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
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;
704 $ri{location} = $item->location;
705 my $shelfcode = $ri{'location'};
706 $ri{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
717 errmsgloop => \@errmsgloop,
718 exemptfine => $exemptfine,
719 dropboxmode => $dropboxmode,
720 dropboxdate => $dropboxdate,
721 forgivemanualholdsexpire => $forgivemanualholdsexpire,
722 overduecharges => $overduecharges,
723 AudioAlerts => C4::Context->preference("AudioAlerts"),
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 ) ) {
736 collectionItemNeedsTransferred => 1,
737 collectionBranch => $collectionBranch,
744 $template->param( itemnumber => $itemnumber );
746 # Checking if there is a Fast Cataloging Framework
747 $template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' );
749 # actually print the page!
750 output_html_with_http_headers $query, $cookie, $template->output;