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;
59 my ( $template, $librarian, $cookie, $flags ) = get_template_and_user(
61 template_name => "circ/returns.tt",
64 flagsrequired => { circulate => "circulate_remaining_permissions" },
68 my $sessionID = $query->cookie("CGISESSID");
69 my $session = get_session($sessionID);
70 my $desk_id = C4::Context->userenv->{"desk_id"} || '';
72 # Print a reserve slip on this page
73 if ( $query->param('print_slip') ) {
76 reserve_id => scalar $query->param('reserve_id'),
82 my $userenv = C4::Context->userenv;
83 my $userenv_branch = $userenv->{'branch'} // '';
84 my $forgivemanualholdsexpire = $query->param('forgivemanualholdsexpire');
86 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') eq 'production');
88 # Set up the item stack ....
93 foreach ( $query->param ) {
106 my $barcode = $query->param("ri-$counter");
107 my $duedate = $query->param("dd-$counter");
108 my $borrowernumber = $query->param("bn-$counter");
111 # decode barcode ## Didn't we already decode them before passing them back last time??
112 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
113 $barcode = barcodedecode($barcode) if $barcode;
115 ######################
116 #Are these lines still useful ?
117 $returneditems{$counter} = $barcode;
118 $riduedate{$counter} = $duedate;
119 $riborrowernumber{$counter} = $borrowernumber;
121 #######################
122 $input{counter} = $counter;
123 $input{barcode} = $barcode;
124 $input{duedate} = $duedate;
125 $input{borrowernumber} = $borrowernumber;
126 push( @inputloop, \%input );
130 # Deal with the requests....
131 my $itemnumber = $query->param('itemnumber');
132 if ( $query->param('reserve_id') ) {
133 my $borrowernumber = $query->param('borrowernumber');
134 my $reserve_id = $query->param('reserve_id');
135 my $diffBranchReturned = $query->param('diffBranch');
136 my $cancel_reserve = $query->param('cancel_reserve');
137 # fix up item type for display
138 my $item = Koha::Items->find( $itemnumber );
139 my $biblio = $item->biblio;
141 if ( $cancel_reserve ) {
142 my $hold = Koha::Holds->find( $reserve_id );
144 $hold->cancel( { charge_cancel_fee => !$forgivemanualholdsexpire } );
147 my $diffBranchSend = ($userenv_branch ne $diffBranchReturned) ? $diffBranchReturned : undef;
148 # diffBranchSend tells ModReserveAffect whether document is expected in this library or not,
149 # i.e., whether to apply waiting status
150 ModReserveAffect( $itemnumber, $borrowernumber, $diffBranchSend, $reserve_id, $desk_id );
152 # check if we have other reserves for this document, if we have a return send the message of transfer
153 my ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
155 my $patron = Koha::Patrons->find( $nextreservinfo );
156 if ( $messages->{'transfert'} ) {
158 itemtitle => $biblio->title,
159 itembiblionumber => $biblio->biblionumber,
160 iteminfo => $biblio->author,
171 my $barcode = $query->param('barcode');
172 my $exemptfine = $query->param('exemptfine');
175 !C4::Auth::haspermission(C4::Context->userenv->{'id'}, {'updatecharges' => 'writeoff'})
177 # silently prevent unauthorized operator from forgiving overdue
178 # fines by manually tweaking form parameters
181 my $dropboxmode = $query->param('dropboxmode');
182 my $dotransfer = $query->param('dotransfer');
183 my $canceltransfer = $query->param('canceltransfer');
184 my $transit = $query->param('transit');
185 my $dest = $query->param('dest');
186 #dropbox: get last open day (today - 1)
187 my $dropboxdate = Koha::Checkouts::calculate_dropbox_date();
189 my $return_date_override = $query->param('return_date_override');
190 my $return_date_override_dt;
191 my $return_date_override_remember =
192 $query->param('return_date_override_remember');
193 if ($return_date_override) {
194 if ( C4::Context->preference('SpecifyReturnDate') ) {
195 $return_date_override_dt = eval {dt_from_string( $return_date_override ) };
196 if ( $return_date_override_dt ) {
197 # note that we've overriden the return date
198 $template->param( return_date_was_overriden => 1);
199 # Save the original format if we are remembering for this series
201 return_date_override => $return_date_override,
202 return_date_override_remember => 1
203 ) if ($return_date_override_remember);
205 $return_date_override =
206 DateTime::Format::MySQL->format_datetime( $return_date_override_dt );
210 $return_date_override = q{};
215 # An item has been returned to a branch other than the homebranch, and the librarian has chosen to initiate a transfer
216 my $transferitem = $query->param('transferitem');
217 my $tobranch = $query->param('tobranch');
218 my $trigger = $query->param('trigger');
219 ModItemTransfer($transferitem, $userenv_branch, $tobranch, $trigger);
223 my $transfer = Koha::Item::Transfers->find($transit);
224 if ( $canceltransfer ) {
225 $transfer->cancel({ reason => 'Manual', force => 1});
226 $template->param( transfercancelled => 1);
230 } elsif ($canceltransfer){
231 my $item = Koha::Items->find($itemnumber);
232 my $transfer = $item->get_transfer;
233 $transfer->cancel({ reason => 'Manual', force => 1});
235 print $query->redirect("/cgi-bin/koha/circ/transferstoreceive.pl");
238 $template->param( transfercancelled => 1);
243 # actually return book and prepare item table.....
246 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
247 $barcode = barcodedecode($barcode) if $barcode;
248 my $item = Koha::Items->find({ barcode => $barcode });
251 $itemnumber = $item->itemnumber;
252 # Check if we should display a checkin message, based on the the item
253 # type of the checked in item
254 my $itemtype = Koha::ItemTypes->find( $item->effective_itemtype );
255 if ( $itemtype && $itemtype->checkinmsg ) {
257 checkinmsg => $itemtype->checkinmsg,
258 checkinmsgtype => $itemtype->checkinmsgtype,
262 # make sure return branch respects home branch circulation rules, default to homebranch
263 my $hbr = GetBranchItemRule($item->homebranch, $itemtype ? $itemtype->itemtype : undef )->{'returnbranch'} || "homebranch";
264 $returnbranch = $hbr ne 'noreturn' ? $item->$hbr : $userenv_branch; # can be noreturn, homebranch or holdingbranch
266 my $materials = $item->materials;
267 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield =>'items.materials', authorised_value => $materials });
268 $materials = $descriptions->{lib} // $materials;
270 my $checkout = $item->checkout;
271 my $biblio = $item->biblio;
273 title => $biblio->title,
274 returnbranch => $returnbranch,
275 author => $biblio->author,
276 itembiblionumber => $biblio->biblionumber,
277 biblionumber => $biblio->biblionumber,
278 additional_materials => $materials,
282 } # FIXME else we should not call AddReturn but set BadBarcode directly instead
290 my $return_date = $dropboxmode ? $dropboxdate : $return_date_override_dt;
292 # Block return if multi-part and confirm has not been received
294 C4::Context->preference("CircConfirmItemParts")
297 && !$query->param('multiple_confirm');
298 $template->param( 'multiple_confirmed' => 1 )
299 if $query->param('multiple_confirm');
302 ( $returned, $messages, $issue, $borrower ) =
303 AddReturn( $barcode, $userenv_branch, $exemptfine, $return_date )
304 unless $needs_confirm;
307 my $time_now = dt_from_string()->truncate( to => 'minute');
308 my $date_due_dt = dt_from_string( $issue->date_due, 'sql' );
309 my $duedate = $date_due_dt->strftime('%Y-%m-%d %H:%M');
310 $returneditems{0} = $barcode;
311 $riborrowernumber{0} = $borrower->{'borrowernumber'};
312 $riduedate{0} = $duedate;
313 $input{borrowernumber} = $borrower->{'borrowernumber'};
314 $input{duedate} = $duedate;
315 unless ( $dropboxmode ) {
316 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, dt_from_string()) == -1);
318 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, $dropboxdate) == -1);
320 push( @inputloop, \%input );
322 if ( C4::Context->preference("FineNotifyAtCheckin") ) {
323 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
324 my $balance = $patron->account->balance;
327 $template->param( fines => sprintf("%.2f", $balance) );
328 $template->param( fineborrowernumber => $borrower->{'borrowernumber'} );
332 if (C4::Context->preference("WaitingNotifyAtCheckin") ) {
333 #Check for waiting holds
334 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
335 my $waiting_holds = $patron->holds->search({ found => 'W', branchcode => $userenv_branch })->count;
336 if ($waiting_holds > 0) {
338 waiting_holds => $waiting_holds,
339 holdsborrowernumber => $borrower->{'borrowernumber'},
340 holdsfirstname => $borrower->{'firstname'},
341 holdssurname => $borrower->{'surname'},
345 } elsif ( C4::Context->preference('ShowAllCheckins') and !$messages->{'BadBarcode'} and !$needs_confirm ) {
347 $returneditems{0} = $barcode;
349 push( @inputloop, \%input );
351 $template->param( privacy => $borrower->{privacy} );
353 if ( $needs_confirm ) {
354 $template->param( needs_confirm => $needs_confirm );
357 $template->param( inputloop => \@inputloop );
363 # new op dev : we check if the document must be returned to his homebranch directly,
364 # if the document is transferred, we have warning message .
366 if ( $messages->{'WasTransfered'} ) {
369 transfer => $messages->{'WasTransfered'},
370 trigger => $messages->{'TransferTrigger'},
371 itemnumber => $itemnumber,
375 if ( $messages->{'NeedsTransfer'} ){
378 needstransfer => $messages->{'NeedsTransfer'},
379 trigger => $messages->{'TransferTrigger'},
383 if ( $messages->{'Wrongbranch'} ){
386 rightbranch => $messages->{'Wrongbranch'}->{'Rightbranch'},
390 # case of wrong transfert, if the document wasn't transferred to the right library (according to branchtransfer (tobranch) BDD)
392 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
394 # Trigger modal to prompt librarian
397 TransferWaitingAt => $messages->{'WrongTransfer'},
398 WrongTransferItem => $messages->{'WrongTransferItem'},
399 trigger => $messages->{'TransferTrigger'},
402 # Update the transfer to reflect the new item holdingbranch
403 my $new_transfer = updateWrongTransfer($messages->{'WrongTransferItem'},$messages->{'WrongTransfer'}, $userenv_branch);
405 NewTransfer => $new_transfer->id
408 my $reserve = $messages->{'ResFound'};
410 my $patron = Koha::Patrons->find( $reserve->{'borrowernumber'} );
418 # reserve found and item arrived at the expected branch
420 if ( $messages->{'ResFound'}) {
421 my $reserve = $messages->{'ResFound'};
422 my $patron = Koha::Patrons->find( $reserve->{borrowernumber} );
423 my $holdmsgpreferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $reserve->{'borrowernumber'}, message_name => 'Hold_Filled' } );
424 my $branchCheck = ( $userenv_branch eq $reserve->{branchcode} );
425 if ( $reserve->{'ResFound'} eq "Waiting" ) {
427 waiting => $branchCheck ? 1 : undef,
429 } elsif ( C4::Context->preference('HoldsAutoFill') ) {
430 my $item = Koha::Items->find( $itemnumber );
431 my $biblio = $item->biblio;
433 my $diffBranchSend = !$branchCheck ? $reserve->{branchcode} : undef;
434 ModReserveAffect( $itemnumber, $reserve->{borrowernumber}, $diffBranchSend, $reserve->{reserve_id}, $desk_id );
435 my ( $messages, $nextreservinfo ) = GetOtherReserves($reserve->{itemnumber});
438 hold_auto_filled => 1,
439 print_slip => C4::Context->preference('HoldsAutoFillPrintSlip'),
440 reserve_id => $nextreservinfo->{reserve_id},
443 if ( $messages->{'transfert'} ) {
445 itemtitle => $biblio->title,
446 itembiblionumber => $biblio->biblionumber,
447 iteminfo => $biblio->author,
453 intransit => $branchCheck ? undef : 1,
454 transfertodo => $branchCheck ? undef : 1,
455 reserve_id => $reserve->{reserve_id},
460 # same params for Waiting or Reserved
465 destbranch => $reserve->{'branchcode'},
466 reservenotes => $reserve->{'reservenotes'},
467 reserve_id => $reserve->{reserve_id},
468 bormessagepref => $holdmsgpreferences->{'transports'},
474 foreach my $code ( keys %$messages ) {
476 my $exit_required_p = 0;
477 if ( $code eq 'BadBarcode' ) {
478 $err{badbarcode} = 1;
479 $err{msg} = $messages->{'BadBarcode'};
481 elsif ( $code eq 'NotIssued' ) {
485 elsif ( $code eq 'LocalUse' ) {
488 elsif ( $code eq 'WasLost' ) {
490 $exit_required_p = 1 if C4::Context->preference("BlockReturnOfLostItems");
492 elsif ( $code eq 'LostItemFeeRefunded' ) {
493 $template->param( LostItemFeeRefunded => 1 );
495 elsif ( $code eq 'LostItemFeeCharged' ) {
496 $template->param( LostItemFeeCharged => 1 );
498 elsif ( $code eq 'LostItemFeeRestored' ) {
499 $template->param( LostItemFeeRestored => 1 );
501 elsif ( $code eq 'ResFound' ) {
502 ; # FIXME... anything to do here?
504 elsif ( $code eq 'WasReturned' ) {
505 ; # FIXME... anything to do here?
507 elsif ( $code eq 'WasTransfered' ) {
508 ; # FIXME... anything to do here?
510 elsif ( $code eq 'withdrawn' ) {
512 $exit_required_p = 1 if C4::Context->preference("BlockReturnOfWithdrawnItems");
514 elsif ( $code eq 'WrongTransfer' ) {
515 ; # FIXME... anything to do here?
517 elsif ( $code eq 'WrongTransferItem' ) {
518 ; # FIXME... anything to do here?
520 elsif ( $code eq 'NeedsTransfer' ) {
522 elsif ( $code eq 'TransferTrigger' ) {
523 ; # Handled alongside NeedsTransfer
525 elsif ( $code eq 'TransferArrived' ) {
526 $err{transferred} = $messages->{'TransferArrived'};
528 elsif ( $code eq 'Wrongbranch' ) {
530 elsif ( $code eq 'Debarred' ) {
531 $err{debarred} = $messages->{'Debarred'};
532 $err{debarcardnumber} = $borrower->{cardnumber};
533 $err{debarborrowernumber} = $borrower->{borrowernumber};
534 $err{debarname} = "$borrower->{firstname} $borrower->{surname}";
536 elsif ( $code eq 'PrevDebarred' ) {
537 $err{prevdebarred} = $messages->{'PrevDebarred'};
539 elsif ( $code eq 'ForeverDebarred' ) {
540 $err{foreverdebarred} = $messages->{'ForeverDebarred'};
542 elsif ( $code eq 'ItemLocationUpdated' ) {
543 $err{ItemLocationUpdated} = $messages->{ItemLocationUpdated};
545 elsif ( $code eq 'NotForLoanStatusUpdated' ) {
546 $err{NotForLoanStatusUpdated} = $messages->{NotForLoanStatusUpdated};
548 elsif ( $code eq 'DataCorrupted' ) {
549 $err{data_corrupted} = 1;
551 elsif ( $code eq 'ReturnClaims' ) {
552 $template->param( ReturnClaims => $messages->{ReturnClaims} );
554 die "Unknown error code $code"; # note we need all the (empty) elsif's above, or we die.
555 # This forces the issue of staying in sync w/ Circulation.pm
558 push( @errmsgloop, \%err );
560 last if $exit_required_p;
562 $template->param( errmsgloop => \@errmsgloop );
564 #set up so only the last 8 returned items display (make for faster loading pages)
565 my $returned_counter = ( C4::Context->preference('numReturnedItemsToShow') ) ? C4::Context->preference('numReturnedItemsToShow') : 8;
569 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
570 foreach ( sort { $a <=> $b } keys %returneditems ) {
572 if ( $count++ < $returned_counter ) {
573 my $bar_code = $returneditems{$_};
574 if ($riduedate{$_}) {
575 my $duedate = dt_from_string( $riduedate{$_}, 'sql');
576 $ri{year} = $duedate->year();
577 $ri{month} = $duedate->month();
578 $ri{day} = $duedate->day();
579 $ri{hour} = $duedate->hour();
580 $ri{minute} = $duedate->minute();
581 $ri{duedate} = output_pref($duedate);
582 my $patron = Koha::Patrons->find( $riborrowernumber{$_} );
583 unless ( $dropboxmode ) {
584 $ri{return_overdue} = 1 if (DateTime->compare($duedate, dt_from_string()) == -1);
586 $ri{return_overdue} = 1 if (DateTime->compare($duedate, $dropboxdate) == -1);
588 $ri{patron} = $patron,
589 $ri{borissuescount} = $patron->checkouts->count;
592 $ri{borrowernumber} = $riborrowernumber{$_};
595 my $item = Koha::Items->find({ barcode => $bar_code });
596 next unless $item; # FIXME The item has been deleted in the meantime,
597 # we could handle that better displaying a message in the template
599 my $biblio = $item->biblio;
600 # FIXME pass $item to the template and we are done here...
601 $ri{itembiblionumber} = $biblio->biblionumber;
602 $ri{itemtitle} = $biblio->title;
603 $ri{subtitle} = $biblio->subtitle;
604 $ri{part_name} = $biblio->part_name;
605 $ri{part_number} = $biblio->part_number;
606 $ri{itemauthor} = $biblio->author;
607 $ri{itemcallnumber} = $item->itemcallnumber;
608 $ri{dateaccessioned} = $item->dateaccessioned;
609 $ri{recordtype} = $biblio->itemtype;
610 $ri{itemtype} = $item->itype;
611 $ri{itemnote} = $item->itemnotes;
612 $ri{itemnotes_nonpublic} = $item->itemnotes_nonpublic;
613 $ri{ccode} = $item->ccode;
614 $ri{enumchron} = $item->enumchron;
615 $ri{itemnumber} = $item->itemnumber;
616 $ri{barcode} = $bar_code;
617 $ri{homebranch} = $item->homebranch;
618 $ri{transferbranch} = $item->get_transfer ? $item->get_transfer->tobranch : '';
619 $ri{damaged} = $item->damaged;
621 $ri{location} = $item->location;
622 my $shelfcode = $ri{'location'};
623 $ri{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
634 errmsgloop => \@errmsgloop,
635 exemptfine => $exemptfine,
636 dropboxmode => $dropboxmode,
637 dropboxdate => $dropboxdate,
638 forgivemanualholdsexpire => $forgivemanualholdsexpire,
639 overduecharges => $overduecharges,
640 AudioAlerts => C4::Context->preference("AudioAlerts"),
644 my $item_from_barcode = Koha::Items->find({barcode => $barcode }); # How many times do we fetch this item?!?
645 if ( $item_from_barcode ) {
646 $itemnumber = $item_from_barcode->itemnumber;
647 my ( $holdingBranch, $collectionBranch ) = GetCollectionItemBranches( $itemnumber );
648 if ( $holdingBranch and $collectionBranch ) {
649 $holdingBranch //= '';
650 $collectionBranch //= $returnbranch;
651 if ( ! ( $holdingBranch eq $collectionBranch ) ) {
653 collectionItemNeedsTransferred => 1,
654 collectionBranch => $collectionBranch,
661 $template->param( itemnumber => $itemnumber );
663 # Checking if there is a Fast Cataloging Framework
664 $template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' );
666 # actually print the page!
667 output_html_with_http_headers $query, $cookie, $template->output;