Bug Fixing : returns.pl compile error $duedate undefined
[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 with
19 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
20 # Suite 330, Boston, MA  02111-1307 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
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
47 my $query = new CGI;
48
49 if (!C4::Context->userenv){
50         my $sessionID = $query->cookie("CGISESSID");
51         my $session = get_session($sessionID);
52         if ($session->param('branch') eq 'NO_LIBRARY_SET'){
53                 # no branch set we can't return
54                 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
55                 exit;
56         }
57
58
59 #getting the template
60 my ( $template, $librarian, $cookie ) = get_template_and_user(
61     {
62         template_name   => "circ/returns.tmpl",
63         query           => $query,
64         type            => "intranet",
65         authnotrequired => 0,
66         flagsrequired   => { circulate => "circulate_remaining_permissions" },
67     }
68 );
69
70 #####################
71 #Global vars
72 my $branches = GetBranches();
73 my $printers = GetPrinters();
74
75 #my $branch  = C4::Context->userenv?C4::Context->userenv->{'branch'}:"";
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     (next) unless (/ri-(\d*)/);
91     my %input;
92     my $counter = $1;
93     (next) if ( $counter > 20 );
94     my $barcode        = $query->param("ri-$counter");
95     my $duedate        = $query->param("dd-$counter");
96     my $borrowernumber = $query->param("bn-$counter");
97     $counter++;
98
99     # decode barcode    ## Didn't we already decode them before passing them back last time??
100     $barcode = barcodedecode($barcode) if(C4::Context->preference('itemBarcodeInputFilter'));
101
102     ######################
103     #Are these lines still useful ?
104     $returneditems{$counter}    = $barcode;
105     $riduedate{$counter}        = $duedate;
106     $riborrowernumber{$counter} = $borrowernumber;
107
108     #######################
109     $input{counter}        = $counter;
110     $input{barcode}        = $barcode;
111     $input{duedate}        = $duedate;
112     $input{borrowernumber} = $borrowernumber;
113     push( @inputloop, \%input );
114 }
115
116 ############
117 # Deal with the requests....
118
119 if ($query->param('WT-itemNumber')){
120         updateWrongTransfer ($query->param('WT-itemNumber'),$query->param('WT-waitingAt'),$query->param('WT-From'));
121 }
122
123 if ( $query->param('resbarcode') ) {
124     my $item           = $query->param('itemnumber');
125     my $borrowernumber = $query->param('borrowernumber');
126     my $resbarcode     = $query->param('resbarcode');
127     my $diffBranchReturned = $query->param('diffBranch');
128     my $iteminfo   = GetBiblioFromItemNumber($item);
129     # fix up item type for display
130     $iteminfo->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $iteminfo->{'itype'} : $iteminfo->{'itemtype'};
131     my $diffBranchSend = ($userenv_branch ne $diffBranchReturned) ? $diffBranchReturned : undef;
132 # diffBranchSend tells ModReserveAffect whether document is expected in this library or not,
133 # i.e., whether to apply waiting status
134     ModReserveAffect( $item, $borrowernumber, $diffBranchSend);
135 #   check if we have other reserves for this document, if we have a return send the message of transfer
136     my ( $messages, $nextreservinfo ) = GetOtherReserves($item);
137
138     my ($borr) = GetMemberDetails( $nextreservinfo, 0 );
139     my $name   = $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'};
140     if ( $messages->{'transfert'} ) {
141         $template->param(
142             itemtitle      => $iteminfo->{'title'},
143                         itembiblionumber => $iteminfo->{'biblionumber'},
144             iteminfo       => $iteminfo->{'author'},
145             tobranchname   => GetBranchName($messages->{'transfert'}),
146             name           => $name,
147             borrowernumber => $borrowernumber,
148             borcnum        => $borr->{'cardnumber'},
149             borfirstname   => $borr->{'firstname'},
150             borsurname     => $borr->{'surname'},
151             diffbranch     => 1,
152         );
153     }
154 }
155
156 my $borrower;
157 my $returned = 0;
158 my $messages;
159 my $issueinformation;
160 my $itemnumber;
161 my $barcode     = $query->param('barcode');
162 my $exemptfine  = $query->param('exemptfine');
163 my $dropboxmode = $query->param('dropboxmode');
164 my $dotransfer  = $query->param('dotransfer');
165 my $calendar    = C4::Calendar->new( branchcode => $userenv_branch );
166         #dropbox: get last open day (today - 1)
167 my $today       = C4::Dates->new();
168 my $today_iso   = $today->output('iso');
169 my $dropboxdate = $calendar->addDate($today, -1);
170 if ($dotransfer){
171         # An item has been returned to a branch other than the homebranch, and the librarian has chosen to initiate a transfer
172         my $transferitem = $query->param('transferitem');
173         my $tobranch     = $query->param('tobranch');
174         ModItemTransfer($transferitem, $userenv_branch, $tobranch); 
175 }
176
177 # actually return book and prepare item table.....
178 if ($barcode) {
179     $barcode = barcodedecode($barcode) if C4::Context->preference('itemBarcodeInputFilter');
180 #
181 # save the return
182 #
183     $itemnumber = GetItemnumberFromBarcode($barcode);
184
185     ( $returned, $messages, $issueinformation, $borrower ) =
186       AddReturn( $barcode, $userenv_branch, $exemptfine, $dropboxmode);     # do the return
187
188     # get biblio description
189     my $biblio = GetBiblioFromItemNumber($itemnumber);
190     # fix up item type for display
191     $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
192
193     $template->param(
194         title            => $biblio->{'title'},
195         homebranch       => $biblio->{'homebranch'},
196         author           => $biblio->{'author'},
197         itembarcode      => $biblio->{'barcode'},
198         itemtype         => $biblio->{'itemtype'},
199         ccode            => $biblio->{'ccode'},
200         itembiblionumber => $biblio->{'biblionumber'},    
201     );
202
203     my %input = (
204         counter => 0,
205         first   => 1,
206         barcode => $barcode,
207     );
208
209     if ($returned) {
210         $returneditems{0}    = $barcode;
211         $riborrowernumber{0} = $borrower->{'borrowernumber'};
212         $riduedate{0}        = $issueinformation->{'date_due'};
213         $input{borrowernumber} = $borrower->{'borrowernumber'};
214         $input{duedate}        = $riduedate{0};
215         $input{return_overdue} = 1 if ($riduedate{0} and $riduedate{0} lt $today->output('iso'));
216         push( @inputloop, \%input );
217
218         # check if the branch is the same as homebranch
219         # if not, we want to put a message
220         if ( $biblio->{'homebranch'} ne $userenv_branch ) {
221             $template->param( homebranch => $biblio->{'homebranch'} );
222         }
223     }
224     elsif ( !$messages->{'BadBarcode'} ) {
225         $input{duedate}   = 0;
226         $returneditems{0} = $barcode;
227         $riduedate{0}     = 0;
228         if ( $messages->{'wthdrawn'} ) {
229             $input{withdrawn}      = 1;
230             $input{borrowernumber} = 'Item Cancelled';  # FIXME: should be in display layer ?
231             $riborrowernumber{0}   = 'Item Cancelled';
232         }
233         else {
234             $input{borrowernumber} = ' ';  # This seems clearly bogus.
235             $riborrowernumber{0}   = ' ';
236         }
237         push( @inputloop, \%input );
238     }
239 }
240 $template->param( inputloop => \@inputloop );
241
242 my $found    = 0;
243 my $waiting  = 0;
244 my $reserved = 0;
245
246 # new op dev : we check if the document must be returned to his homebranch directly,
247 #  if the document is transfered, we have warning message .
248
249 if ( $messages->{'WasTransfered'} ) {
250     $template->param(
251         found          => 1,
252         transfer       => 1,
253     );
254 }
255
256 if ( $messages->{'NeedsTransfer'} ){
257         $template->param(
258                 found          => 1,
259                 needstransfer  => 1,
260                 itemnumber     => $itemnumber,
261         );
262 }
263
264 if ( $messages->{'Wrongbranch'} ){
265         $template->param(
266                 wrongbranch => 1,
267         );
268 }
269
270 # case of wrong transfert, if the document wasn't transfered to the right library (according to branchtransfer (tobranch) BDD)
271
272 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
273         $template->param(
274         WrongTransfer  => 1,
275         TransferWaitingAt => $messages->{'WrongTransfer'},
276         WrongTransferItem => $messages->{'WrongTransferItem'},
277     );
278
279     my $reserve    = $messages->{'ResFound'};
280     my $branchname = $branches->{ $reserve->{'branchcode'} }->{'branchname'};
281     my ($borr) = GetMemberDetails( $reserve->{'borrowernumber'}, 0 );
282     my $name = $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'};
283     $template->param(
284             wname           => $name,
285             wborfirstname   => $borr->{'firstname'},
286             wborsurname     => $borr->{'surname'},
287             wbortitle       => $borr->{'title'},
288             wborphone       => $borr->{'phone'},
289             wboremail       => $borr->{'email'},
290             wboraddress     => $borr->{'address'},
291             wboraddress2    => $borr->{'address2'},
292             wborcity        => $borr->{'city'},
293             wborzip         => $borr->{'zipcode'},
294             wborrowernumber => $reserve->{'borrowernumber'},
295             wborcnum        => $borr->{'cardnumber'},
296             wtransfertFrom  => $userenv_branch,
297     );
298 }
299
300 #
301 # reserve found and item arrived at the expected branch
302 #
303 if ( $messages->{'ResFound'}) {
304     my $reserve    = $messages->{'ResFound'};
305     my $branchname = $branches->{ $reserve->{'branchcode'} }->{'branchname'};
306     my ($borr) = GetMemberDetails( $reserve->{'borrowernumber'}, 0 );
307
308     if ( $reserve->{'ResFound'} eq "Waiting" or $reserve->{'ResFound'} eq "Reserved" ) {
309         if ( $reserve->{'ResFound'} eq "Waiting" ) {
310             $template->param(
311                 waiting      => ($userenv_branch eq $reserve->{'branchcode'} ? 1 : 0 ),
312             );
313         } elsif ( $reserve->{'ResFound'} eq "Reserved" ) {
314             $template->param(
315                 intransit    => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
316                 transfertodo => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
317                 resbarcode   => $barcode,
318                 reserved     => 1,
319             );
320         }
321
322         # same params for Waiting or Reserved
323         $template->param(
324             found          => 1,
325             currentbranch  => $branches->{$userenv_branch}->{'branchname'},
326             destbranchname => $branches->{ $reserve->{'branchcode'} }->{'branchname'},
327             name           => $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'},
328             borfirstname   => $borr->{'firstname'},
329             borsurname     => $borr->{'surname'},
330             bortitle       => $borr->{'title'},
331             borphone       => $borr->{'phone'},
332             boremail       => $borr->{'email'},
333             boraddress     => $borr->{'address'},
334             boraddress2    => $borr->{'address2'},
335             borcity        => $borr->{'city'},
336             borzip         => $borr->{'zipcode'},
337             borcnum        => $borr->{'cardnumber'},
338             debarred       => $borr->{'debarred'},
339             gonenoaddress  => $borr->{'gonenoaddress'},
340             barcode        => $barcode,
341             destbranch     => $reserve->{'branchcode'},
342             borrowernumber => $reserve->{'borrowernumber'},
343             itemnumber     => $reserve->{'itemnumber'},
344         );
345     } # else { ; }  # error?
346 }
347
348 # Error Messages
349 my @errmsgloop;
350 foreach my $code ( keys %$messages ) {
351     my %err;
352     my $exit_required_p = 0;
353     if ( $code eq 'BadBarcode' ) {
354         $err{badbarcode} = 1;
355         $err{msg}        = $messages->{'BadBarcode'};
356     }
357     elsif ( $code eq 'NotIssued' ) {
358         $err{notissued} = 1;
359         $err{msg} = $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
360     }
361     elsif ( $code eq 'WasLost' ) {
362         $err{waslost} = 1;
363     }
364     elsif ( $code eq 'ResFound' ) {
365         ;    # FIXME... anything to do here?
366     }
367     elsif ( $code eq 'WasReturned' ) {
368         ;    # FIXME... anything to do here?
369     }
370     elsif ( $code eq 'WasTransfered' ) {
371         ;    # FIXME... anything to do here?
372     }
373     elsif ( $code eq 'wthdrawn' ) {
374         $err{withdrawn} = 1;
375         $exit_required_p = 1;
376     }
377     elsif ( ( $code eq 'IsPermanent' ) && ( not $messages->{'ResFound'} ) ) {
378         if ( $messages->{'IsPermanent'} ne $userenv_branch ) {
379             $err{ispermanent} = 1;
380             $err{msg}         =
381               $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
382         }
383     }
384     elsif ( $code eq 'WrongTransfer' ) {
385         ;    # FIXME... anything to do here?
386     }
387     elsif ( $code eq 'WrongTransferItem' ) {
388         ;    # FIXME... anything to do here?
389     }
390     elsif ( $code eq 'NeedsTransfer' ) {
391     }
392     elsif ( $code eq 'Wrongbranch' ) {
393     }
394                 
395     else {
396         die "Unknown error code $code";    # note we need all the (empty) elsif's above, or we die.
397         # This forces the issue of staying in sync w/ Circulation.pm
398     }
399     if (%err) {
400         push( @errmsgloop, \%err );
401     }
402     last if $exit_required_p;
403 }
404 $template->param( errmsgloop => \@errmsgloop );
405
406 # patrontable ....
407 if ($borrower) {
408     my $flags = $borrower->{'flags'};
409     my @flagloop;
410     my $flagset;
411     foreach my $flag ( sort keys %$flags ) {
412         my %flaginfo;
413         unless ($flagset) { $flagset = 1; }
414         $flaginfo{redfont} = ( $flags->{$flag}->{'noissues'} );
415         $flaginfo{flag}    = $flag;
416         if ( $flag eq 'CHARGES' ) {
417             $flaginfo{msg}            = $flag;
418             $flaginfo{charges}        = 1;
419             $flaginfo{chargeamount}   = $flags->{$flag}->{amount};
420             $flaginfo{borrowernumber} = $borrower->{borrowernumber};
421         }
422         elsif ( $flag eq 'WAITING' ) {
423             $flaginfo{msg}     = $flag;
424             $flaginfo{waiting} = 1;
425             my @waitingitemloop;
426             my $items = $flags->{$flag}->{'itemlist'};
427             foreach my $item (@$items) {
428                 my $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'});
429                 push @waitingitemloop, {
430                     biblionum => $biblio->{'biblionumber'},
431                     barcode   => $biblio->{'barcode'},
432                     title     => $biblio->{'title'},
433                     brname    => $branches->{ $biblio->{'holdingbranch'} }->{'branchname'},
434                 };
435             }
436             $flaginfo{itemloop} = \@waitingitemloop;
437         }
438         elsif ( $flag eq 'ODUES' ) {
439             my $items = $flags->{$flag}->{'itemlist'};
440             my @itemloop;
441             foreach my $item ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
442                 @$items )
443             {
444                 my $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'});
445                 push @itemloop, {
446                     duedate   => format_date($item->{'date_due'}),
447                     biblionum => $biblio->{'biblionumber'},
448                     barcode   => $biblio->{'barcode'},
449                     title     => $biblio->{'title'},
450                     brname    => $branches->{ $biblio->{'holdingbranch'} }->{'branchname'},
451                 };
452             }
453             $flaginfo{itemloop} = \@itemloop;
454             $flaginfo{overdue}  = 1;
455         }
456         else {
457             $flaginfo{other} = 1;
458             $flaginfo{msg}   = $flags->{$flag}->{'message'};
459         }
460         push( @flagloop, \%flaginfo );
461     }
462     $template->param(
463         flagset          => $flagset,
464         flagloop         => \@flagloop,
465         riborrowernumber => $borrower->{'borrowernumber'},
466         riborcnum        => $borrower->{'cardnumber'},
467         riborsurname     => $borrower->{'surname'},
468         ribortitle       => $borrower->{'title'},
469         riborfirstname   => $borrower->{'firstname'}
470     );
471 }
472
473 #set up so only the last 8 returned items display (make for faster loading pages)
474 my $returned_counter = ( C4::Context->preference('numReturnedItemsToShow') ) ? C4::Context->preference('numReturnedItemsToShow') : 8;
475 my $count = 0;
476 my @riloop;
477 foreach ( sort { $a <=> $b } keys %returneditems ) {
478     my %ri;
479     if ( $count++ < $returned_counter ) {
480         my $barcode = $returneditems{$_};
481         my $duedate = $riduedate{$_};
482         my $overduetext;
483         my $borrowerinfo;
484         if ($duedate) {
485             my @tempdate = split( /-/, $duedate );
486             $ri{year}  = $tempdate[0];
487             $ri{month} = $tempdate[1];
488             $ri{day}   = $tempdate[2];
489             $ri{duedate} = format_date($duedate);
490             my ($borrower) = GetMemberDetails( $riborrowernumber{$_}, 0 );
491             $ri{return_overdue} = 1 if ($duedate lt $today->output('iso'));
492             $ri{borrowernumber} = $borrower->{'borrowernumber'};
493             $ri{borcnum}        = $borrower->{'cardnumber'};
494             $ri{borfirstname}   = $borrower->{'firstname'};
495             $ri{borsurname}     = $borrower->{'surname'};
496             $ri{bortitle}       = $borrower->{'title'};
497             $ri{bornote}        = $borrower->{'borrowernotes'};
498             $ri{borcategorycode}= $borrower->{'categorycode'};
499         }
500         else {
501             $ri{borrowernumber} = $riborrowernumber{$_};
502         }
503
504         #        my %ri;
505         my $biblio = GetBiblioFromItemNumber(GetItemnumberFromBarcode($barcode));
506         # fix up item type for display
507         $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
508         $ri{itembiblionumber} = $biblio->{'biblionumber'};
509         $ri{itemtitle}        = $biblio->{'title'};
510         $ri{itemauthor}       = $biblio->{'author'};
511         $ri{itemtype}         = $biblio->{'itemtype'};
512         $ri{itemnote}         = $biblio->{'itemnotes'};
513         $ri{ccode}            = $biblio->{'ccode'};
514         $ri{itemnumber}       = $biblio->{'itemnumber'};
515         $ri{barcode}          = $barcode;
516     }
517     else {
518         last;
519     }
520     push( @riloop, \%ri );
521 }
522
523 $template->param(
524     riloop         => \@riloop,
525     genbrname      => $branches->{$userenv_branch}->{'branchname'},
526     genprname      => $printers->{$printer}->{'printername'},
527     branchname     => $branches->{$userenv_branch}->{'branchname'},
528     printer        => $printer,
529     errmsgloop     => \@errmsgloop,
530     exemptfine     => $exemptfine,
531     dropboxmode    => $dropboxmode,
532     dropboxdate    => $dropboxdate->output(),
533     overduecharges => $overduecharges,
534 );
535
536 # actually print the page!
537 output_html_with_http_headers $query, $cookie, $template->output;