Bug 24610: Let user switch between 'Pay' and 'Write off' mode
[koha.git] / circ / returns.pl
blobe1bce3c3f11e129c028b2763a8bb9d1f3039d465
1 #!/usr/bin/perl
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.
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>.
24 =head1 returns.pl
26 script to execute returns of books
28 =cut
30 use Modern::Perl;
32 # FIXME There are weird things going on with $patron and $borrowernumber in this script
34 use CGI qw ( -utf8 );
35 use DateTime;
37 use C4::Auth qw/:DEFAULT get_session/;
38 use C4::Output;
39 use C4::Circulation;
40 use C4::Reserves;
41 use C4::Biblio;
42 use C4::Circulation;
43 use C4::Context;
44 use C4::Items;
45 use C4::Koha; # FIXME : is it still useful ?
46 use C4::Members::Messaging;
47 use C4::Members;
48 use C4::Output;
49 use C4::Reserves;
50 use C4::RotatingCollections;
51 use Koha::AuthorisedValues;
52 use Koha::BiblioFrameworks;
53 use Koha::Calendar;
54 use Koha::Checkouts;
55 use Koha::DateUtils;
56 use Koha::Holds;
57 use Koha::Items;
58 use Koha::Patrons;
60 my $query = new CGI;
62 #getting the template
63 my ( $template, $librarian, $cookie, $flags ) = get_template_and_user(
65 template_name => "circ/returns.tt",
66 query => $query,
67 type => "intranet",
68 authnotrequired => 0,
69 flagsrequired => { circulate => "circulate_remaining_permissions" },
73 my $sessionID = $query->cookie("CGISESSID");
74 my $session = get_session($sessionID);
76 # Print a reserve slip on this page
77 if ( $query->param('print_slip') ) {
78 $template->param(
79 print_slip => 1,
80 reserve_id => scalar $query->param('reserve_id'),
84 #####################
85 #Global vars
86 my $userenv = C4::Context->userenv;
87 my $userenv_branch = $userenv->{'branch'} // '';
88 my $forgivemanualholdsexpire = $query->param('forgivemanualholdsexpire');
90 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') ne 'off');
92 # Set up the item stack ....
93 my %returneditems;
94 my %riduedate;
95 my %riborrowernumber;
96 my @inputloop;
97 foreach ( $query->param ) {
98 my $counter;
99 if (/ri-(\d*)/) {
100 $counter = $1;
101 if ($counter > 20) {
102 next;
105 else {
106 next;
109 my %input;
110 my $barcode = $query->param("ri-$counter");
111 my $duedate = $query->param("dd-$counter");
112 my $borrowernumber = $query->param("bn-$counter");
113 $counter++;
115 # decode barcode ## Didn't we already decode them before passing them back last time??
116 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
117 $barcode = barcodedecode($barcode) if(C4::Context->preference('itemBarcodeInputFilter'));
119 ######################
120 #Are these lines still useful ?
121 $returneditems{$counter} = $barcode;
122 $riduedate{$counter} = $duedate;
123 $riborrowernumber{$counter} = $borrowernumber;
125 #######################
126 $input{counter} = $counter;
127 $input{barcode} = $barcode;
128 $input{duedate} = $duedate;
129 $input{borrowernumber} = $borrowernumber;
130 push( @inputloop, \%input );
133 ############
134 # Deal with the requests....
136 if ($query->param('WT-itemNumber')){
137 updateWrongTransfer ($query->param('WT-itemNumber'),$query->param('WT-waitingAt'),$query->param('WT-From'));
140 if ( $query->param('reserve_id') ) {
141 my $itemnumber = $query->param('itemnumber');
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;
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 );
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);
164 my $patron = Koha::Patrons->find( $nextreservinfo );
165 my $name = $patron ? $patron->surname . ", " . $patron->title . " " . $patron->firstname : '';
166 if ( $messages->{'transfert'} ) {
167 $template->param(
168 itemtitle => $biblio->title,
169 itemnumber => $item->itemnumber,
170 itembiblionumber => $biblio->biblionumber,
171 iteminfo => $biblio->author,
172 name => $name,
173 patron => $patron,
174 diffbranch => 1,
179 my $borrower;
180 my $returned = 0;
181 my $messages;
182 my $issue;
183 my $itemnumber;
184 my $barcode = $query->param('barcode');
185 my $exemptfine = $query->param('exemptfine');
186 if (
187 $exemptfine &&
188 !C4::Auth::haspermission(C4::Context->userenv->{'id'}, {'updatecharges' => 'writeoff'})
190 # silently prevent unauthorized operator from forgiving overdue
191 # fines by manually tweaking form parameters
192 undef $exemptfine;
194 my $dropboxmode = $query->param('dropboxmode');
195 my $dotransfer = $query->param('dotransfer');
196 my $canceltransfer = $query->param('canceltransfer');
197 my $dest = $query->param('dest');
198 #dropbox: get last open day (today - 1)
199 my $dropboxdate = Koha::Checkouts::calculate_dropbox_date();
201 my $return_date_override = $query->param('return_date_override');
202 my $return_date_override_dt;
203 my $return_date_override_remember =
204 $query->param('return_date_override_remember');
205 if ($return_date_override) {
206 if ( C4::Context->preference('SpecifyReturnDate') ) {
207 $return_date_override_dt = eval {dt_from_string( $return_date_override ) };
208 if ( $return_date_override_dt ) {
209 # note that we've overriden the return date
210 $template->param( return_date_was_overriden => 1);
211 # Save the original format if we are remembering for this series
212 $template->param(
213 return_date_override => $return_date_override,
214 return_date_override_remember => 1
215 ) if ($return_date_override_remember);
217 $return_date_override =
218 DateTime::Format::MySQL->format_datetime( $return_date_override_dt );
221 else {
222 $return_date_override = q{};
226 if ($dotransfer){
227 # An item has been returned to a branch other than the homebranch, and the librarian has chosen to initiate a transfer
228 my $transferitem = $query->param('transferitem');
229 my $tobranch = $query->param('tobranch');
230 my $trigger = $query->param('trigger');
231 ModItemTransfer($transferitem, $userenv_branch, $tobranch, $trigger);
234 if ($canceltransfer){
235 $itemnumber=$query->param('itemnumber');
236 DeleteTransfer($itemnumber);
237 if($dest eq "ttr"){
238 print $query->redirect("/cgi-bin/koha/circ/transferstoreceive.pl");
239 exit;
240 } else {
241 $template->param( transfercancelled => 1);
245 # actually return book and prepare item table.....
246 my $returnbranch;
247 if ($barcode) {
248 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
249 $barcode = barcodedecode($barcode) if C4::Context->preference('itemBarcodeInputFilter');
250 my $item = Koha::Items->find({ barcode => $barcode });
252 if ( $item ) {
253 $itemnumber = $item->itemnumber;
254 # Check if we should display a checkin message, based on the the item
255 # type of the checked in item
256 my $itemtype = Koha::ItemTypes->find( $item->effective_itemtype );
257 if ( $itemtype && $itemtype->checkinmsg ) {
258 $template->param(
259 checkinmsg => $itemtype->checkinmsg,
260 checkinmsgtype => $itemtype->checkinmsgtype,
264 # make sure return branch respects home branch circulation rules, default to homebranch
265 my $hbr = GetBranchItemRule($item->homebranch, $itemtype ? $itemtype->itemtype : undef )->{'returnbranch'} || "homebranch";
266 $returnbranch = $hbr ne 'noreturn' ? $item->$hbr : $userenv_branch; # can be noreturn, homebranch or holdingbranch
268 my $materials = $item->materials;
269 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield =>'items.materials', authorised_value => $materials });
270 $materials = $descriptions->{lib} // $materials;
272 my $checkout = $item->checkout;
273 my $biblio = $item->biblio;
274 $template->param(
275 title => $biblio->title,
276 homebranch => $item->homebranch,
277 holdingbranch => $item->holdingbranch,
278 returnbranch => $returnbranch,
279 author => $biblio->author,
280 itembarcode => $item->barcode,
281 itemtype => $item->effective_itemtype,
282 ccode => $item->ccode,
283 itembiblionumber => $biblio->biblionumber,
284 biblionumber => $biblio->biblionumber,
285 additional_materials => $materials,
286 issue => $checkout,
288 } # FIXME else we should not call AddReturn but set BadBarcode directly instead
290 my %input = (
291 counter => 0,
292 first => 1,
293 barcode => $barcode,
296 my $return_date = $dropboxmode ? $dropboxdate : $return_date_override_dt;
298 # do the return
299 ( $returned, $messages, $issue, $borrower ) =
300 AddReturn( $barcode, $userenv_branch, $exemptfine, $return_date );
302 if ($returned) {
303 my $time_now = dt_from_string()->truncate( to => 'minute');
304 my $date_due_dt = dt_from_string( $issue->date_due, 'sql' );
305 my $duedate = $date_due_dt->strftime('%Y-%m-%d %H:%M');
306 $returneditems{0} = $barcode;
307 $riborrowernumber{0} = $borrower->{'borrowernumber'};
308 $riduedate{0} = $duedate;
309 $input{borrowernumber} = $borrower->{'borrowernumber'};
310 $input{duedate} = $duedate;
311 unless ( $dropboxmode ) {
312 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, dt_from_string()) == -1);
313 } else {
314 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, $dropboxdate) == -1);
316 push( @inputloop, \%input );
318 if ( C4::Context->preference("FineNotifyAtCheckin") ) {
319 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
320 my $balance = $patron->account->balance;
322 if ($balance > 0) {
323 $template->param( fines => sprintf("%.2f", $balance) );
324 $template->param( fineborrowernumber => $borrower->{'borrowernumber'} );
328 if (C4::Context->preference("WaitingNotifyAtCheckin") ) {
329 #Check for waiting holds
330 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
331 my $waiting_holds = $patron->holds->search({ found => 'W', branchcode => $userenv_branch })->count;
332 if ($waiting_holds > 0) {
333 $template->param(
334 waiting_holds => $waiting_holds,
335 holdsborrowernumber => $borrower->{'borrowernumber'},
336 holdsfirstname => $borrower->{'firstname'},
337 holdssurname => $borrower->{'surname'},
341 } elsif ( C4::Context->preference('ShowAllCheckins') and !$messages->{'BadBarcode'} ) {
342 $input{duedate} = 0;
343 $returneditems{0} = $barcode;
344 $riduedate{0} = 0;
345 push( @inputloop, \%input );
347 $template->param( privacy => $borrower->{privacy} );
349 $template->param( inputloop => \@inputloop );
351 my $found = 0;
352 my $waiting = 0;
353 my $reserved = 0;
355 # new op dev : we check if the document must be returned to his homebranch directly,
356 # if the document is transferred, we have warning message .
358 if ( $messages->{'WasTransfered'} ) {
359 $template->param(
360 found => 1,
361 transfer => 1,
362 itemnumber => $itemnumber,
366 if ( $messages->{'NeedsTransfer'} ){
367 $template->param(
368 found => 1,
369 needstransfer => $messages->{'NeedsTransfer'},
370 trigger => $messages->{'TransferTrigger'},
371 itemnumber => $itemnumber,
375 if ( $messages->{'Wrongbranch'} ){
376 $template->param(
377 wrongbranch => 1,
378 rightbranch => $messages->{'Wrongbranch'}->{'Rightbranch'},
382 # case of wrong transfert, if the document wasn't transferred to the right library (according to branchtransfer (tobranch) BDD)
384 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
385 $template->param(
386 WrongTransfer => 1,
387 TransferWaitingAt => $messages->{'WrongTransfer'},
388 WrongTransferItem => $messages->{'WrongTransferItem'},
389 itemnumber => $itemnumber,
392 my $reserve = $messages->{'ResFound'};
393 if ( $reserve ) {
394 my $patron = Koha::Patrons->find( $reserve->{'borrowernumber'} );
395 my $name = $patron->surname . ", " . $patron->title . " " . $patron->firstname;
396 $template->param(
397 patron => $patron,
400 $template->param(
401 wtransfertFrom => $userenv_branch,
406 # reserve found and item arrived at the expected branch
408 if ( $messages->{'ResFound'}) {
409 my $reserve = $messages->{'ResFound'};
410 my $patron = Koha::Patrons->find( $reserve->{borrowernumber} );
411 my $holdmsgpreferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $reserve->{'borrowernumber'}, message_name => 'Hold_Filled' } );
412 my $branchCheck = ( $userenv_branch eq $reserve->{branchcode} );
413 if ( $reserve->{'ResFound'} eq "Reserved" && C4::Context->preference('HoldsAutoFill') ) {
414 my $item = Koha::Items->find( $itemnumber );
415 my $biblio = $item->biblio;
417 my $diffBranchSend = !$branchCheck ? $reserve->{branchcode} : undef;
418 ModReserveAffect( $reserve->{itemnumber}, $reserve->{borrowernumber}, $diffBranchSend, $reserve->{reserve_id} );
419 my ( $messages, $nextreservinfo ) = GetOtherReserves($reserve->{itemnumber});
420 $template->param(
421 hold_auto_filled => 1,
422 print_slip => C4::Context->preference('HoldsAutoFillPrintSlip'),
423 reserve_id => $nextreservinfo->{reserve_id},
426 if ( $messages->{'transfert'} ) {
427 $template->param(
428 itemtitle => $biblio->title,
429 itemnumber => $item->itemnumber,
430 itembiblionumber => $biblio->biblionumber,
431 iteminfo => $biblio->author,
432 diffbranch => 1,
436 elsif ( $reserve->{'ResFound'} eq "Waiting" or $reserve->{'ResFound'} eq "Reserved" ) {
437 if ( $reserve->{'ResFound'} eq "Waiting" ) {
438 $template->param(
439 waiting => $branchCheck ? 1 : undef,
441 } elsif ( $reserve->{'ResFound'} eq "Reserved" ) {
442 $template->param(
443 intransit => $branchCheck ? undef : 1,
444 transfertodo => $branchCheck ? undef : 1,
445 reserve_id => $reserve->{reserve_id},
446 reserved => 1,
450 } # else { ; } # error?
452 # same params for Waiting or Reserved
453 $template->param(
454 found => 1,
455 patron => $patron,
456 barcode => $barcode,
457 destbranch => $reserve->{'branchcode'},
458 itemnumber => $reserve->{'itemnumber'},
459 reservenotes => $reserve->{'reservenotes'},
460 reserve_id => $reserve->{reserve_id},
461 bormessagepref => $holdmsgpreferences->{'transports'},
465 # Error Messages
466 my @errmsgloop;
467 foreach my $code ( keys %$messages ) {
468 my %err;
469 my $exit_required_p = 0;
470 if ( $code eq 'BadBarcode' ) {
471 $err{badbarcode} = 1;
472 $err{msg} = $messages->{'BadBarcode'};
474 elsif ( $code eq 'NotIssued' ) {
475 $err{notissued} = 1;
476 $err{msg} = '';
478 elsif ( $code eq 'LocalUse' ) {
479 $err{localuse} = 1;
481 elsif ( $code eq 'WasLost' ) {
482 $err{waslost} = 1;
483 $exit_required_p = 1 if C4::Context->preference("BlockReturnOfLostItems");
485 elsif ( $code eq 'LostItemFeeRefunded' ) {
486 $template->param( LostItemFeeRefunded => 1 );
488 elsif ( $code eq 'ResFound' ) {
489 ; # FIXME... anything to do here?
491 elsif ( $code eq 'WasReturned' ) {
492 ; # FIXME... anything to do here?
494 elsif ( $code eq 'WasTransfered' ) {
495 ; # FIXME... anything to do here?
497 elsif ( $code eq 'withdrawn' ) {
498 $err{withdrawn} = 1;
499 $exit_required_p = 1 if C4::Context->preference("BlockReturnOfWithdrawnItems");
501 elsif ( $code eq 'WrongTransfer' ) {
502 ; # FIXME... anything to do here?
504 elsif ( $code eq 'WrongTransferItem' ) {
505 ; # FIXME... anything to do here?
507 elsif ( $code eq 'NeedsTransfer' ) {
509 elsif ( $code eq 'TransferTrigger' ) {
510 ; # Handled alongside NeedsTransfer
512 elsif ( $code eq 'Wrongbranch' ) {
514 elsif ( $code eq 'Debarred' ) {
515 $err{debarred} = $messages->{'Debarred'};
516 $err{debarcardnumber} = $borrower->{cardnumber};
517 $err{debarborrowernumber} = $borrower->{borrowernumber};
518 $err{debarname} = "$borrower->{firstname} $borrower->{surname}";
520 elsif ( $code eq 'PrevDebarred' ) {
521 $err{prevdebarred} = $messages->{'PrevDebarred'};
523 elsif ( $code eq 'ForeverDebarred' ) {
524 $err{foreverdebarred} = $messages->{'ForeverDebarred'};
526 elsif ( $code eq 'ItemLocationUpdated' ) {
527 $err{ItemLocationUpdated} = $messages->{ItemLocationUpdated};
529 elsif ( $code eq 'NotForLoanStatusUpdated' ) {
530 $err{NotForLoanStatusUpdated} = $messages->{NotForLoanStatusUpdated};
532 elsif ( $code eq 'DataCorrupted' ) {
533 $err{data_corrupted} = 1;
535 elsif ( $code eq 'ReturnClaims' ) {
536 $template->param( ReturnClaims => $messages->{ReturnClaims} );
537 } else {
538 die "Unknown error code $code"; # note we need all the (empty) elsif's above, or we die.
539 # This forces the issue of staying in sync w/ Circulation.pm
541 if (%err) {
542 push( @errmsgloop, \%err );
544 last if $exit_required_p;
546 $template->param( errmsgloop => \@errmsgloop );
548 #set up so only the last 8 returned items display (make for faster loading pages)
549 my $returned_counter = ( C4::Context->preference('numReturnedItemsToShow') ) ? C4::Context->preference('numReturnedItemsToShow') : 8;
550 my $count = 0;
551 my @riloop;
552 my $shelflocations =
553 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
554 foreach ( sort { $a <=> $b } keys %returneditems ) {
555 my %ri;
556 if ( $count++ < $returned_counter ) {
557 my $bar_code = $returneditems{$_};
558 if ($riduedate{$_}) {
559 my $duedate = dt_from_string( $riduedate{$_}, 'sql');
560 $ri{year} = $duedate->year();
561 $ri{month} = $duedate->month();
562 $ri{day} = $duedate->day();
563 $ri{hour} = $duedate->hour();
564 $ri{minute} = $duedate->minute();
565 $ri{duedate} = output_pref($duedate);
566 my $patron = Koha::Patrons->find( $riborrowernumber{$_} );
567 unless ( $dropboxmode ) {
568 $ri{return_overdue} = 1 if (DateTime->compare($duedate, dt_from_string()) == -1);
569 } else {
570 $ri{return_overdue} = 1 if (DateTime->compare($duedate, $dropboxdate) == -1);
572 $ri{patron} = $patron,
573 $ri{borissuescount} = $patron->checkouts->count;
575 else {
576 $ri{borrowernumber} = $riborrowernumber{$_};
579 my $item = Koha::Items->find({ barcode => $bar_code });
580 next unless $item; # FIXME The item has been deleted in the meantime,
581 # we could handle that better displaying a message in the template
583 my $biblio = $item->biblio;
584 # FIXME pass $item to the template and we are done here...
585 $ri{itembiblionumber} = $biblio->biblionumber;
586 $ri{itemtitle} = $biblio->title;
587 $ri{subtitle} = $biblio->subtitle;
588 $ri{part_name} = $biblio->part_name;
589 $ri{part_number} = $biblio->part_number;
590 $ri{itemauthor} = $biblio->author;
591 $ri{itemcallnumber} = $item->itemcallnumber;
592 $ri{dateaccessioned} = $item->dateaccessioned;
593 $ri{recordtype} = $biblio->itemtype;
594 $ri{itemtype} = $item->itype;
595 $ri{itemnote} = $item->itemnotes;
596 $ri{itemnotes_nonpublic} = $item->itemnotes_nonpublic;
597 $ri{ccode} = $item->ccode;
598 $ri{enumchron} = $item->enumchron;
599 $ri{itemnumber} = $item->itemnumber;
600 $ri{barcode} = $bar_code;
601 $ri{homebranch} = $item->homebranch;
602 $ri{holdingbranch} = $item->holdingbranch;
604 $ri{location} = $item->location;
605 my $shelfcode = $ri{'location'};
606 $ri{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
609 else {
610 last;
612 push @riloop, \%ri;
615 $template->param(
616 riloop => \@riloop,
617 errmsgloop => \@errmsgloop,
618 exemptfine => $exemptfine,
619 dropboxmode => $dropboxmode,
620 dropboxdate => $dropboxdate,
621 forgivemanualholdsexpire => $forgivemanualholdsexpire,
622 overduecharges => $overduecharges,
623 AudioAlerts => C4::Context->preference("AudioAlerts"),
626 if ( $barcode ) {
627 my $item_from_barcode = Koha::Items->find({barcode => $barcode }); # How many times do we fetch this item?!?
628 if ( $item_from_barcode ) {
629 $itemnumber = $item_from_barcode->itemnumber;
630 my ( $holdingBranch, $collectionBranch ) = GetCollectionItemBranches( $itemnumber );
631 if ( $holdingBranch and $collectionBranch ) {
632 $holdingBranch //= '';
633 $collectionBranch //= $returnbranch;
634 if ( ! ( $holdingBranch eq $collectionBranch ) ) {
635 $template->param(
636 collectionItemNeedsTransferred => 1,
637 collectionBranch => $collectionBranch,
638 itemnumber => $itemnumber,
645 # Checking if there is a Fast Cataloging Framework
646 $template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' );
648 # actually print the page!
649 output_html_with_http_headers $query, $cookie, $template->output;