Bug 26145: (QA follow-up) Add missing filters
[koha.git] / circ / returns.pl
blob6c9718495b13cbe5cdf5e8b4c4283fc18823e02e
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 flagsrequired => { circulate => "circulate_remaining_permissions" },
72 my $sessionID = $query->cookie("CGISESSID");
73 my $session = get_session($sessionID);
75 # Print a reserve slip on this page
76 if ( $query->param('print_slip') ) {
77 $template->param(
78 print_slip => 1,
79 reserve_id => scalar $query->param('reserve_id'),
83 #####################
84 #Global vars
85 my $userenv = C4::Context->userenv;
86 my $userenv_branch = $userenv->{'branch'} // '';
87 my $forgivemanualholdsexpire = $query->param('forgivemanualholdsexpire');
89 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') ne 'off');
91 # Set up the item stack ....
92 my %returneditems;
93 my %riduedate;
94 my %riborrowernumber;
95 my @inputloop;
96 foreach ( $query->param ) {
97 my $counter;
98 if (/ri-(\d*)/) {
99 $counter = $1;
100 if ($counter > 20) {
101 next;
104 else {
105 next;
108 my %input;
109 my $barcode = $query->param("ri-$counter");
110 my $duedate = $query->param("dd-$counter");
111 my $borrowernumber = $query->param("bn-$counter");
112 $counter++;
114 # decode barcode ## Didn't we already decode them before passing them back last time??
115 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
116 $barcode = barcodedecode($barcode) if(C4::Context->preference('itemBarcodeInputFilter'));
118 ######################
119 #Are these lines still useful ?
120 $returneditems{$counter} = $barcode;
121 $riduedate{$counter} = $duedate;
122 $riborrowernumber{$counter} = $borrowernumber;
124 #######################
125 $input{counter} = $counter;
126 $input{barcode} = $barcode;
127 $input{duedate} = $duedate;
128 $input{borrowernumber} = $borrowernumber;
129 push( @inputloop, \%input );
132 ############
133 # Deal with the requests....
135 if ($query->param('WT-itemNumber')){
136 updateWrongTransfer ($query->param('WT-itemNumber'),$query->param('WT-waitingAt'),$query->param('WT-From'));
139 my $itemnumber = $query->param('itemnumber');
140 if ( $query->param('reserve_id') ) {
141 my $borrowernumber = $query->param('borrowernumber');
142 my $reserve_id = $query->param('reserve_id');
143 my $diffBranchReturned = $query->param('diffBranch');
144 my $cancel_reserve = $query->param('cancel_reserve');
145 # fix up item type for display
146 my $item = Koha::Items->find( $itemnumber );
147 my $biblio = $item->biblio;
149 if ( $cancel_reserve ) {
150 my $hold = Koha::Holds->find( $reserve_id );
151 if ( $hold ) {
152 $hold->cancel( { charge_cancel_fee => !$forgivemanualholdsexpire } );
153 } # FIXME else?
154 } else {
155 my $diffBranchSend = ($userenv_branch ne $diffBranchReturned) ? $diffBranchReturned : undef;
156 # diffBranchSend tells ModReserveAffect whether document is expected in this library or not,
157 # i.e., whether to apply waiting status
158 ModReserveAffect( $itemnumber, $borrowernumber, $diffBranchSend, $reserve_id );
160 # check if we have other reserves for this document, if we have a return send the message of transfer
161 my ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
163 my $patron = Koha::Patrons->find( $nextreservinfo );
164 my $name = $patron ? $patron->surname . ", " . $patron->title . " " . $patron->firstname : '';
165 if ( $messages->{'transfert'} ) {
166 $template->param(
167 itemtitle => $biblio->title,
168 itembiblionumber => $biblio->biblionumber,
169 iteminfo => $biblio->author,
170 name => $name,
171 patron => $patron,
172 diffbranch => 1,
177 my $borrower;
178 my $returned = 0;
179 my $messages;
180 my $issue;
181 my $barcode = $query->param('barcode');
182 my $exemptfine = $query->param('exemptfine');
183 if (
184 $exemptfine &&
185 !C4::Auth::haspermission(C4::Context->userenv->{'id'}, {'updatecharges' => 'writeoff'})
187 # silently prevent unauthorized operator from forgiving overdue
188 # fines by manually tweaking form parameters
189 undef $exemptfine;
191 my $dropboxmode = $query->param('dropboxmode');
192 my $dotransfer = $query->param('dotransfer');
193 my $canceltransfer = $query->param('canceltransfer');
194 my $dest = $query->param('dest');
195 #dropbox: get last open day (today - 1)
196 my $dropboxdate = Koha::Checkouts::calculate_dropbox_date();
198 my $return_date_override = $query->param('return_date_override');
199 my $return_date_override_dt;
200 my $return_date_override_remember =
201 $query->param('return_date_override_remember');
202 if ($return_date_override) {
203 if ( C4::Context->preference('SpecifyReturnDate') ) {
204 $return_date_override_dt = eval {dt_from_string( $return_date_override ) };
205 if ( $return_date_override_dt ) {
206 # note that we've overriden the return date
207 $template->param( return_date_was_overriden => 1);
208 # Save the original format if we are remembering for this series
209 $template->param(
210 return_date_override => $return_date_override,
211 return_date_override_remember => 1
212 ) if ($return_date_override_remember);
214 $return_date_override =
215 DateTime::Format::MySQL->format_datetime( $return_date_override_dt );
218 else {
219 $return_date_override = q{};
223 if ($dotransfer){
224 # An item has been returned to a branch other than the homebranch, and the librarian has chosen to initiate a transfer
225 my $transferitem = $query->param('transferitem');
226 my $tobranch = $query->param('tobranch');
227 my $trigger = $query->param('trigger');
228 ModItemTransfer($transferitem, $userenv_branch, $tobranch, $trigger);
231 if ($canceltransfer){
232 DeleteTransfer($itemnumber);
233 if($dest eq "ttr"){
234 print $query->redirect("/cgi-bin/koha/circ/transferstoreceive.pl");
235 exit;
236 } else {
237 $template->param( transfercancelled => 1);
241 # actually return book and prepare item table.....
242 my $returnbranch;
243 if ($barcode) {
244 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
245 $barcode = barcodedecode($barcode) if C4::Context->preference('itemBarcodeInputFilter');
246 my $item = Koha::Items->find({ barcode => $barcode });
248 if ( $item ) {
249 $itemnumber = $item->itemnumber;
250 # Check if we should display a checkin message, based on the the item
251 # type of the checked in item
252 my $itemtype = Koha::ItemTypes->find( $item->effective_itemtype );
253 if ( $itemtype && $itemtype->checkinmsg ) {
254 $template->param(
255 checkinmsg => $itemtype->checkinmsg,
256 checkinmsgtype => $itemtype->checkinmsgtype,
260 # make sure return branch respects home branch circulation rules, default to homebranch
261 my $hbr = GetBranchItemRule($item->homebranch, $itemtype ? $itemtype->itemtype : undef )->{'returnbranch'} || "homebranch";
262 $returnbranch = $hbr ne 'noreturn' ? $item->$hbr : $userenv_branch; # can be noreturn, homebranch or holdingbranch
264 my $materials = $item->materials;
265 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield =>'items.materials', authorised_value => $materials });
266 $materials = $descriptions->{lib} // $materials;
268 my $checkout = $item->checkout;
269 my $biblio = $item->biblio;
270 $template->param(
271 title => $biblio->title,
272 homebranch => $item->homebranch,
273 holdingbranch => $item->holdingbranch,
274 returnbranch => $returnbranch,
275 author => $biblio->author,
276 itembarcode => $item->barcode,
277 itemtype => $item->effective_itemtype,
278 ccode => $item->ccode,
279 itembiblionumber => $biblio->biblionumber,
280 biblionumber => $biblio->biblionumber,
281 additional_materials => $materials,
282 issue => $checkout,
284 } # FIXME else we should not call AddReturn but set BadBarcode directly instead
286 my %input = (
287 counter => 0,
288 first => 1,
289 barcode => $barcode,
292 my $return_date = $dropboxmode ? $dropboxdate : $return_date_override_dt;
294 # Block return if multi-part and confirm has not been received
295 my $needs_confirm =
296 C4::Context->preference("CircConfirmItemParts")
297 && $item
298 && $item->materials
299 && !$query->param('multiple_confirm');
300 $template->param( 'multiple_confirmed' => 1 )
301 if $query->param('multiple_confirm');
303 # do the return
304 ( $returned, $messages, $issue, $borrower ) =
305 AddReturn( $barcode, $userenv_branch, $exemptfine, $return_date )
306 unless $needs_confirm;
308 if ($returned) {
309 my $time_now = dt_from_string()->truncate( to => 'minute');
310 my $date_due_dt = dt_from_string( $issue->date_due, 'sql' );
311 my $duedate = $date_due_dt->strftime('%Y-%m-%d %H:%M');
312 $returneditems{0} = $barcode;
313 $riborrowernumber{0} = $borrower->{'borrowernumber'};
314 $riduedate{0} = $duedate;
315 $input{borrowernumber} = $borrower->{'borrowernumber'};
316 $input{duedate} = $duedate;
317 unless ( $dropboxmode ) {
318 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, dt_from_string()) == -1);
319 } else {
320 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, $dropboxdate) == -1);
322 push( @inputloop, \%input );
324 if ( C4::Context->preference("FineNotifyAtCheckin") ) {
325 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
326 my $balance = $patron->account->balance;
328 if ($balance > 0) {
329 $template->param( fines => sprintf("%.2f", $balance) );
330 $template->param( fineborrowernumber => $borrower->{'borrowernumber'} );
334 if (C4::Context->preference("WaitingNotifyAtCheckin") ) {
335 #Check for waiting holds
336 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
337 my $waiting_holds = $patron->holds->search({ found => 'W', branchcode => $userenv_branch })->count;
338 if ($waiting_holds > 0) {
339 $template->param(
340 waiting_holds => $waiting_holds,
341 holdsborrowernumber => $borrower->{'borrowernumber'},
342 holdsfirstname => $borrower->{'firstname'},
343 holdssurname => $borrower->{'surname'},
347 } elsif ( C4::Context->preference('ShowAllCheckins') and !$messages->{'BadBarcode'} and !$needs_confirm ) {
348 $input{duedate} = 0;
349 $returneditems{0} = $barcode;
350 $riduedate{0} = 0;
351 push( @inputloop, \%input );
353 $template->param( privacy => $borrower->{privacy} );
355 if ( $needs_confirm ) {
356 $template->param( needs_confirm => $needs_confirm );
359 $template->param( inputloop => \@inputloop );
361 my $found = 0;
362 my $waiting = 0;
363 my $reserved = 0;
365 # new op dev : we check if the document must be returned to his homebranch directly,
366 # if the document is transferred, we have warning message .
368 if ( $messages->{'WasTransfered'} ) {
369 $template->param(
370 found => 1,
371 transfer => 1,
375 if ( $messages->{'NeedsTransfer'} ){
376 $template->param(
377 found => 1,
378 needstransfer => $messages->{'NeedsTransfer'},
379 trigger => $messages->{'TransferTrigger'},
383 if ( $messages->{'Wrongbranch'} ){
384 $template->param(
385 wrongbranch => 1,
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'}) {
393 $template->param(
394 WrongTransfer => 1,
395 TransferWaitingAt => $messages->{'WrongTransfer'},
396 WrongTransferItem => $messages->{'WrongTransferItem'},
399 my $reserve = $messages->{'ResFound'};
400 if ( $reserve ) {
401 my $patron = Koha::Patrons->find( $reserve->{'borrowernumber'} );
402 my $name = $patron->surname . ", " . $patron->title . " " . $patron->firstname;
403 $template->param(
404 patron => $patron,
407 $template->param(
408 wtransfertFrom => $userenv_branch,
413 # reserve found and item arrived at the expected branch
415 if ( $messages->{'ResFound'}) {
416 my $reserve = $messages->{'ResFound'};
417 my $patron = Koha::Patrons->find( $reserve->{borrowernumber} );
418 my $holdmsgpreferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $reserve->{'borrowernumber'}, message_name => 'Hold_Filled' } );
419 my $branchCheck = ( $userenv_branch eq $reserve->{branchcode} );
420 if ( $reserve->{'ResFound'} eq "Reserved" && C4::Context->preference('HoldsAutoFill') ) {
421 my $item = Koha::Items->find( $itemnumber );
422 my $biblio = $item->biblio;
424 my $diffBranchSend = !$branchCheck ? $reserve->{branchcode} : undef;
425 ModReserveAffect( $reserve->{itemnumber}, $reserve->{borrowernumber}, $diffBranchSend, $reserve->{reserve_id} );
426 my ( $messages, $nextreservinfo ) = GetOtherReserves($reserve->{itemnumber});
428 $template->param(
429 hold_auto_filled => 1,
430 print_slip => C4::Context->preference('HoldsAutoFillPrintSlip'),
431 reserve_id => $nextreservinfo->{reserve_id},
434 if ( $messages->{'transfert'} ) {
435 $template->param(
436 itemtitle => $biblio->title,
437 itembiblionumber => $biblio->biblionumber,
438 iteminfo => $biblio->author,
439 diffbranch => 1,
443 elsif ( $reserve->{'ResFound'} eq "Waiting" or $reserve->{'ResFound'} eq "Reserved" ) {
444 if ( $reserve->{'ResFound'} eq "Waiting" ) {
445 $template->param(
446 waiting => $branchCheck ? 1 : undef,
448 } elsif ( $reserve->{'ResFound'} eq "Reserved" ) {
449 $template->param(
450 intransit => $branchCheck ? undef : 1,
451 transfertodo => $branchCheck ? undef : 1,
452 reserve_id => $reserve->{reserve_id},
453 reserved => 1,
457 } # else { ; } # error?
459 # same params for Waiting or Reserved
460 $template->param(
461 found => 1,
462 patron => $patron,
463 barcode => $barcode,
464 destbranch => $reserve->{'branchcode'},
465 reservenotes => $reserve->{'reservenotes'},
466 reserve_id => $reserve->{reserve_id},
467 bormessagepref => $holdmsgpreferences->{'transports'},
471 # Error Messages
472 my @errmsgloop;
473 foreach my $code ( keys %$messages ) {
474 my %err;
475 my $exit_required_p = 0;
476 if ( $code eq 'BadBarcode' ) {
477 $err{badbarcode} = 1;
478 $err{msg} = $messages->{'BadBarcode'};
480 elsif ( $code eq 'NotIssued' ) {
481 $err{notissued} = 1;
482 $err{msg} = '';
484 elsif ( $code eq 'LocalUse' ) {
485 $err{localuse} = 1;
487 elsif ( $code eq 'WasLost' ) {
488 $err{waslost} = 1;
489 $exit_required_p = 1 if C4::Context->preference("BlockReturnOfLostItems");
491 elsif ( $code eq 'LostItemFeeRefunded' ) {
492 $template->param( LostItemFeeRefunded => 1 );
494 elsif ( $code eq 'ResFound' ) {
495 ; # FIXME... anything to do here?
497 elsif ( $code eq 'WasReturned' ) {
498 ; # FIXME... anything to do here?
500 elsif ( $code eq 'WasTransfered' ) {
501 ; # FIXME... anything to do here?
503 elsif ( $code eq 'withdrawn' ) {
504 $err{withdrawn} = 1;
505 $exit_required_p = 1 if C4::Context->preference("BlockReturnOfWithdrawnItems");
507 elsif ( $code eq 'WrongTransfer' ) {
508 ; # FIXME... anything to do here?
510 elsif ( $code eq 'WrongTransferItem' ) {
511 ; # FIXME... anything to do here?
513 elsif ( $code eq 'NeedsTransfer' ) {
515 elsif ( $code eq 'TransferTrigger' ) {
516 ; # Handled alongside NeedsTransfer
518 elsif ( $code eq 'Wrongbranch' ) {
520 elsif ( $code eq 'Debarred' ) {
521 $err{debarred} = $messages->{'Debarred'};
522 $err{debarcardnumber} = $borrower->{cardnumber};
523 $err{debarborrowernumber} = $borrower->{borrowernumber};
524 $err{debarname} = "$borrower->{firstname} $borrower->{surname}";
526 elsif ( $code eq 'PrevDebarred' ) {
527 $err{prevdebarred} = $messages->{'PrevDebarred'};
529 elsif ( $code eq 'ForeverDebarred' ) {
530 $err{foreverdebarred} = $messages->{'ForeverDebarred'};
532 elsif ( $code eq 'ItemLocationUpdated' ) {
533 $err{ItemLocationUpdated} = $messages->{ItemLocationUpdated};
535 elsif ( $code eq 'NotForLoanStatusUpdated' ) {
536 $err{NotForLoanStatusUpdated} = $messages->{NotForLoanStatusUpdated};
538 elsif ( $code eq 'DataCorrupted' ) {
539 $err{data_corrupted} = 1;
541 elsif ( $code eq 'ReturnClaims' ) {
542 $template->param( ReturnClaims => $messages->{ReturnClaims} );
543 } else {
544 die "Unknown error code $code"; # note we need all the (empty) elsif's above, or we die.
545 # This forces the issue of staying in sync w/ Circulation.pm
547 if (%err) {
548 push( @errmsgloop, \%err );
550 last if $exit_required_p;
552 $template->param( errmsgloop => \@errmsgloop );
554 #set up so only the last 8 returned items display (make for faster loading pages)
555 my $returned_counter = ( C4::Context->preference('numReturnedItemsToShow') ) ? C4::Context->preference('numReturnedItemsToShow') : 8;
556 my $count = 0;
557 my @riloop;
558 my $shelflocations =
559 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
560 foreach ( sort { $a <=> $b } keys %returneditems ) {
561 my %ri;
562 if ( $count++ < $returned_counter ) {
563 my $bar_code = $returneditems{$_};
564 if ($riduedate{$_}) {
565 my $duedate = dt_from_string( $riduedate{$_}, 'sql');
566 $ri{year} = $duedate->year();
567 $ri{month} = $duedate->month();
568 $ri{day} = $duedate->day();
569 $ri{hour} = $duedate->hour();
570 $ri{minute} = $duedate->minute();
571 $ri{duedate} = output_pref($duedate);
572 my $patron = Koha::Patrons->find( $riborrowernumber{$_} );
573 unless ( $dropboxmode ) {
574 $ri{return_overdue} = 1 if (DateTime->compare($duedate, dt_from_string()) == -1);
575 } else {
576 $ri{return_overdue} = 1 if (DateTime->compare($duedate, $dropboxdate) == -1);
578 $ri{patron} = $patron,
579 $ri{borissuescount} = $patron->checkouts->count;
581 else {
582 $ri{borrowernumber} = $riborrowernumber{$_};
585 my $item = Koha::Items->find({ barcode => $bar_code });
586 next unless $item; # FIXME The item has been deleted in the meantime,
587 # we could handle that better displaying a message in the template
589 my $biblio = $item->biblio;
590 # FIXME pass $item to the template and we are done here...
591 $ri{itembiblionumber} = $biblio->biblionumber;
592 $ri{itemtitle} = $biblio->title;
593 $ri{subtitle} = $biblio->subtitle;
594 $ri{part_name} = $biblio->part_name;
595 $ri{part_number} = $biblio->part_number;
596 $ri{itemauthor} = $biblio->author;
597 $ri{itemcallnumber} = $item->itemcallnumber;
598 $ri{dateaccessioned} = $item->dateaccessioned;
599 $ri{recordtype} = $biblio->itemtype;
600 $ri{itemtype} = $item->itype;
601 $ri{itemnote} = $item->itemnotes;
602 $ri{itemnotes_nonpublic} = $item->itemnotes_nonpublic;
603 $ri{ccode} = $item->ccode;
604 $ri{enumchron} = $item->enumchron;
605 $ri{itemnumber} = $item->itemnumber;
606 $ri{barcode} = $bar_code;
607 $ri{homebranch} = $item->homebranch;
608 $ri{holdingbranch} = $item->holdingbranch;
610 $ri{location} = $item->location;
611 my $shelfcode = $ri{'location'};
612 $ri{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
615 else {
616 last;
618 push @riloop, \%ri;
621 $template->param(
622 riloop => \@riloop,
623 errmsgloop => \@errmsgloop,
624 exemptfine => $exemptfine,
625 dropboxmode => $dropboxmode,
626 dropboxdate => $dropboxdate,
627 forgivemanualholdsexpire => $forgivemanualholdsexpire,
628 overduecharges => $overduecharges,
629 AudioAlerts => C4::Context->preference("AudioAlerts"),
632 if ( $barcode ) {
633 my $item_from_barcode = Koha::Items->find({barcode => $barcode }); # How many times do we fetch this item?!?
634 if ( $item_from_barcode ) {
635 $itemnumber = $item_from_barcode->itemnumber;
636 my ( $holdingBranch, $collectionBranch ) = GetCollectionItemBranches( $itemnumber );
637 if ( $holdingBranch and $collectionBranch ) {
638 $holdingBranch //= '';
639 $collectionBranch //= $returnbranch;
640 if ( ! ( $holdingBranch eq $collectionBranch ) ) {
641 $template->param(
642 collectionItemNeedsTransferred => 1,
643 collectionBranch => $collectionBranch,
650 $template->param( 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;