Merge remote branch 'kc/new/enh/bug_3495' into kcmaster
[koha.git] / circ / returns.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 #           2006 SAN-OP
5 #           2007 BibLibre, Paul POULAIN
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 =head1 returns.pl
23
24 script to execute returns of books
25
26 =cut
27
28 use strict;
29 #use warnings; FIXME - Bug 2505
30
31 use CGI;
32 use C4::Context;
33 use C4::Auth qw/:DEFAULT get_session/;
34 use C4::Output;
35 use C4::Circulation;
36 use C4::Dates qw/format_date/;
37 use Date::Calc qw/Add_Delta_Days/;
38 use C4::Calendar;
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
48 my $query = new CGI;
49
50 if (!C4::Context->userenv){
51     my $sessionID = $query->cookie("CGISESSID");
52     my $session = get_session($sessionID);
53     if ($session->param('branch') eq 'NO_LIBRARY_SET'){
54         # no branch set we can't return
55         print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
56         exit;
57     }
58
59
60 #getting the template
61 my ( $template, $librarian, $cookie ) = get_template_and_user(
62     {
63         template_name   => "circ/returns.tmpl",
64         query           => $query,
65         type            => "intranet",
66         authnotrequired => 0,
67         flagsrequired   => { circulate => "circulate_remaining_permissions" },
68     }
69 );
70
71 #####################
72 #Global vars
73 my $branches = GetBranches();
74 my $printers = GetPrinters();
75
76 my $printer = C4::Context->userenv ? C4::Context->userenv->{'branchprinter'} : "";
77 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') ne 'off');
78
79 my $userenv_branch = C4::Context->userenv->{'branch'} || '';
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             itembiblionumber => $iteminfo->{'biblionumber'},
153             iteminfo       => $iteminfo->{'author'},
154             tobranchname   => GetBranchName($messages->{'transfert'}),
155             name           => $name,
156             borrowernumber => $borrowernumber,
157             borcnum        => $borr->{'cardnumber'},
158             borfirstname   => $borr->{'firstname'},
159             borsurname     => $borr->{'surname'},
160             diffbranch     => 1,
161         );
162     }
163 }
164
165 my $borrower;
166 my $returned = 0;
167 my $messages;
168 my $issueinformation;
169 my $itemnumber;
170 my $barcode     = $query->param('barcode');
171 my $exemptfine  = $query->param('exemptfine');
172 my $dropboxmode = $query->param('dropboxmode');
173 my $dotransfer  = $query->param('dotransfer');
174 my $calendar    = C4::Calendar->new( branchcode => $userenv_branch );
175 #dropbox: get last open day (today - 1)
176 my $today       = C4::Dates->new();
177 my $today_iso   = $today->output('iso');
178 my $dropboxdate = $calendar->addDate($today, -1);
179 if ($dotransfer){
180 # An item has been returned to a branch other than the homebranch, and the librarian has chosen to initiate a transfer
181     my $transferitem = $query->param('transferitem');
182     my $tobranch     = $query->param('tobranch');
183     ModItemTransfer($transferitem, $userenv_branch, $tobranch); 
184 }
185
186 # actually return book and prepare item table.....
187 if ($barcode) {
188     $barcode =~ s/^\s*|\s*$//g; # remove leading/trailing whitespace
189     $barcode = barcodedecode($barcode) if C4::Context->preference('itemBarcodeInputFilter');
190     $itemnumber = GetItemnumberFromBarcode($barcode);
191
192     if ( C4::Context->preference("InProcessingToShelvingCart") ) {
193         my $item = GetItem( $itemnumber );
194         if ( $item->{'location'} eq 'PROC' ) {
195             $item->{'location'} = 'CART';
196             ModItem( $item, $item->{'biblionumber'}, $item->{'itemnumber'} );
197         }
198     }
199
200     if ( C4::Context->preference("ReturnToShelvingCart") ) {
201         my $item = GetItem( $itemnumber );
202         $item->{'location'} = 'CART';
203         ModItem( $item, $item->{'biblionumber'}, $item->{'itemnumber'} );
204     }
205
206 #
207 # save the return
208 #
209     ( $returned, $messages, $issueinformation, $borrower ) =
210       AddReturn( $barcode, $userenv_branch, $exemptfine, $dropboxmode);     # do the return
211     my $homeorholdingbranchreturn = C4::Context->preference('HomeOrHoldingBranchReturn') or 'homebranch';
212
213     # get biblio description
214     my $biblio = GetBiblioFromItemNumber($itemnumber);
215     # fix up item type for display
216     $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
217
218     $template->param(
219         title            => $biblio->{'title'},
220         homebranch       => $biblio->{'homebranch'},
221         homebranchname   => GetBranchName( $biblio->{$homeorholdingbranchreturn} ),
222         author           => $biblio->{'author'},
223         itembarcode      => $biblio->{'barcode'},
224         itemtype         => $biblio->{'itemtype'},
225         ccode            => $biblio->{'ccode'},
226         itembiblionumber => $biblio->{'biblionumber'},    
227     );
228
229     my %input = (
230         counter => 0,
231         first   => 1,
232         barcode => $barcode,
233     );
234
235     if ($returned) {
236         my $duedate = $issueinformation->{'date_due'};
237         $returneditems{0}      = $barcode;
238         $riborrowernumber{0}   = $borrower->{'borrowernumber'};
239         $riduedate{0}          = $duedate;
240         $input{borrowernumber} = $borrower->{'borrowernumber'};
241         $input{duedate}        = $duedate;
242         $input{return_overdue} = 1 if ($duedate and $duedate lt $today->output('iso'));
243         push( @inputloop, \%input );
244
245         my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrower->{'borrowernumber'} );
246         if ($fines > 0) {
247             $template->param( fines => sprintf("%.2f",$fines) );
248             $template->param( fineborrowernumber => $borrower->{'borrowernumber'} );
249         }
250
251     }
252     elsif ( !$messages->{'BadBarcode'} ) {
253         $input{duedate}   = 0;
254         $returneditems{0} = $barcode;
255         $riduedate{0}     = 0;
256         if ( $messages->{'wthdrawn'} ) {
257             $input{withdrawn}      = 1;
258             $input{borrowernumber} = 'Item Cancelled';  # FIXME: should be in display layer ?
259             $riborrowernumber{0}   = 'Item Cancelled';
260         }
261         else {
262             $input{borrowernumber} = ' ';  # This seems clearly bogus.
263             $riborrowernumber{0}   = ' ';
264         }
265         push( @inputloop, \%input );
266     }
267 }
268 $template->param( inputloop => \@inputloop );
269
270 my $found    = 0;
271 my $waiting  = 0;
272 my $reserved = 0;
273
274 # new op dev : we check if the document must be returned to his homebranch directly,
275 #  if the document is transfered, we have warning message .
276
277 if ( $messages->{'WasTransfered'} ) {
278     $template->param(
279         found          => 1,
280         transfer       => 1,
281     );
282 }
283
284 if ( $messages->{'NeedsTransfer'} ){
285     $template->param(
286         found          => 1,
287         needstransfer  => 1,
288         itemnumber     => $itemnumber,
289     );
290 }
291
292 if ( $messages->{'Wrongbranch'} ){
293     $template->param(
294         wrongbranch => 1,
295     );
296 }
297
298 # case of wrong transfert, if the document wasn't transfered to the right library (according to branchtransfer (tobranch) BDD)
299
300 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
301     $messages->{'WrongTransfer'} = GetBranchName( $messages->{'WrongTransfer'} );
302     $template->param(
303         WrongTransfer  => 1,
304         TransferWaitingAt => $messages->{'WrongTransfer'},
305         WrongTransferItem => $messages->{'WrongTransferItem'},
306     );
307
308     my $reserve    = $messages->{'ResFound'};
309     my $branchname = $branches->{ $reserve->{'branchcode'} }->{'branchname'};
310     my ($borr) = GetMemberDetails( $reserve->{'borrowernumber'}, 0 );
311     my $name = $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'};
312     $template->param(
313             wname           => $name,
314             wborfirstname   => $borr->{'firstname'},
315             wborsurname     => $borr->{'surname'},
316             wbortitle       => $borr->{'title'},
317             wborphone       => $borr->{'phone'},
318             wboremail       => $borr->{'email'},
319             wboraddress     => $borr->{'address'},
320             wboraddress2    => $borr->{'address2'},
321             wborcity        => $borr->{'city'},
322             wborzip         => $borr->{'zipcode'},
323             wborrowernumber => $reserve->{'borrowernumber'},
324             wborcnum        => $borr->{'cardnumber'},
325             wtransfertFrom  => $userenv_branch,
326     );
327 }
328
329 #
330 # reserve found and item arrived at the expected branch
331 #
332 if ( $messages->{'ResFound'}) {
333     my $reserve    = $messages->{'ResFound'};
334     my $branchname = $branches->{ $reserve->{'branchcode'} }->{'branchname'};
335     my ($borr) = GetMemberDetails( $reserve->{'borrowernumber'}, 0 );
336
337     if ( $reserve->{'ResFound'} eq "Waiting" or $reserve->{'ResFound'} eq "Reserved" ) {
338         if ( $reserve->{'ResFound'} eq "Waiting" ) {
339             $template->param(
340                 waiting      => ($userenv_branch eq $reserve->{'branchcode'} ? 1 : 0 ),
341             );
342         } elsif ( $reserve->{'ResFound'} eq "Reserved" ) {
343             $template->param(
344                 intransit    => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
345                 transfertodo => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
346                 resbarcode   => $barcode,
347                 reserved     => 1,
348             );
349         }
350
351         # same params for Waiting or Reserved
352         $template->param(
353             found          => 1,
354             currentbranch  => $branches->{$userenv_branch}->{'branchname'},
355             destbranchname => $branches->{ $reserve->{'branchcode'} }->{'branchname'},
356             name           => $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'},
357             borfirstname   => $borr->{'firstname'},
358             borsurname     => $borr->{'surname'},
359             bortitle       => $borr->{'title'},
360             borphone       => $borr->{'phone'},
361             boremail       => $borr->{'email'},
362             boraddress     => $borr->{'address'},
363             boraddress2    => $borr->{'address2'},
364             borcity        => $borr->{'city'},
365             borzip         => $borr->{'zipcode'},
366             borcnum        => $borr->{'cardnumber'},
367             debarred       => $borr->{'debarred'},
368             gonenoaddress  => $borr->{'gonenoaddress'},
369             barcode        => $barcode,
370             destbranch     => $reserve->{'branchcode'},
371             borrowernumber => $reserve->{'borrowernumber'},
372             itemnumber     => $reserve->{'itemnumber'},
373             reservenotes   => $reserve->{'reservenotes'},
374         );
375     } # else { ; }  # error?
376 }
377
378 # Error Messages
379 my @errmsgloop;
380 foreach my $code ( keys %$messages ) {
381     my %err;
382     my $exit_required_p = 0;
383     if ( $code eq 'BadBarcode' ) {
384         $err{badbarcode} = 1;
385         $err{msg}        = $messages->{'BadBarcode'};
386     }
387     elsif ( $code eq 'NotIssued' ) {
388         $err{notissued} = 1;
389         $err{msg} = $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
390     }
391     elsif ( $code eq 'WasLost' ) {
392         $err{waslost} = 1;
393     }
394     elsif ( $code eq 'ResFound' ) {
395         ;    # FIXME... anything to do here?
396     }
397     elsif ( $code eq 'WasReturned' ) {
398         ;    # FIXME... anything to do here?
399     }
400     elsif ( $code eq 'WasTransfered' ) {
401         ;    # FIXME... anything to do here?
402     }
403     elsif ( $code eq 'wthdrawn' ) {
404         $err{withdrawn} = 1;
405         $exit_required_p = 1;
406     }
407     elsif ( ( $code eq 'IsPermanent' ) && ( not $messages->{'ResFound'} ) ) {
408         if ( $messages->{'IsPermanent'} ne $userenv_branch ) {
409             $err{ispermanent} = 1;
410             $err{msg}         =
411               $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
412         }
413     }
414     elsif ( $code eq 'WrongTransfer' ) {
415         ;    # FIXME... anything to do here?
416     }
417     elsif ( $code eq 'WrongTransferItem' ) {
418         ;    # FIXME... anything to do here?
419     }
420     elsif ( $code eq 'NeedsTransfer' ) {
421     }
422     elsif ( $code eq 'Wrongbranch' ) {
423     }
424
425     else {
426         die "Unknown error code $code";    # note we need all the (empty) elsif's above, or we die.
427         # This forces the issue of staying in sync w/ Circulation.pm
428     }
429     if (%err) {
430         push( @errmsgloop, \%err );
431     }
432     last if $exit_required_p;
433 }
434 $template->param( errmsgloop => \@errmsgloop );
435
436 # patrontable ....
437 if ($borrower) {
438     my $flags = $borrower->{'flags'};
439     my @flagloop;
440     my $flagset;
441     foreach my $flag ( sort keys %$flags ) {
442         my %flaginfo;
443         unless ($flagset) { $flagset = 1; }
444         $flaginfo{redfont} = ( $flags->{$flag}->{'noissues'} );
445         $flaginfo{flag}    = $flag;
446         if ( $flag eq 'CHARGES' ) {
447             $flaginfo{msg}            = $flag;
448             $flaginfo{charges}        = 1;
449             $flaginfo{chargeamount}   = $flags->{$flag}->{amount};
450             $flaginfo{borrowernumber} = $borrower->{borrowernumber};
451         }
452         elsif ( $flag eq 'WAITING' ) {
453             $flaginfo{msg}     = $flag;
454             $flaginfo{waiting} = 1;
455             my @waitingitemloop;
456             my $items = $flags->{$flag}->{'itemlist'};
457             foreach my $item (@$items) {
458                 my $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'});
459                 push @waitingitemloop, {
460                     biblionum => $biblio->{'biblionumber'},
461                     barcode   => $biblio->{'barcode'},
462                     title     => $biblio->{'title'},
463                     brname    => $branches->{ $biblio->{'holdingbranch'} }->{'branchname'},
464                 };
465             }
466             $flaginfo{itemloop} = \@waitingitemloop;
467         }
468         elsif ( $flag eq 'ODUES' ) {
469             my $items = $flags->{$flag}->{'itemlist'};
470             my @itemloop;
471             foreach my $item ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
472                 @$items )
473             {
474                 my $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'});
475                 push @itemloop, {
476                     duedate   => format_date($item->{'date_due'}),
477                     biblionum => $biblio->{'biblionumber'},
478                     barcode   => $biblio->{'barcode'},
479                     title     => $biblio->{'title'},
480                     brname    => $branches->{ $biblio->{'holdingbranch'} }->{'branchname'},
481                 };
482             }
483             $flaginfo{itemloop} = \@itemloop;
484             $flaginfo{overdue}  = 1;
485         }
486         else {
487             $flaginfo{other} = 1;
488             $flaginfo{msg}   = $flags->{$flag}->{'message'};
489         }
490         push( @flagloop, \%flaginfo );
491     }
492     $template->param(
493         flagset          => $flagset,
494         flagloop         => \@flagloop,
495         riborrowernumber => $borrower->{'borrowernumber'},
496         riborcnum        => $borrower->{'cardnumber'},
497         riborsurname     => $borrower->{'surname'},
498         ribortitle       => $borrower->{'title'},
499         riborfirstname   => $borrower->{'firstname'}
500     );
501 }
502
503 #set up so only the last 8 returned items display (make for faster loading pages)
504 my $returned_counter = ( C4::Context->preference('numReturnedItemsToShow') ) ? C4::Context->preference('numReturnedItemsToShow') : 8;
505 my $count = 0;
506 my @riloop;
507 foreach ( sort { $a <=> $b } keys %returneditems ) {
508     my %ri;
509     if ( $count++ < $returned_counter ) {
510         my $bar_code = $returneditems{$_};
511         my $duedate = $riduedate{$_};
512         if ($duedate) {
513             my @tempdate = split( /-/, $duedate );
514             $ri{year}  = $tempdate[0];
515             $ri{month} = $tempdate[1];
516             $ri{day}   = $tempdate[2];
517             $ri{duedate} = format_date($duedate);
518             my ($b)      = GetMemberDetails( $riborrowernumber{$_}, 0 );
519             $ri{return_overdue} = 1 if ($duedate lt $today->output('iso'));
520             $ri{borrowernumber} = $b->{'borrowernumber'};
521             $ri{borcnum}        = $b->{'cardnumber'};
522             $ri{borfirstname}   = $b->{'firstname'};
523             $ri{borsurname}     = $b->{'surname'};
524             $ri{bortitle}       = $b->{'title'};
525             $ri{bornote}        = $b->{'borrowernotes'};
526             $ri{borcategorycode}= $b->{'categorycode'};
527         }
528         else {
529             $ri{borrowernumber} = $riborrowernumber{$_};
530         }
531
532         #        my %ri;
533         my $biblio = GetBiblioFromItemNumber(GetItemnumberFromBarcode($bar_code));
534         # fix up item type for display
535         $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
536         $ri{itembiblionumber} = $biblio->{'biblionumber'};
537         $ri{itemtitle}        = $biblio->{'title'};
538         $ri{itemauthor}       = $biblio->{'author'};
539         $ri{itemtype}         = $biblio->{'itemtype'};
540         $ri{itemnote}         = $biblio->{'itemnotes'};
541         $ri{ccode}            = $biblio->{'ccode'};
542         $ri{itemnumber}       = $biblio->{'itemnumber'};
543         $ri{barcode}          = $bar_code;
544     }
545     else {
546         last;
547     }
548     push @riloop, \%ri;
549 }
550
551 $template->param(
552     riloop         => \@riloop,
553     genbrname      => $branches->{$userenv_branch}->{'branchname'},
554     genprname      => $printers->{$printer}->{'printername'},
555     branchname     => $branches->{$userenv_branch}->{'branchname'},
556     printer        => $printer,
557     errmsgloop     => \@errmsgloop,
558     exemptfine     => $exemptfine,
559     dropboxmode    => $dropboxmode,
560     dropboxdate    => $dropboxdate->output(),
561     overduecharges => $overduecharges,
562     soundon        => C4::Context->preference("SoundOn"),
563 );
564
565 ### Comment out rotating collections for now to allow it a little more time to bake
566 ### for 3.4; in particular, must ensure that it doesn't fight with transfers required
567 ### to fill hold requests
568 ### -- Galen Charlton 2010-10-06
569 #my $itemnumber = GetItemnumberFromBarcode( $query->param('barcode') );
570 #if ( $itemnumber ) {
571 #   my ( $holdingBranch, $collectionBranch ) = GetCollectionItemBranches( $itemnumber );
572 #    if ( ! ( $holdingBranch eq $collectionBranch ) ) {
573 #        $template->param(
574 #          collectionItemNeedsTransferred => 1,
575 #          collectionBranch => GetBranchName($collectionBranch),
576 #        );
577 #    }
578 #}                                                                                                            
579
580 # actually print the page!
581 output_html_with_http_headers $query, $cookie, $template->output;