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