Bug 11182: get rid of some warnings in circulation
[koha.git] / circ / returns.pl
1 #!/usr/bin/perl
2
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.
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it under the
12 # terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 2 of the License, or (at your option) any later
14 # version.
15 #
16 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
17 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License along
21 # with Koha; if not, write to the Free Software Foundation, Inc.,
22 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23
24 =head1 returns.pl
25
26 script to execute returns of books
27
28 =cut
29
30 use strict;
31 use warnings;
32
33 use CGI;
34 use DateTime;
35 use C4::Context;
36 use C4::Auth qw/:DEFAULT get_session/;
37 use C4::Output;
38 use C4::Circulation;
39 use C4::Print;
40 use C4::Reserves;
41 use C4::Biblio;
42 use C4::Items;
43 use C4::Members;
44 use C4::Branch; # GetBranches GetBranchName
45 use C4::Koha;   # FIXME : is it still useful ?
46 use C4::RotatingCollections;
47 use Koha::DateUtils;
48 use Koha::Calendar;
49
50 my $query = new CGI;
51
52 my $userenv = C4::Context->userenv;
53 if (!$userenv){
54     my $sessionID = $query->cookie("CGISESSID");
55     my $session = get_session($sessionID);
56     if ($session->param('branch') eq 'NO_LIBRARY_SET'){
57         # no branch set we can't return
58         print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
59         exit;
60     }
61
62
63 #getting the template
64 my ( $template, $librarian, $cookie ) = get_template_and_user(
65     {
66         template_name   => "circ/returns.tmpl",
67         query           => $query,
68         type            => "intranet",
69         authnotrequired => 0,
70         flagsrequired   => { circulate => "circulate_remaining_permissions" },
71     }
72 );
73
74 #####################
75 #Global vars
76 my $branches = GetBranches();
77 my $printers = GetPrinters();
78 my $userenv_branch = $userenv->{'branch'} // '';
79 my $printer = $userenv->{'branchprinter'} // '';
80
81 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') ne 'off');
82 #
83 # Some code to handle the error if there is no branch or printer setting.....
84 #
85
86 # Set up the item stack ....
87 my %returneditems;
88 my %riduedate;
89 my %riborrowernumber;
90 my @inputloop;
91 foreach ( $query->param ) {
92     my $counter;
93     if (/ri-(\d*)/) {
94         $counter = $1;
95         if ($counter > 20) {
96             next;
97         }
98     }
99     else {
100         next;
101     }
102
103     my %input;
104     my $barcode        = $query->param("ri-$counter");
105     my $duedate        = $query->param("dd-$counter");
106     my $borrowernumber = $query->param("bn-$counter");
107     $counter++;
108
109     # decode barcode    ## Didn't we already decode them before passing them back last time??
110     $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
111     $barcode = barcodedecode($barcode) if(C4::Context->preference('itemBarcodeInputFilter'));
112
113     ######################
114     #Are these lines still useful ?
115     $returneditems{$counter}    = $barcode;
116     $riduedate{$counter}        = $duedate;
117     $riborrowernumber{$counter} = $borrowernumber;
118
119     #######################
120     $input{counter}        = $counter;
121     $input{barcode}        = $barcode;
122     $input{duedate}        = $duedate;
123     $input{borrowernumber} = $borrowernumber;
124     push( @inputloop, \%input );
125 }
126
127 ############
128 # Deal with the requests....
129
130 if ($query->param('WT-itemNumber')){
131         updateWrongTransfer ($query->param('WT-itemNumber'),$query->param('WT-waitingAt'),$query->param('WT-From'));
132 }
133
134 if ( $query->param('resbarcode') ) {
135     my $item           = $query->param('itemnumber');
136     my $borrowernumber = $query->param('borrowernumber');
137     my $resbarcode     = $query->param('resbarcode');
138     my $diffBranchReturned = $query->param('diffBranch');
139     my $iteminfo   = GetBiblioFromItemNumber($item);
140     # fix up item type for display
141     $iteminfo->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $iteminfo->{'itype'} : $iteminfo->{'itemtype'};
142     my $diffBranchSend = ($userenv_branch ne $diffBranchReturned) ? $diffBranchReturned : undef;
143 # diffBranchSend tells ModReserveAffect whether document is expected in this library or not,
144 # i.e., whether to apply waiting status
145     ModReserveAffect( $item, $borrowernumber, $diffBranchSend);
146 #   check if we have other reserves for this document, if we have a return send the message of transfer
147     my ( $messages, $nextreservinfo ) = GetOtherReserves($item);
148
149     my ($borr) = GetMemberDetails( $nextreservinfo, 0 );
150     my $name   = $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'};
151     if ( $messages->{'transfert'} ) {
152         $template->param(
153             itemtitle      => $iteminfo->{'title'},
154             itemnumber     => $iteminfo->{'itemnumber'},
155             itembiblionumber => $iteminfo->{'biblionumber'},
156             iteminfo       => $iteminfo->{'author'},
157             tobranchname   => GetBranchName($messages->{'transfert'}),
158             name           => $name,
159             borrowernumber => $borrowernumber,
160             borcnum        => $borr->{'cardnumber'},
161             borfirstname   => $borr->{'firstname'},
162             borsurname     => $borr->{'surname'},
163             diffbranch     => 1,
164         );
165     }
166 }
167
168 my $borrower;
169 my $returned = 0;
170 my $messages;
171 my $issueinformation;
172 my $itemnumber;
173 my $barcode     = $query->param('barcode');
174 my $exemptfine  = $query->param('exemptfine');
175 if (
176   $exemptfine &&
177   !C4::Auth::haspermission(C4::Context->userenv->{'id'}, {'updatecharges' => 'writeoff'})
178 ) {
179     # silently prevent unauthorized operator from forgiving overdue
180     # fines by manually tweaking form parameters
181     undef $exemptfine;
182 }
183 my $dropboxmode = $query->param('dropboxmode');
184 my $dotransfer  = $query->param('dotransfer');
185 my $canceltransfer = $query->param('canceltransfer');
186 my $dest = $query->param('dest');
187 my $calendar    = Koha::Calendar->new( branchcode => $userenv_branch );
188 #dropbox: get last open day (today - 1)
189 my $today       = DateTime->now( time_zone => C4::Context->tz());
190 my $dropboxdate = $calendar->addDate($today, -1);
191 if ($dotransfer){
192 # An item has been returned to a branch other than the homebranch, and the librarian has chosen to initiate a transfer
193     my $transferitem = $query->param('transferitem');
194     my $tobranch     = $query->param('tobranch');
195     ModItemTransfer($transferitem, $userenv_branch, $tobranch); 
196 }
197
198 if ($canceltransfer){
199     $itemnumber=$query->param('itemnumber');
200     DeleteTransfer($itemnumber);
201     if($dest eq "ttr"){
202         print $query->redirect("/cgi-bin/koha/circ/transferstoreceive.pl");
203         exit;
204     } else {
205         $template->param( transfercancelled => 1);
206     }
207 }
208
209 # actually return book and prepare item table.....
210 if ($barcode) {
211     $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
212     $barcode = barcodedecode($barcode) if C4::Context->preference('itemBarcodeInputFilter');
213     $itemnumber = GetItemnumberFromBarcode($barcode);
214
215     if ( C4::Context->preference("InProcessingToShelvingCart") ) {
216         my $item = GetItem( $itemnumber );
217         if ( $item->{'location'} eq 'PROC' ) {
218             $item->{'location'} = 'CART';
219             ModItem( $item, $item->{'biblionumber'}, $item->{'itemnumber'} );
220         }
221     }
222
223 #
224 # save the return
225 #
226     ( $returned, $messages, $issueinformation, $borrower ) =
227       AddReturn( $barcode, $userenv_branch, $exemptfine, $dropboxmode);     # do the return
228     my $homeorholdingbranchreturn = C4::Context->preference('HomeOrHoldingBranchReturn');
229     $homeorholdingbranchreturn ||= 'homebranch';
230
231     # get biblio description
232     my $biblio = GetBiblioFromItemNumber($itemnumber);
233     # fix up item type for display
234     $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
235
236     # Check if we should display a checkin message, based on the the item
237     # type of the checked in item
238     my $itemtype = C4::ItemType->get( $biblio->{'itemtype'} );
239     if ( $itemtype->{'checkinmsg'} ) {
240         $template->param(
241             checkinmsg     => $itemtype->{'checkinmsg'},
242             checkinmsgtype => $itemtype->{'checkinmsgtype'},
243         );
244     }
245
246     $template->param(
247         title            => $biblio->{'title'},
248         homebranch       => $biblio->{'homebranch'},
249         homebranchname   => GetBranchName( $biblio->{$homeorholdingbranchreturn} ),
250         author           => $biblio->{'author'},
251         itembarcode      => $biblio->{'barcode'},
252         itemtype         => $biblio->{'itemtype'},
253         ccode            => $biblio->{'ccode'},
254         itembiblionumber => $biblio->{'biblionumber'},    
255         additional_materials => $biblio->{'materials'}
256     );
257
258     my %input = (
259         counter => 0,
260         first   => 1,
261         barcode => $barcode,
262     );
263
264     if ($returned) {
265         my $time_now = DateTime->now( time_zone => C4::Context->tz )->truncate( to => 'minute');
266         my $duedate = $issueinformation->{date_due}->strftime('%Y-%m-%d %H:%M');
267         $returneditems{0}      = $barcode;
268         $riborrowernumber{0}   = $borrower->{'borrowernumber'};
269         $riduedate{0}          = $duedate;
270         $input{borrowernumber} = $borrower->{'borrowernumber'};
271         $input{duedate}        = $duedate;
272         $input{return_overdue} = 1 if (DateTime->compare($issueinformation->{date_due}, $time_now) == -1);
273         push( @inputloop, \%input );
274
275         if ( C4::Context->preference("FineNotifyAtCheckin") ) {
276             my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrower->{'borrowernumber'} );
277             if ($fines && $fines > 0) {
278                 $template->param( fines => sprintf("%.2f",$fines) );
279                 $template->param( fineborrowernumber => $borrower->{'borrowernumber'} );
280             }
281         }
282         
283         if (C4::Context->preference("WaitingNotifyAtCheckin") ) {
284             #Check for waiting holds
285             my @reserves = GetReservesFromBorrowernumber($borrower->{'borrowernumber'});
286             my $waiting_holds = 0;
287             foreach my $num_res (@reserves) {
288                 if ( $num_res->{'found'} eq 'W' && $num_res->{'branchcode'} eq $userenv_branch) {
289                     $waiting_holds++;
290                 }
291             } 
292             if ($waiting_holds > 0) {
293                 $template->param(
294                     waiting_holds       => $waiting_holds,
295                     holdsborrowernumber => $borrower->{'borrowernumber'},
296                     holdsfirstname => $borrower->{'firstname'},
297                     holdssurname => $borrower->{'surname'},
298                 );
299             }
300         }
301     }
302     elsif ( !$messages->{'BadBarcode'} ) {
303         $input{duedate}   = 0;
304         $returneditems{0} = $barcode;
305         $riduedate{0}     = 0;
306         push( @inputloop, \%input );
307     }
308 }
309 $template->param( inputloop => \@inputloop );
310
311 my $found    = 0;
312 my $waiting  = 0;
313 my $reserved = 0;
314
315 # new op dev : we check if the document must be returned to his homebranch directly,
316 #  if the document is transfered, we have warning message .
317
318 if ( $messages->{'WasTransfered'} ) {
319     $template->param(
320         found          => 1,
321         transfer       => 1,
322         itemnumber     => $itemnumber,
323     );
324 }
325
326 if ( $messages->{'NeedsTransfer'} ){
327     $template->param(
328         found          => 1,
329         needstransfer  => 1,
330         itemnumber     => $itemnumber,
331     );
332 }
333
334 if ( $messages->{'Wrongbranch'} ){
335     $template->param(
336         wrongbranch => 1,
337     );
338 }
339
340 # case of wrong transfert, if the document wasn't transfered to the right library (according to branchtransfer (tobranch) BDD)
341
342 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
343     $template->param(
344         WrongTransfer  => 1,
345         TransferWaitingAt => $messages->{'WrongTransfer'},
346         WrongTransferItem => $messages->{'WrongTransferItem'},
347         itemnumber => $itemnumber,
348     );
349
350     my $reserve    = $messages->{'ResFound'};
351     my $branchname = $branches->{ $reserve->{'branchcode'} }->{'branchname'};
352     my ($borr) = GetMemberDetails( $reserve->{'borrowernumber'}, 0 );
353     my $name = $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'};
354     $template->param(
355             wname           => $name,
356             wborfirstname   => $borr->{'firstname'},
357             wborsurname     => $borr->{'surname'},
358             wbortitle       => $borr->{'title'},
359             wborphone       => $borr->{'phone'},
360             wboremail       => $borr->{'email'},
361             wboraddress     => $borr->{'address'},
362             wboraddress2    => $borr->{'address2'},
363             wborcity        => $borr->{'city'},
364             wborzip         => $borr->{'zipcode'},
365             wborrowernumber => $reserve->{'borrowernumber'},
366             wborcnum        => $borr->{'cardnumber'},
367             wtransfertFrom  => $userenv_branch,
368     );
369 }
370
371 #
372 # reserve found and item arrived at the expected branch
373 #
374 if ( $messages->{'ResFound'}) {
375     my $reserve    = $messages->{'ResFound'};
376     my $branchname = $branches->{ $reserve->{'branchcode'} }->{'branchname'};
377     my ($borr) = GetMemberDetails( $reserve->{'borrowernumber'}, 0 );
378
379     if ( $reserve->{'ResFound'} eq "Waiting" or $reserve->{'ResFound'} eq "Reserved" ) {
380         if ( $reserve->{'ResFound'} eq "Waiting" ) {
381             $template->param(
382                 waiting      => ($userenv_branch eq $reserve->{'branchcode'} ? 1 : 0 ),
383             );
384         } elsif ( $reserve->{'ResFound'} eq "Reserved" ) {
385             $template->param(
386                 intransit    => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
387                 transfertodo => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
388                 resbarcode   => $barcode,
389                 reserved     => 1,
390             );
391         }
392
393         # same params for Waiting or Reserved
394         $template->param(
395             found          => 1,
396             currentbranch  => $branches->{$userenv_branch}->{'branchname'},
397             destbranchname => $branches->{ $reserve->{'branchcode'} }->{'branchname'},
398             name           => $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'},
399             borfirstname   => $borr->{'firstname'},
400             borsurname     => $borr->{'surname'},
401             bortitle       => $borr->{'title'},
402             borphone       => $borr->{'phone'},
403             boremail       => $borr->{'email'},
404             boraddress     => $borr->{'address'},
405             boraddress2    => $borr->{'address2'},
406             borcity        => $borr->{'city'},
407             borzip         => $borr->{'zipcode'},
408             borcnum        => $borr->{'cardnumber'},
409             debarred       => $borr->{'debarred'},
410             gonenoaddress  => $borr->{'gonenoaddress'},
411             barcode        => $barcode,
412             destbranch     => $reserve->{'branchcode'},
413             borrowernumber => $reserve->{'borrowernumber'},
414             itemnumber     => $reserve->{'itemnumber'},
415             reservenotes   => $reserve->{'reservenotes'},
416         );
417     } # else { ; }  # error?
418 }
419
420 # Error Messages
421 my @errmsgloop;
422 foreach my $code ( keys %$messages ) {
423     my %err;
424     my $exit_required_p = 0;
425     if ( $code eq 'BadBarcode' ) {
426         $err{badbarcode} = 1;
427         $err{msg}        = $messages->{'BadBarcode'};
428     }
429     elsif ( $code eq 'NotIssued' ) {
430         $err{notissued} = 1;
431         $err{msg} = $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
432     }
433     elsif ( $code eq 'LocalUse' ) {
434         $err{localuse} = 1;
435     }
436     elsif ( $code eq 'WasLost' ) {
437         $err{waslost} = 1;
438     }
439     elsif ( $code eq 'LostItemFeeRefunded' ) {
440         $template->param( LostItemFeeRefunded => 1 );
441     }
442     elsif ( $code eq 'ResFound' ) {
443         ;    # FIXME... anything to do here?
444     }
445     elsif ( $code eq 'WasReturned' ) {
446         ;    # FIXME... anything to do here?
447     }
448     elsif ( $code eq 'WasTransfered' ) {
449         ;    # FIXME... anything to do here?
450     }
451     elsif ( $code eq 'withdrawn' ) {
452         $err{withdrawn} = 1;
453         $exit_required_p = 1 if C4::Context->preference("BlockReturnOfWithdrawnItems");
454     }
455     elsif ( ( $code eq 'IsPermanent' ) && ( not $messages->{'ResFound'} ) ) {
456         if ( $messages->{'IsPermanent'} ne $userenv_branch ) {
457             $err{ispermanent} = 1;
458             $err{msg}         =
459               $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
460         }
461     }
462     elsif ( $code eq 'WrongTransfer' ) {
463         ;    # FIXME... anything to do here?
464     }
465     elsif ( $code eq 'WrongTransferItem' ) {
466         ;    # FIXME... anything to do here?
467     }
468     elsif ( $code eq 'NeedsTransfer' ) {
469     }
470     elsif ( $code eq 'Wrongbranch' ) {
471     }
472     elsif ( $code eq 'Debarred' ) {
473         $err{debarred}            = $messages->{'Debarred'};
474         $err{debarcardnumber}     = $borrower->{cardnumber};
475         $err{debarborrowernumber} = $borrower->{borrowernumber};
476         $err{debarname}           = "$borrower->{firstname} $borrower->{surname}";
477     }
478     else {
479         die "Unknown error code $code";    # note we need all the (empty) elsif's above, or we die.
480         # This forces the issue of staying in sync w/ Circulation.pm
481     }
482     if (%err) {
483         push( @errmsgloop, \%err );
484     }
485     last if $exit_required_p;
486 }
487 $template->param( errmsgloop => \@errmsgloop );
488
489 #set up so only the last 8 returned items display (make for faster loading pages)
490 my $returned_counter = ( C4::Context->preference('numReturnedItemsToShow') ) ? C4::Context->preference('numReturnedItemsToShow') : 8;
491 my $count = 0;
492 my @riloop;
493 my $shelflocations = GetKohaAuthorisedValues('items.location','');
494 foreach ( sort { $a <=> $b } keys %returneditems ) {
495     my %ri;
496     if ( $count++ < $returned_counter ) {
497         my $bar_code = $returneditems{$_};
498         if ($riduedate{$_}) {
499             my $duedate = dt_from_string( $riduedate{$_}, 'sql');
500             $ri{year}  = $duedate->year();
501             $ri{month} = $duedate->month();
502             $ri{day}   = $duedate->day();
503             $ri{hour}   = $duedate->hour();
504             $ri{minute}   = $duedate->minute();
505             $ri{duedate} = output_pref($duedate);
506             my ($b)      = GetMemberDetails( $riborrowernumber{$_}, 0 );
507             $ri{return_overdue} = 1 if (DateTime->compare($duedate, DateTime->now()) == -1 );
508             $ri{borrowernumber} = $b->{'borrowernumber'};
509             $ri{borcnum}        = $b->{'cardnumber'};
510             $ri{borfirstname}   = $b->{'firstname'};
511             $ri{borsurname}     = $b->{'surname'};
512             $ri{bortitle}       = $b->{'title'};
513             $ri{bornote}        = $b->{'borrowernotes'};
514             $ri{borcategorycode}= $b->{'categorycode'};
515         }
516         else {
517             $ri{borrowernumber} = $riborrowernumber{$_};
518         }
519
520         #        my %ri;
521         my $biblio = GetBiblioFromItemNumber(GetItemnumberFromBarcode($bar_code));
522         my $item   = GetItem( GetItemnumberFromBarcode($bar_code) );
523         # fix up item type for display
524         $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
525         $ri{itembiblionumber} = $biblio->{'biblionumber'};
526         $ri{itemtitle}        = $biblio->{'title'};
527         $ri{itemauthor}       = $biblio->{'author'};
528         $ri{itemcallnumber}   = $biblio->{'itemcallnumber'};
529         $ri{itemtype}         = $biblio->{'itemtype'};
530         $ri{itemnote}         = $biblio->{'itemnotes'};
531         $ri{ccode}            = $biblio->{'ccode'};
532         $ri{itemnumber}       = $biblio->{'itemnumber'};
533         $ri{barcode}          = $bar_code;
534         $ri{homebranch}       = $item->{'homebranch'};
535         $ri{holdingbranch}    = $item->{'holdingbranch'};
536
537         $ri{location}         = $biblio->{'location'};
538         my $shelfcode = $ri{'location'};
539         $ri{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
540
541     }
542     else {
543         last;
544     }
545     push @riloop, \%ri;
546 }
547 my ($genbrname, $genprname);
548 if (my $b = $branches->{$userenv_branch}) {
549     $genbrname = $b->{'branchname'};
550 }
551 if (my $p = $printers->{$printer}) {
552     $genprname = $p->{'printername'};
553 }
554 $template->param(
555     riloop         => \@riloop,
556     genbrname      => $genbrname,
557     genprname      => $genprname,
558     branchname     => $genbrname,
559     printer        => $printer,
560     errmsgloop     => \@errmsgloop,
561     exemptfine     => $exemptfine,
562     dropboxmode    => $dropboxmode,
563     dropboxdate    => output_pref($dropboxdate),
564     overduecharges => $overduecharges,
565     soundon        => C4::Context->preference("SoundOn"),
566     BlockReturnOfWithdrawnItems => C4::Context->preference("BlockReturnOfWithdrawnItems"),
567 );
568
569 ### Comment out rotating collections for now to allow it a little more time to bake
570 ### for 3.4; in particular, must ensure that it doesn't fight with transfers required
571 ### to fill hold requests
572 ### -- Galen Charlton 2010-10-06
573 #my $itemnumber = GetItemnumberFromBarcode( $query->param('barcode') );
574 #if ( $itemnumber ) {
575 #   my ( $holdingBranch, $collectionBranch ) = GetCollectionItemBranches( $itemnumber );
576 #    if ( ! ( $holdingBranch eq $collectionBranch ) ) {
577 #        $template->param(
578 #          collectionItemNeedsTransferred => 1,
579 #          collectionBranch => GetBranchName($collectionBranch),
580 #        );
581 #    }
582 #}                                                                                                            
583
584 # actually print the page!
585 output_html_with_http_headers $query, $cookie, $template->output;