Update release notes for 19.11.08 release
[koha.git] / circ / returns.pl
blob557fadc2747be2bf414300df1e2a5fa022c06f24
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::Biblio;
39 use C4::Circulation;
40 use C4::Context;
41 use C4::Items;
42 use C4::Koha; # FIXME : is it still useful ?
43 use C4::Members::Messaging;
44 use C4::Members;
45 use C4::Output;
46 use C4::Print;
47 use C4::Reserves;
48 use C4::RotatingCollections;
49 use Koha::AuthorisedValues;
50 use Koha::BiblioFrameworks;
51 use Koha::Calendar;
52 use Koha::Checkouts;
53 use Koha::DateUtils;
54 use Koha::Holds;
55 use Koha::Items;
56 use Koha::Patrons;
58 my $query = new CGI;
60 #getting the template
61 my ( $template, $librarian, $cookie, $flags ) = get_template_and_user(
63 template_name => "circ/returns.tt",
64 query => $query,
65 type => "intranet",
66 authnotrequired => 0,
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");
76 exit;
79 # Print a reserve slip on this page
80 if ( $query->param('print_slip') ) {
81 $template->param(
82 print_slip => 1,
83 reserve_id => scalar $query->param('reserve_id'),
87 #####################
88 #Global vars
89 my $printers = GetPrinters();
90 my $userenv = C4::Context->userenv;
91 my $userenv_branch = $userenv->{'branch'} // '';
92 my $printer = $userenv->{'branchprinter'} // '';
93 my $forgivemanualholdsexpire = $query->param('forgivemanualholdsexpire');
95 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') ne 'off');
97 # Some code to handle the error if there is no branch or printer setting.....
100 # Set up the item stack ....
101 my %returneditems;
102 my %riduedate;
103 my %riborrowernumber;
104 my @inputloop;
105 foreach ( $query->param ) {
106 my $counter;
107 if (/ri-(\d*)/) {
108 $counter = $1;
109 if ($counter > 20) {
110 next;
113 else {
114 next;
117 my %input;
118 my $barcode = $query->param("ri-$counter");
119 my $duedate = $query->param("dd-$counter");
120 my $borrowernumber = $query->param("bn-$counter");
121 $counter++;
123 # decode barcode ## Didn't we already decode them before passing them back last time??
124 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
125 $barcode = barcodedecode($barcode) if(C4::Context->preference('itemBarcodeInputFilter'));
127 ######################
128 #Are these lines still useful ?
129 $returneditems{$counter} = $barcode;
130 $riduedate{$counter} = $duedate;
131 $riborrowernumber{$counter} = $borrowernumber;
133 #######################
134 $input{counter} = $counter;
135 $input{barcode} = $barcode;
136 $input{duedate} = $duedate;
137 $input{borrowernumber} = $borrowernumber;
138 push( @inputloop, \%input );
141 ############
142 # Deal with the requests....
144 if ($query->param('WT-itemNumber')){
145 updateWrongTransfer ($query->param('WT-itemNumber'),$query->param('WT-waitingAt'),$query->param('WT-From'));
148 if ( $query->param('reserve_id') ) {
149 my $itemnumber = $query->param('itemnumber');
150 my $borrowernumber = $query->param('borrowernumber');
151 my $reserve_id = $query->param('reserve_id');
152 my $diffBranchReturned = $query->param('diffBranch');
153 my $cancel_reserve = $query->param('cancel_reserve');
154 # fix up item type for display
155 my $item = Koha::Items->find( $itemnumber );
156 my $biblio = $item->biblio;
158 if ( $cancel_reserve ) {
159 my $hold = Koha::Holds->find( $reserve_id );
160 if ( $hold ) {
161 $hold->cancel( { charge_cancel_fee => !$forgivemanualholdsexpire } );
162 } # FIXME else?
163 } else {
164 my $diffBranchSend = ($userenv_branch ne $diffBranchReturned) ? $diffBranchReturned : undef;
165 # diffBranchSend tells ModReserveAffect whether document is expected in this library or not,
166 # i.e., whether to apply waiting status
167 ModReserveAffect( $itemnumber, $borrowernumber, $diffBranchSend, $reserve_id );
169 # check if we have other reserves for this document, if we have a return send the message of transfer
170 my ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
172 my $patron = Koha::Patrons->find( $nextreservinfo );
173 my $name = $patron ? $patron->surname . ", " . $patron->title . " " . $patron->firstname : '';
174 if ( $messages->{'transfert'} ) {
175 $template->param(
176 itemtitle => $biblio->title,
177 itemnumber => $item->itemnumber,
178 itembiblionumber => $biblio->biblionumber,
179 iteminfo => $biblio->author,
180 name => $name,
181 patron => $patron,
182 diffbranch => 1,
187 my $borrower;
188 my $returned = 0;
189 my $messages;
190 my $issue;
191 my $itemnumber;
192 my $barcode = $query->param('barcode');
193 my $exemptfine = $query->param('exemptfine');
194 if (
195 $exemptfine &&
196 !C4::Auth::haspermission(C4::Context->userenv->{'id'}, {'updatecharges' => 'writeoff'})
198 # silently prevent unauthorized operator from forgiving overdue
199 # fines by manually tweaking form parameters
200 undef $exemptfine;
202 my $dropboxmode = $query->param('dropboxmode');
203 my $dotransfer = $query->param('dotransfer');
204 my $canceltransfer = $query->param('canceltransfer');
205 my $dest = $query->param('dest');
206 #dropbox: get last open day (today - 1)
207 my $dropboxdate = Koha::Checkouts::calculate_dropbox_date();
209 my $return_date_override = $query->param('return_date_override');
210 my $return_date_override_dt;
211 my $return_date_override_remember =
212 $query->param('return_date_override_remember');
213 if ($return_date_override) {
214 if ( C4::Context->preference('SpecifyReturnDate') ) {
215 $return_date_override_dt = eval {dt_from_string( $return_date_override ) };
216 if ( $return_date_override_dt ) {
217 # note that we've overriden the return date
218 $template->param( return_date_was_overriden => 1);
219 # Save the original format if we are remembering for this series
220 $template->param(
221 return_date_override => $return_date_override,
222 return_date_override_remember => 1
223 ) if ($return_date_override_remember);
225 $return_date_override =
226 DateTime::Format::MySQL->format_datetime( $return_date_override_dt );
229 else {
230 $return_date_override = q{};
234 if ($dotransfer){
235 # An item has been returned to a branch other than the homebranch, and the librarian has chosen to initiate a transfer
236 my $transferitem = $query->param('transferitem');
237 my $tobranch = $query->param('tobranch');
238 ModItemTransfer($transferitem, $userenv_branch, $tobranch);
241 if ($canceltransfer){
242 $itemnumber=$query->param('itemnumber');
243 DeleteTransfer($itemnumber);
244 if($dest eq "ttr"){
245 print $query->redirect("/cgi-bin/koha/circ/transferstoreceive.pl");
246 exit;
247 } else {
248 $template->param( transfercancelled => 1);
252 # actually return book and prepare item table.....
253 my $returnbranch;
254 if ($barcode) {
255 $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
256 $barcode = barcodedecode($barcode) if C4::Context->preference('itemBarcodeInputFilter');
257 my $item = Koha::Items->find({ barcode => $barcode });
259 if ( $item ) {
260 $itemnumber = $item->itemnumber;
261 # Check if we should display a checkin message, based on the the item
262 # type of the checked in item
263 my $itemtype = Koha::ItemTypes->find( $item->effective_itemtype );
264 if ( $itemtype && $itemtype->checkinmsg ) {
265 $template->param(
266 checkinmsg => $itemtype->checkinmsg,
267 checkinmsgtype => $itemtype->checkinmsgtype,
271 # make sure return branch respects home branch circulation rules, default to homebranch
272 my $hbr = GetBranchItemRule($item->homebranch, $itemtype ? $itemtype->itemtype : undef )->{'returnbranch'} || "homebranch";
273 $returnbranch = $hbr ne 'noreturn' ? $item->$hbr : $userenv_branch; # can be noreturn, homebranch or holdingbranch
275 my $materials = $item->materials;
276 my $descriptions = Koha::AuthorisedValues->get_description_by_koha_field({frameworkcode => '', kohafield =>'items.materials', authorised_value => $materials });
277 $materials = $descriptions->{lib} // $materials;
279 my $checkout = $item->checkout;
280 my $biblio = $item->biblio;
281 $template->param(
282 title => $biblio->title,
283 homebranch => $item->homebranch,
284 holdingbranch => $item->holdingbranch,
285 returnbranch => $returnbranch,
286 author => $biblio->author,
287 itembarcode => $item->barcode,
288 itemtype => $item->effective_itemtype,
289 ccode => $item->ccode,
290 itembiblionumber => $biblio->biblionumber,
291 biblionumber => $biblio->biblionumber,
292 additional_materials => $materials,
293 issue => $checkout,
295 } # FIXME else we should not call AddReturn but set BadBarcode directly instead
297 my %input = (
298 counter => 0,
299 first => 1,
300 barcode => $barcode,
303 my $return_date = $dropboxmode ? $dropboxdate : $return_date_override_dt;
305 # do the return
306 ( $returned, $messages, $issue, $borrower ) =
307 AddReturn( $barcode, $userenv_branch, $exemptfine, $return_date );
309 if ($returned) {
310 my $time_now = dt_from_string()->truncate( to => 'minute');
311 my $date_due_dt = dt_from_string( $issue->date_due, 'sql' );
312 my $duedate = $date_due_dt->strftime('%Y-%m-%d %H:%M');
313 $returneditems{0} = $barcode;
314 $riborrowernumber{0} = $borrower->{'borrowernumber'};
315 $riduedate{0} = $duedate;
316 $input{borrowernumber} = $borrower->{'borrowernumber'};
317 $input{duedate} = $duedate;
318 unless ( $dropboxmode ) {
319 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, dt_from_string()) == -1);
320 } else {
321 $input{return_overdue} = 1 if (DateTime->compare($date_due_dt, $dropboxdate) == -1);
323 push( @inputloop, \%input );
325 if ( C4::Context->preference("FineNotifyAtCheckin") ) {
326 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
327 my $balance = $patron->account->balance;
329 if ($balance > 0) {
330 $template->param( fines => sprintf("%.2f", $balance) );
331 $template->param( fineborrowernumber => $borrower->{'borrowernumber'} );
335 if (C4::Context->preference("WaitingNotifyAtCheckin") ) {
336 #Check for waiting holds
337 my $patron = Koha::Patrons->find( $borrower->{borrowernumber} );
338 my $waiting_holds = $patron->holds->search({ found => 'W', branchcode => $userenv_branch })->count;
339 if ($waiting_holds > 0) {
340 $template->param(
341 waiting_holds => $waiting_holds,
342 holdsborrowernumber => $borrower->{'borrowernumber'},
343 holdsfirstname => $borrower->{'firstname'},
344 holdssurname => $borrower->{'surname'},
348 } elsif ( C4::Context->preference('ShowAllCheckins') and !$messages->{'BadBarcode'} ) {
349 $input{duedate} = 0;
350 $returneditems{0} = $barcode;
351 $riduedate{0} = 0;
352 push( @inputloop, \%input );
354 $template->param( privacy => $borrower->{privacy} );
356 $template->param( inputloop => \@inputloop );
358 my $found = 0;
359 my $waiting = 0;
360 my $reserved = 0;
362 # new op dev : we check if the document must be returned to his homebranch directly,
363 # if the document is transferred, we have warning message .
365 if ( $messages->{'WasTransfered'} ) {
366 $template->param(
367 found => 1,
368 transfer => 1,
369 itemnumber => $itemnumber,
373 if ( $messages->{'NeedsTransfer'} ){
374 $template->param(
375 found => 1,
376 needstransfer => $messages->{'NeedsTransfer'},
377 itemnumber => $itemnumber,
381 if ( $messages->{'Wrongbranch'} ){
382 $template->param(
383 wrongbranch => 1,
384 rightbranch => $messages->{'Wrongbranch'}->{'Rightbranch'},
388 # case of wrong transfert, if the document wasn't transferred to the right library (according to branchtransfer (tobranch) BDD)
390 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
391 $template->param(
392 WrongTransfer => 1,
393 TransferWaitingAt => $messages->{'WrongTransfer'},
394 WrongTransferItem => $messages->{'WrongTransferItem'},
395 itemnumber => $itemnumber,
398 my $reserve = $messages->{'ResFound'};
399 if ( $reserve ) {
400 my $patron = Koha::Patrons->find( $reserve->{'borrowernumber'} );
401 my $name = $patron->surname . ", " . $patron->title . " " . $patron->firstname;
402 $template->param(
403 patron => $patron,
406 $template->param(
407 wtransfertFrom => $userenv_branch,
412 # reserve found and item arrived at the expected branch
414 if ( $messages->{'ResFound'}) {
415 my $reserve = $messages->{'ResFound'};
416 my $patron = Koha::Patrons->find( $reserve->{borrowernumber} );
417 my $holdmsgpreferences = C4::Members::Messaging::GetMessagingPreferences( { borrowernumber => $reserve->{'borrowernumber'}, message_name => 'Hold_Filled' } );
418 my $branchCheck = ( $userenv_branch eq $reserve->{branchcode} );
419 if ( $reserve->{'ResFound'} eq "Reserved" && C4::Context->preference('HoldsAutoFill') ) {
420 my $item = Koha::Items->find( $itemnumber );
421 my $biblio = $item->biblio;
423 my $diffBranchSend = !$branchCheck ? $reserve->{branchcode} : undef;
424 ModReserveAffect( $reserve->{itemnumber}, $reserve->{borrowernumber}, $diffBranchSend, $reserve->{reserve_id} );
425 my ( $messages, $nextreservinfo ) = GetOtherReserves($reserve->{itemnumber});
426 $template->param(
427 hold_auto_filled => 1,
428 print_slip => C4::Context->preference('HoldsAutoFillPrintSlip'),
429 reserve_id => $nextreservinfo->{reserve_id},
432 if ( $messages->{'transfert'} ) {
433 $template->param(
434 itemtitle => $biblio->title,
435 itemnumber => $item->itemnumber,
436 itembiblionumber => $biblio->biblionumber,
437 iteminfo => $biblio->author,
438 diffbranch => 1,
442 elsif ( $reserve->{'ResFound'} eq "Waiting" or $reserve->{'ResFound'} eq "Reserved" ) {
443 if ( $reserve->{'ResFound'} eq "Waiting" ) {
444 $template->param(
445 waiting => $branchCheck ? 1 : undef,
447 } elsif ( $reserve->{'ResFound'} eq "Reserved" ) {
448 $template->param(
449 intransit => $branchCheck ? undef : 1,
450 transfertodo => $branchCheck ? undef : 1,
451 reserve_id => $reserve->{reserve_id},
452 reserved => 1,
456 } # else { ; } # error?
458 # same params for Waiting or Reserved
459 $template->param(
460 found => 1,
461 patron => $patron,
462 barcode => $barcode,
463 destbranch => $reserve->{'branchcode'},
464 itemnumber => $reserve->{'itemnumber'},
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 'Wrongbranch' ) {
517 elsif ( $code eq 'Debarred' ) {
518 $err{debarred} = $messages->{'Debarred'};
519 $err{debarcardnumber} = $borrower->{cardnumber};
520 $err{debarborrowernumber} = $borrower->{borrowernumber};
521 $err{debarname} = "$borrower->{firstname} $borrower->{surname}";
523 elsif ( $code eq 'PrevDebarred' ) {
524 $err{prevdebarred} = $messages->{'PrevDebarred'};
526 elsif ( $code eq 'ForeverDebarred' ) {
527 $err{foreverdebarred} = $messages->{'ForeverDebarred'};
529 elsif ( $code eq 'ItemLocationUpdated' ) {
530 $err{ItemLocationUpdated} = $messages->{ItemLocationUpdated};
532 elsif ( $code eq 'NotForLoanStatusUpdated' ) {
533 $err{NotForLoanStatusUpdated} = $messages->{NotForLoanStatusUpdated};
535 elsif ( $code eq 'DataCorrupted' ) {
536 $err{data_corrupted} = 1;
538 elsif ( $code eq 'ReturnClaims' ) {
539 $template->param( ReturnClaims => $messages->{ReturnClaims} );
540 } else {
541 die "Unknown error code $code"; # note we need all the (empty) elsif's above, or we die.
542 # This forces the issue of staying in sync w/ Circulation.pm
544 if (%err) {
545 push( @errmsgloop, \%err );
547 last if $exit_required_p;
549 $template->param( errmsgloop => \@errmsgloop );
551 #set up so only the last 8 returned items display (make for faster loading pages)
552 my $returned_counter = ( C4::Context->preference('numReturnedItemsToShow') ) ? C4::Context->preference('numReturnedItemsToShow') : 8;
553 my $count = 0;
554 my @riloop;
555 my $shelflocations =
556 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => '', kohafield => 'items.location' } ) };
557 foreach ( sort { $a <=> $b } keys %returneditems ) {
558 my %ri;
559 if ( $count++ < $returned_counter ) {
560 my $bar_code = $returneditems{$_};
561 if ($riduedate{$_}) {
562 my $duedate = dt_from_string( $riduedate{$_}, 'sql');
563 $ri{year} = $duedate->year();
564 $ri{month} = $duedate->month();
565 $ri{day} = $duedate->day();
566 $ri{hour} = $duedate->hour();
567 $ri{minute} = $duedate->minute();
568 $ri{duedate} = output_pref($duedate);
569 my $patron = Koha::Patrons->find( $riborrowernumber{$_} );
570 unless ( $dropboxmode ) {
571 $ri{return_overdue} = 1 if (DateTime->compare($duedate, dt_from_string()) == -1);
572 } else {
573 $ri{return_overdue} = 1 if (DateTime->compare($duedate, $dropboxdate) == -1);
575 $ri{patron} = $patron,
576 $ri{borissuescount} = $patron->checkouts->count;
578 else {
579 $ri{borrowernumber} = $riborrowernumber{$_};
582 my $item = Koha::Items->find({ barcode => $bar_code });
583 next unless $item; # FIXME The item has been deleted in the meantime,
584 # we could handle that better displaying a message in the template
586 my $biblio = $item->biblio;
587 # FIXME pass $item to the template and we are done here...
588 $ri{itembiblionumber} = $biblio->biblionumber;
589 $ri{itemtitle} = $biblio->title;
590 $ri{subtitle} = $biblio->subtitle;
591 $ri{part_name} = $biblio->part_name;
592 $ri{part_number} = $biblio->part_number;
593 $ri{itemauthor} = $biblio->author;
594 $ri{itemcallnumber} = $item->itemcallnumber;
595 $ri{dateaccessioned} = $item->dateaccessioned;
596 $ri{recordtype} = $biblio->itemtype;
597 $ri{itemtype} = $item->itype;
598 $ri{itemnote} = $item->itemnotes;
599 $ri{itemnotes_nonpublic} = $item->itemnotes_nonpublic;
600 $ri{ccode} = $item->ccode;
601 $ri{enumchron} = $item->enumchron;
602 $ri{itemnumber} = $item->itemnumber;
603 $ri{barcode} = $bar_code;
604 $ri{homebranch} = $item->homebranch;
605 $ri{holdingbranch} = $item->holdingbranch;
607 $ri{location} = $item->location;
608 my $shelfcode = $ri{'location'};
609 $ri{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
612 else {
613 last;
615 push @riloop, \%ri;
618 $template->param(
619 riloop => \@riloop,
620 printer => $printer,
621 errmsgloop => \@errmsgloop,
622 exemptfine => $exemptfine,
623 dropboxmode => $dropboxmode,
624 dropboxdate => $dropboxdate,
625 forgivemanualholdsexpire => $forgivemanualholdsexpire,
626 overduecharges => $overduecharges,
627 AudioAlerts => C4::Context->preference("AudioAlerts"),
630 if ( $barcode ) {
631 my $item_from_barcode = Koha::Items->find({barcode => $barcode }); # How many times do we fetch this item?!?
632 if ( $item_from_barcode ) {
633 $itemnumber = $item_from_barcode->itemnumber;
634 my ( $holdingBranch, $collectionBranch ) = GetCollectionItemBranches( $itemnumber );
635 if ( $holdingBranch and $collectionBranch ) {
636 $holdingBranch //= '';
637 $collectionBranch //= $returnbranch;
638 if ( ! ( $holdingBranch eq $collectionBranch ) ) {
639 $template->param(
640 collectionItemNeedsTransferred => 1,
641 collectionBranch => $collectionBranch,
642 itemnumber => $itemnumber,
649 # Checking if there is a Fast Cataloging Framework
650 $template->param( fast_cataloging => 1 ) if Koha::BiblioFrameworks->find( 'FA' );
652 # actually print the page!
653 output_html_with_http_headers $query, $cookie, $template->output;