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
34 $SIG{ __DIE__ } = sub { Carp::confess( @_ ) };
39 use C4::Auth qw/:DEFAULT get_session/;
47 use C4::Members::Messaging;
48 use C4::Koha; # FIXME : is it still useful ?
49 use C4::RotatingCollections;
50 use Koha::AuthorisedValues;
53 use Koha::BiblioFrameworks;
61 my ( $template, $librarian, $cookie, $flags ) = get_template_and_user(
63 template_name => "circ/returns.tt",
67 flagsrequired => { circulate => "circulate_remaining_permissions" },
71 my $sessionID = $query->cookie("CGISESSID");
72 my $session = get_session($sessionID);
73 if ($session->param('branch') eq 'NO_LIBRARY_SET'){
74 # no branch set we can't return
75 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
79 # Print a reserve slip on this page
80 if ( $query->param('print_slip') ) {
83 borrowernumber => scalar $query->param('borrowernumber'),
84 biblionumber => scalar $query->param('biblionumber'),
90 my $printers = GetPrinters();
91 my $userenv = C4::Context->userenv;
92 my $userenv_branch = $userenv->{'branch'} // '';
93 my $printer = $userenv->{'branchprinter'} // '';
94 my $forgivemanualholdsexpire = $query->param('forgivemanualholdsexpire');
96 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') ne 'off');
98 # Some code to handle the error if there is no branch or printer setting.....
101 # Set up the item stack ....
104 my %riborrowernumber;
106 foreach ( $query->param ) {
119 my $barcode = $query->param("ri-$counter");
120 my $duedate = $query->param("dd-$counter");
121 my $borrowernumber = $query->param("bn-$counter");
124 # decode barcode ## Didn't we already decode them before passing them back last time??
125 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
126 $barcode = barcodedecode($barcode) if(C4::Context->preference('itemBarcodeInputFilter'));
128 ######################
129 #Are these lines still useful ?
130 $returneditems{$counter} = $barcode;
131 $riduedate{$counter} = $duedate;
132 $riborrowernumber{$counter} = $borrowernumber;
134 #######################
135 $input{counter} = $counter;
136 $input{barcode} = $barcode;
137 $input{duedate} = $duedate;
138 $input{borrowernumber} = $borrowernumber;
139 push( @inputloop, \%input );
143 # Deal with the requests....
145 if ($query->param('WT-itemNumber')){
146 updateWrongTransfer ($query->param('WT-itemNumber'),$query->param('WT-waitingAt'),$query->param('WT-From'));
149 if ( $query->param('reserve_id') ) {
150 my $itemnumber = $query->param('itemnumber');
151 my $borrowernumber = $query->param('borrowernumber');
152 my $reserve_id = $query->param('reserve_id');
153 my $diffBranchReturned = $query->param('diffBranch');
154 my $cancel_reserve = $query->param('cancel_reserve');
155 # fix up item type for display
156 my $item = Koha::Items->find( $itemnumber );
157 my $biblio = $item->biblio;
159 if ( $cancel_reserve ) {
160 CancelReserve({ reserve_id => $reserve_id, charge_cancel_fee => !$forgivemanualholdsexpire });
162 my $diffBranchSend = ($userenv_branch ne $diffBranchReturned) ? $diffBranchReturned : undef;
163 # diffBranchSend tells ModReserveAffect whether document is expected in this library or not,
164 # i.e., whether to apply waiting status
165 ModReserveAffect( $itemnumber, $borrowernumber, $diffBranchSend, $reserve_id );
167 # check if we have other reserves for this document, if we have a return send the message of transfer
168 my ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
170 my $borr = GetMember( borrowernumber => $nextreservinfo );
171 my $name = $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'};
172 if ( $messages->{'transfert'} ) {
174 itemtitle => $biblio->title,
175 itemnumber => $item->itemnumber,
176 itembiblionumber => $biblio->biblionumber,
177 iteminfo => $biblio->author,
179 borrowernumber => $borrowernumber,
180 borcnum => $borr->{'cardnumber'},
181 borfirstname => $borr->{'firstname'},
182 borsurname => $borr->{'surname'},
183 borcategory => $borr->{'description'},
194 my $barcode = $query->param('barcode');
195 my $exemptfine = $query->param('exemptfine');
198 !C4::Auth::haspermission(C4::Context->userenv->{'id'}, {'updatecharges' => 'writeoff'})
200 # silently prevent unauthorized operator from forgiving overdue
201 # fines by manually tweaking form parameters
204 my $dropboxmode = $query->param('dropboxmode');
205 my $dotransfer = $query->param('dotransfer');
206 my $canceltransfer = $query->param('canceltransfer');
207 my $dest = $query->param('dest');
208 my $calendar = Koha::Calendar->new( branchcode => $userenv_branch );
209 #dropbox: get last open day (today - 1)
210 my $today = DateTime->now( time_zone => C4::Context->tz());
211 my $dropboxdate = $calendar->addDate($today, -1);
213 my $return_date_override = $query->param('return_date_override');
214 my $return_date_override_remember =
215 $query->param('return_date_override_remember');
216 if ($return_date_override) {
217 if ( C4::Context->preference('SpecifyReturnDate') ) {
218 my $return_date_override_dt = eval {dt_from_string( $return_date_override ) };
219 if ( $return_date_override_dt ) {
220 # note that we've overriden the return date
221 $template->param( return_date_was_overriden => 1);
222 # Save the original format if we are remembering for this series
224 return_date_override => $return_date_override,
225 return_date_override_remember => 1
226 ) if ($return_date_override_remember);
228 $return_date_override =
229 DateTime::Format::MySQL->format_datetime( $return_date_override_dt );
233 $return_date_override = q{};
238 # An item has been returned to a branch other than the homebranch, and the librarian has chosen to initiate a transfer
239 my $transferitem = $query->param('transferitem');
240 my $tobranch = $query->param('tobranch');
241 ModItemTransfer($transferitem, $userenv_branch, $tobranch);
244 if ($canceltransfer){
245 $itemnumber=$query->param('itemnumber');
246 DeleteTransfer($itemnumber);
248 print $query->redirect("/cgi-bin/koha/circ/transferstoreceive.pl");
251 $template->param( transfercancelled => 1);
255 # actually return book and prepare item table.....
258 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
259 $barcode = barcodedecode($barcode) if C4::Context->preference('itemBarcodeInputFilter');
260 my $item = Koha::Items->find({ barcode => $barcode });
263 # Check if we should display a checkin message, based on the the item
264 # type of the checked in item
265 my $itemtype = Koha::ItemTypes->find( $item->effective_itemtype );
266 if ( $itemtype && $itemtype->checkinmsg ) {
268 checkinmsg => $itemtype->checkinmsg,
269 checkinmsgtype => $itemtype->checkinmsgtype,
273 # make sure return branch respects home branch circulation rules, default to homebranch
274 my $hbr = GetBranchItemRule($item->homebranch, $itemtype ? $itemtype->itemtype : undef )->{'returnbranch'} || "homebranch";
275 $returnbranch = $item->$hbr;
277 my $materials = $item->materials;
278 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield =>'items.materials', authorised_value => $materials });
279 $materials = $descriptions->{lib} // $materials;
281 my $issue = Koha::Checkouts->find( { itemnumber => $itemnumber } );
283 my $biblio = $item->biblio;
285 title => $biblio->title,
286 homebranch => $item->homebranch,
287 holdingbranch => $item->holdingbranch,
288 returnbranch => $returnbranch,
289 author => $biblio->author,
290 itembarcode => $item->barcode,
291 itemtype => $item->effective_itemtype,
292 ccode => $item->ccode,
293 itembiblionumber => $biblio->biblionumber,
294 biblionumber => $biblio->biblionumber,
295 borrower => $borrower,
296 additional_materials => $materials,
299 } # FIXME else we should not call AddReturn but set BadBarcode directly instead
309 ( $returned, $messages, $issue, $borrower ) =
310 AddReturn( $barcode, $userenv_branch, $exemptfine, $dropboxmode, $return_date_override, $dropboxdate );
313 my $time_now = DateTime->now( time_zone => C4::Context->tz )->truncate( to => 'minute');
314 my $date_due_dt = dt_from_string( $issue->date_due, 'sql' );
315 my $duedate = $date_due_dt->strftime('%Y-%m-%d %H:%M');
316 $returneditems{0} = $barcode;
317 $riborrowernumber{0} = $borrower->{'borrowernumber'};
318 $riduedate{0} = $duedate;
319 $input{borrowernumber} = $borrower->{'borrowernumber'};
320 $input{duedate} = $duedate;
321 unless ( $dropboxmode ) {
322 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, DateTime->now()) == -1);
324 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, $dropboxdate) == -1);
326 push( @inputloop, \%input );
328 if ( C4::Context->preference("FineNotifyAtCheckin") ) {
329 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
330 my $balance = $patron->account->balance;
333 $template->param( fines => sprintf("%.2f", $balance) );
334 $template->param( fineborrowernumber => $borrower->{'borrowernumber'} );
338 if (C4::Context->preference("WaitingNotifyAtCheckin") ) {
339 #Check for waiting holds
340 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
341 my $waiting_holds = $patron->holds->search({ found => 'W', branchcode => $userenv_branch })->count;
342 if ($waiting_holds > 0) {
344 waiting_holds => $waiting_holds,
345 holdsborrowernumber => $borrower->{'borrowernumber'},
346 holdsfirstname => $borrower->{'firstname'},
347 holdssurname => $borrower->{'surname'},
351 } elsif ( C4::Context->preference('ShowAllCheckins') and !$messages->{'BadBarcode'} ) {
353 $returneditems{0} = $barcode;
355 push( @inputloop, \%input );
357 $template->param( privacy => $borrower->{privacy} );
359 $template->param( inputloop => \@inputloop );
365 # new op dev : we check if the document must be returned to his homebranch directly,
366 # if the document is transfered, we have warning message .
368 if ( $messages->{'WasTransfered'} ) {
372 itemnumber => $itemnumber,
376 if ( $messages->{'NeedsTransfer'} ){
379 needstransfer => $messages->{'NeedsTransfer'},
380 itemnumber => $itemnumber,
384 if ( $messages->{'Wrongbranch'} ){
387 rightbranch => $messages->{'Wrongbranch'}->{'Rightbranch'},
391 # case of wrong transfert, if the document wasn't transfered to the right library (according to branchtransfer (tobranch) BDD)
393 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
396 TransferWaitingAt => $messages->{'WrongTransfer'},
397 WrongTransferItem => $messages->{'WrongTransferItem'},
398 itemnumber => $itemnumber,
401 my $reserve = $messages->{'ResFound'};
402 my $borr = C4::Members::GetMember( borrowernumber => $reserve->{'borrowernumber'} );
403 my $name = $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'};
406 wborfirstname => $borr->{'firstname'},
407 wborsurname => $borr->{'surname'},
408 wborcategory => $borr->{'description'},
409 wbortitle => $borr->{'title'},
410 wborphone => $borr->{'phone'},
411 wboremail => $borr->{'email'},
412 streetnumber => $borr->{streetnumber},
413 streettype => $borr->{streettype},
414 address => $borr->{'address'},
415 address2 => $borr->{'address2'},
416 city => $borr->{'city'},
417 zipcode => $borr->{'zipcode'},
418 state => $borr->{'state'},
419 country => $borr->{'country'},
420 wborrowernumber => $reserve->{'borrowernumber'},
421 wborcnum => $borr->{'cardnumber'},
422 wtransfertFrom => $userenv_branch,
427 # reserve found and item arrived at the expected branch
429 if ( $messages->{'ResFound'}) {
430 my $reserve = $messages->{'ResFound'};
431 my $borr = C4::Members::GetMember( borrowernumber => $reserve->{'borrowernumber'} );
432 my $holdmsgpreferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $reserve->{'borrowernumber'}, message_name => 'Hold_Filled' } );
433 if ( $reserve->{'ResFound'} eq "Waiting" or $reserve->{'ResFound'} eq "Reserved" ) {
434 if ( $reserve->{'ResFound'} eq "Waiting" ) {
436 waiting => ($userenv_branch eq $reserve->{'branchcode'} ? 1 : 0 ),
438 } elsif ( $reserve->{'ResFound'} eq "Reserved" ) {
440 intransit => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
441 transfertodo => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
442 reserve_id => $reserve->{reserve_id},
447 # same params for Waiting or Reserved
450 name => $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'},
451 borfirstname => $borr->{'firstname'},
452 borsurname => $borr->{'surname'},
453 borcategory => $borr->{'description'},
454 bortitle => $borr->{'title'},
455 borphone => $borr->{'phone'},
456 boremail => $borr->{'email'},
457 streetnumber => $borr->{streetnumber},
458 streettype => $borr->{streettype},
459 address => $borr->{'address'},
460 address2 => $borr->{'address2'},
461 city => $borr->{'city'},
462 zipcode => $borr->{'zipcode'},
463 state => $borr->{'state'},
464 country => $borr->{'country'},
465 borcnum => $borr->{'cardnumber'},
466 debarred => $borr->{'debarred'},
467 gonenoaddress => $borr->{'gonenoaddress'},
469 destbranch => $reserve->{'branchcode'},
470 borrowernumber => $reserve->{'borrowernumber'},
471 itemnumber => $reserve->{'itemnumber'},
472 reservenotes => $reserve->{'reservenotes'},
473 reserve_id => $reserve->{reserve_id},
474 bormessagepref => $holdmsgpreferences->{'transports'},
476 } # else { ; } # error?
481 foreach my $code ( keys %$messages ) {
483 my $exit_required_p = 0;
484 if ( $code eq 'BadBarcode' ) {
485 $err{badbarcode} = 1;
486 $err{msg} = $messages->{'BadBarcode'};
488 elsif ( $code eq 'NotIssued' ) {
491 $err{msg} = $messages->{'IsPermanent'} if $messages->{'IsPermanent'};
493 elsif ( $code eq 'LocalUse' ) {
496 elsif ( $code eq 'WasLost' ) {
499 elsif ( $code eq 'LostItemFeeRefunded' ) {
500 $template->param( LostItemFeeRefunded => 1 );
502 elsif ( $code eq 'ResFound' ) {
503 ; # FIXME... anything to do here?
505 elsif ( $code eq 'WasReturned' ) {
506 ; # FIXME... anything to do here?
508 elsif ( $code eq 'WasTransfered' ) {
509 ; # FIXME... anything to do here?
511 elsif ( $code eq 'withdrawn' ) {
513 $exit_required_p = 1 if C4::Context->preference("BlockReturnOfWithdrawnItems");
515 elsif ( ( $code eq 'IsPermanent' ) && ( not $messages->{'ResFound'} ) ) {
516 if ( $messages->{'IsPermanent'} ne $userenv_branch ) {
517 $err{ispermanent} = 1;
518 $err{msg} = $messages->{'IsPermanent'};
521 elsif ( $code eq 'WrongTransfer' ) {
522 ; # FIXME... anything to do here?
524 elsif ( $code eq 'WrongTransferItem' ) {
525 ; # FIXME... anything to do here?
527 elsif ( $code eq 'NeedsTransfer' ) {
529 elsif ( $code eq 'Wrongbranch' ) {
531 elsif ( $code eq 'Debarred' ) {
532 $err{debarred} = $messages->{'Debarred'};
533 $err{debarcardnumber} = $borrower->{cardnumber};
534 $err{debarborrowernumber} = $borrower->{borrowernumber};
535 $err{debarname} = "$borrower->{firstname} $borrower->{surname}";
537 elsif ( $code eq 'PrevDebarred' ) {
538 $err{prevdebarred} = $messages->{'PrevDebarred'};
540 elsif ( $code eq 'ForeverDebarred' ) {
541 $err{foreverdebarred} = $messages->{'ForeverDebarred'};
543 elsif ( $code eq 'NotForLoanStatusUpdated' ) {
544 $err{NotForLoanStatusUpdated} = $messages->{NotForLoanStatusUpdated};
547 die "Unknown error code $code"; # note we need all the (empty) elsif's above, or we die.
548 # This forces the issue of staying in sync w/ Circulation.pm
551 push( @errmsgloop, \%err );
553 last if $exit_required_p;
555 $template->param( errmsgloop => \@errmsgloop );
557 #set up so only the last 8 returned items display (make for faster loading pages)
558 my $returned_counter = ( C4::Context->preference('numReturnedItemsToShow') ) ? C4::Context->preference('numReturnedItemsToShow') : 8;
562 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
563 foreach ( sort { $a <=> $b } keys %returneditems ) {
565 if ( $count++ < $returned_counter ) {
566 my $bar_code = $returneditems{$_};
567 if ($riduedate{$_}) {
568 my $duedate = dt_from_string( $riduedate{$_}, 'sql');
569 $ri{year} = $duedate->year();
570 $ri{month} = $duedate->month();
571 $ri{day} = $duedate->day();
572 $ri{hour} = $duedate->hour();
573 $ri{minute} = $duedate->minute();
574 $ri{duedate} = output_pref($duedate);
575 my $b = C4::Members::GetMember( borrowernumber => $riborrowernumber{$_} );
576 unless ( $dropboxmode ) {
577 $ri{return_overdue} = 1 if (DateTime->compare($duedate, DateTime->now()) == -1);
579 $ri{return_overdue} = 1 if (DateTime->compare($duedate, $dropboxdate) == -1);
581 $ri{borrowernumber} = $b->{'borrowernumber'};
582 $ri{borcnum} = $b->{'cardnumber'};
583 $ri{borfirstname} = $b->{'firstname'};
584 $ri{borsurname} = $b->{'surname'};
585 $ri{bortitle} = $b->{'title'};
586 $ri{bornote} = $b->{'borrowernotes'};
587 $ri{borcategorycode}= $b->{'categorycode'};
588 $ri{borissuescount} = Koha::Checkouts->count( { borrowernumber => $b->{'borrowernumber'} } );
591 $ri{borrowernumber} = $riborrowernumber{$_};
594 my $item = Koha::Items->find({ barcode => $bar_code });
595 my $biblio = $item->biblio;
596 # FIXME pass $item to the template and we are done here...
597 $ri{itembiblionumber} = $biblio->biblionumber;
598 $ri{itemtitle} = $biblio->title;
599 $ri{itemauthor} = $biblio->author;
600 $ri{itemcallnumber} = $item->itemcallnumber;
601 $ri{dateaccessioned} = $item->dateaccessioned;
602 $ri{itemtype} = $item->effective_itemtype;
603 $ri{itemnote} = $item->itemnotes;
604 $ri{itemnotes_nonpublic} = $item->itemnotes_nonpublic;
605 $ri{ccode} = $item->ccode;
606 $ri{enumchron} = $item->enumchron;
607 $ri{itemnumber} = $item->itemnumber;
608 $ri{barcode} = $bar_code;
609 $ri{homebranch} = $item->homebranch;
610 $ri{holdingbranch} = $item->holdingbranch;
612 $ri{location} = $biblio->{'location'};
613 my $shelfcode = $ri{'location'};
614 $ri{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
626 errmsgloop => \@errmsgloop,
627 exemptfine => $exemptfine,
628 dropboxmode => $dropboxmode,
629 dropboxdate => output_pref($dropboxdate),
630 forgivemanualholdsexpire => $forgivemanualholdsexpire,
631 overduecharges => $overduecharges,
632 AudioAlerts => C4::Context->preference("AudioAlerts"),
633 BlockReturnOfWithdrawnItems => C4::Context->preference("BlockReturnOfWithdrawnItems"),
636 $itemnumber = GetItemnumberFromBarcode( $barcode );
638 my ( $holdingBranch, $collectionBranch ) = GetCollectionItemBranches( $itemnumber );
639 if ( $holdingBranch and $collectionBranch ) {
640 $holdingBranch //= '';
641 $collectionBranch //= $returnbranch;
642 if ( ! ( $holdingBranch eq $collectionBranch ) ) {
644 collectionItemNeedsTransferred => 1,
645 collectionBranch => $collectionBranch,
646 itemnumber => $itemnumber,
652 # Checking if there is a Fast Cataloging Framework
653 $template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' );
655 # actually print the page!
656 output_html_with_http_headers $query, $cookie, $template->output;