fix for #946
[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 CGI;
30 use C4::Context;
31 use C4::Auth qw/:DEFAULT get_session/;
32 use C4::Output;
33 use C4::Circulation;
34 use C4::Dates qw/format_date/;
35 use Date::Calc qw/Add_Delta_Days/;
36 use C4::Calendar;
37 use C4::Print;
38 use C4::Reserves;
39 use C4::Biblio;
40 use C4::Items;
41 use C4::Members;
42 use C4::Branch; # GetBranchName
43 use C4::Koha;   # FIXME : is it still useful ?
44
45 my $query = new CGI;
46
47 if (!C4::Context->userenv){
48         my $sessionID = $query->cookie("CGISESSID");
49         my $session = get_session($sessionID);
50         if ($session->param('branch') eq 'NO_LIBRARY_SET'){
51                 # no branch set we can't return
52                 print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
53                 exit;
54         }
55
56
57 #getting the template
58 my ( $template, $librarian, $cookie ) = get_template_and_user(
59     {
60         template_name   => "circ/returns.tmpl",
61         query           => $query,
62         type            => "intranet",
63         authnotrequired => 0,
64         flagsrequired   => { circulate => 1 },
65     }
66 );
67
68 #####################
69 #Global vars
70 my $branches = GetBranches();
71 my $printers = GetPrinters();
72
73 #my $branch  = C4::Context->userenv?C4::Context->userenv->{'branch'}:"";
74 my $printer = C4::Context->userenv?C4::Context->userenv->{'branchprinter'}:"";
75 my $overduecharges = (C4::Context->preference('finesMode') && C4::Context->preference('finesMode') ne 'off');
76 #
77 # Some code to handle the error if there is no branch or printer setting.....
78 #
79
80 # Set up the item stack ....
81 my %returneditems;
82 my %riduedate;
83 my %riborrowernumber;
84 my @inputloop;
85 foreach ( $query->param ) {
86     (next) unless (/ri-(\d*)/);
87     my %input;
88     my $counter = $1;
89     (next) if ( $counter > 20 );
90     my $barcode        = $query->param("ri-$counter");
91     my $duedate        = $query->param("dd-$counter");
92     my $borrowernumber = $query->param("bn-$counter");
93     $counter++;
94
95     # decode barcode
96     $barcode = barcodedecode($barcode) if(C4::Context->preference('itemBarcodeInputFilter'));
97
98     ######################
99     #Are these lines still useful ?
100     $returneditems{$counter}    = $barcode;
101     $riduedate{$counter}        = $duedate;
102     $riborrowernumber{$counter} = $borrowernumber;
103
104     #######################
105     $input{counter}        = $counter;
106     $input{barcode}        = $barcode;
107     $input{duedate}        = $duedate;
108     $input{borrowernumber} = $borrowernumber;
109     push( @inputloop, \%input );
110 }
111
112 ############
113 # Deal with the requests....
114
115 if ($query->param('WT-itemNumber')){
116         updateWrongTransfer ($query->param('WT-itemNumber'),$query->param('WT-waitingAt'),$query->param('WT-From'));
117 }
118
119 if ( $query->param('resbarcode') ) {
120     my $item           = $query->param('itemnumber');
121     my $borrowernumber = $query->param('borrowernumber');
122     my $resbarcode     = $query->param('resbarcode');
123     my $diffBranchReturned = $query->param('diffBranch');
124     # set to waiting....
125     my $iteminfo   = GetBiblioFromItemNumber($item);
126     # fix up item type for display
127     $iteminfo->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $iteminfo->{'itype'} : $iteminfo->{'itemtype'};
128     my $diffBranchSend;
129     
130 #     addin in ModReserveAffect the possibility to check if the document is expected in this library or not,
131 # if not we send a value in reserve waiting for not implementting waiting status
132     if ($diffBranchReturned) {
133         $diffBranchSend = $diffBranchReturned;
134     }
135     else {
136         $diffBranchSend = undef;
137     }
138     ModReserveAffect( $item, $borrowernumber,$diffBranchSend);
139 #   check if we have other reservs for this document, if we have a return send the message of transfer
140     my ( $messages, $nextreservinfo ) = GetOtherReserves($item);
141
142     my $branchname = GetBranchName( $messages->{'transfert'} );
143     my ($borr) = GetMemberDetails( $nextreservinfo, 0 );
144     my $borcnum = $borr->{'cardnumber'};
145     my $name    =
146       $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'};
147     my $slip = $query->param('resslip');
148
149
150     if ( $messages->{'transfert'} ) {
151         $template->param(
152             itemtitle      => $iteminfo->{'title'},
153                         itembiblionumber => $iteminfo->{'biblionumber'},
154             iteminfo       => $iteminfo->{'author'},
155             tobranchname   => $branchname,
156             name           => $name,
157             borrowernumber => $borrowernumber,
158             borcnum        => $borcnum,
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 $barcode = $query->param('barcode');
171 # strip whitespace
172 # $barcode =~ s/\s*//g; - use barcodedecode for this; whitespace is not invalid.
173 my $exemptfine = $query->param('exemptfine');
174 my $dropboxmode= $query->param('dropboxmode');
175 my $calendar = C4::Calendar->new(  branchcode => C4::Context->userenv->{'branch'} );
176         #dropbox: get last open day (today - 1)
177 my $dropboxdate = $calendar->addDate(C4::Dates->new(), -1 );
178 my $dotransfer = $query->param('dotransfer');
179 if ($dotransfer){
180         # An item has been returned to a branch other than the homebranch, and the librarian has choosen to initiate a transfer
181         my $transferitem=$query->param('transferitem');
182         my $tobranch=$query->param('tobranch');
183         ModItemTransfer($transferitem, C4::Context->userenv->{'branch'}, $tobranch); 
184 }
185
186 # actually return book and prepare item table.....
187 if ($barcode) {
188     $barcode = barcodedecode($barcode)  if(C4::Context->preference('itemBarcodeInputFilter'));
189 #
190 # save the return
191 #
192     ( $returned, $messages, $issueinformation, $borrower ) =
193       AddReturn( $barcode, C4::Context->userenv->{'branch'}, $exemptfine, $dropboxmode);
194     # get biblio description
195     my $biblio = GetBiblioFromItemNumber($issueinformation->{'itemnumber'});
196     # fix up item type for display
197     $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
198
199     $template->param(
200         title            => $biblio->{'title'},
201         homebranch       => $biblio->{'homebranch'},
202         author           => $biblio->{'author'},
203         itembarcode      => $biblio->{'barcode'},
204         itemtype         => $biblio->{'itemtype'},
205         ccode            => $biblio->{'ccode'},
206         itembiblionumber => $biblio->{'biblionumber'},    
207     );
208     if ($returned) {
209         $returneditems{0}    = $barcode;
210         $riborrowernumber{0} = $borrower->{'borrowernumber'};
211         $riduedate{0}        = $issueinformation->{'date_due'};
212         my %input;
213         $input{counter}        = 0;
214         $input{first}          = 1;
215         $input{barcode}        = $barcode;
216         $input{duedate}        = $riduedate{0};
217         $input{borrowernumber} = $riborrowernumber{0};
218         push( @inputloop, \%input );
219
220         # check if the branch is the same as homebranch
221         # if not, we want to put a message
222         if ( $biblio->{'homebranch'} ne C4::Context->userenv->{'branch'} ) {
223             $template->param( homebranch => $biblio->{'homebranch'} );
224         }
225     }
226     elsif ( !$messages->{'BadBarcode'} ) {
227         my %input;
228         $input{counter} = 0;
229         $input{first}   = 1;
230         $input{barcode} = $barcode;
231         $input{duedate} = 0;
232
233         $returneditems{0} = $barcode;
234         $riduedate{0}     = 0;
235         if ( $messages->{'wthdrawn'} ) {
236             $input{withdrawn}      = 1;
237             $input{borrowernumber} = "Item Cancelled";
238             $riborrowernumber{0}   = 'Item Cancelled';
239         }
240         else {
241             $input{borrowernumber} = " ";
242             $riborrowernumber{0} = ' ';
243         }
244         push( @inputloop, \%input );
245     }
246 }
247 $template->param( inputloop => \@inputloop );
248
249 my $found    = 0;
250 my $waiting  = 0;
251 my $reserved = 0;
252
253 # new op dev : we check if the document must be returned to his homebranch directly,
254 #  if the document is transfered, we have warning message .
255
256 if ( $messages->{'WasTransfered'} ) {
257     $template->param(
258         found          => 1,
259         transfer       => 1,
260     );
261 }
262
263 if ( $messages->{'NeedsTransfer'} ){
264         $template->param(
265                 found          => 1,
266                 needstransfer  => 1,
267                 itemnumber => $issueinformation->{'itemnumber'}
268         );
269 }
270
271 if ( $messages->{'Wrongbranch'} ){
272         $template->param(
273                 wrongbranch => 1,
274         );
275 }
276
277 # adding a case of wrong transfert, if the document wasn't transfered in the good library (according to branchtransfer (tobranch) BDD)
278
279 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
280         $template->param(
281         WrongTransfer  => 1,
282         TransferWaitingAt => $messages->{'WrongTransfer'},
283         WrongTransferItem => $messages->{'WrongTransferItem'},
284     );
285
286     my $reserve        = $messages->{'ResFound'};
287     my $branchname = $branches->{ $reserve->{'branchcode'} }->{'branchname'};
288     my ($borr) = GetMemberDetails( $reserve->{'borrowernumber'}, 0 );
289     my $name =
290       $borr->{'surname'} . " " . $borr->{'title'} . " " . $borr->{'firstname'};
291         $template->param(
292             wname           => $name,
293             wborfirstname   => $borr->{'firstname'},
294             wborsurname     => $borr->{'surname'},
295             wbortitle       => $borr->{'title'},
296             wborphone       => $borr->{'phone'},
297             wboremail       => $borr->{'email'},
298             wboraddress  => $borr->{'address'},
299             wboraddress2 => $borr->{'address2'},
300             wborcity        => $borr->{'city'},
301             wborzip         => $borr->{'zipcode'},
302             wborrowernumber => $reserve->{'borrowernumber'},
303             wborcnum        => $borr->{'cardnumber'},
304             wtransfertFrom    => C4::Context->userenv->{'branch'},
305         );
306 }
307
308
309 #
310 # reserve found and item arrived at the expected branch
311 #
312 if ( $messages->{'ResFound'}) {
313     my $reserve        = $messages->{'ResFound'};
314     my $branchname = $branches->{ $reserve->{'branchcode'} }->{'branchname'};
315     my ($borr) = GetMemberDetails( $reserve->{'borrowernumber'}, 0 );
316     if ( $reserve->{'ResFound'} eq "Waiting" ) {
317         if ( C4::Context->userenv->{'branch'} eq $reserve->{'branchcode'} ) {
318             $template->param( waiting => 1 );
319         }
320         else {
321             $template->param( waiting => 0 );
322         }
323
324         $template->param(
325             found          => 1,
326             name           => $borr->{'surname'} . " " . $borr->{'title'} . " " . $borr->{'firstname'},
327             borfirstname   => $borr->{'firstname'},
328             borsurname     => $borr->{'surname'},
329             bortitle       => $borr->{'title'},
330             borphone       => $borr->{'phone'},
331             boremail       => $borr->{'email'},
332             boraddress  => $borr->{'address'},
333             boraddress2  => $borr->{'address2'},
334             borcity        => $borr->{'city'},
335             borzip         => $borr->{'zipcode'},
336             borrowernumber => $reserve->{'borrowernumber'},
337             borcnum        => $borr->{'cardnumber'},
338             debarred       => $borr->{'debarred'},
339             gonenoaddress  => $borr->{'gonenoaddress'},
340             currentbranch  => $branches->{C4::Context->userenv->{'branch'}}->{'branchname'},
341             itemnumber       => $reserve->{'itemnumber'},
342             barcode     => $barcode,
343             destbranchname =>
344               $branches->{ $reserve->{'branchcode'} }->{'branchname'},
345             destbranch     => $reserve->{'branchcode'},
346         );
347
348     }
349     if ( $reserve->{'ResFound'} eq "Reserved" ) {
350        # my @da         = localtime( time() );
351        # my $todaysdate = sprintf( "%0.2d/%0.2d/%0.4d", ( $datearr[3] + 1 ),( $datearr[4] + 1 ),( $datearr[5] + 1900 ) );
352                 # FIXME - use Dates obj , locale. AND, why [4]+1 ??
353         if ( C4::Context->userenv->{'branch'} eq $reserve->{'branchcode'} ) {
354             $template->param( intransit => 0 );
355         }
356         else {
357             $template->param( intransit => 1 );
358         }
359
360         $template->param(
361             found          => 1,
362             currentbranch  => $branches->{C4::Context->userenv->{'branch'}}->{'branchname'},
363             destbranchname =>
364               $branches->{ $reserve->{'branchcode'} }->{'branchname'},
365             destbranch     => $reserve->{'branchcode'},
366             transfertodo => ( C4::Context->userenv->{'branch'} eq $reserve->{'branchcode'} ? 0 : 1 ),
367             reserved => 1,
368             resbarcode       => $barcode,
369           #  today            => $todaysdate,
370             itemnumber       => $reserve->{'itemnumber'},
371             borsurname       => $borr->{'surname'},
372             bortitle         => $borr->{'title'},
373             borfirstname     => $borr->{'firstname'},
374             borrowernumber   => $reserve->{'borrowernumber'},
375             borcnum          => $borr->{'cardnumber'},
376             borphone         => $borr->{'phone'},
377             boraddress    => $borr->{'address'},
378             boraddress2    => $borr->{'address2'},
379             borsub           => $borr->{'suburb'},
380             borcity          => $borr->{'city'},
381             borzip           => $borr->{'zipcode'},
382             boremail         => $borr->{'email'},
383             debarred         => $borr->{'debarred'},
384             gonenoaddress    => $borr->{'gonenoaddress'},
385             barcode          => $barcode
386         );
387     }
388 }
389
390 # Error Messages
391 my @errmsgloop;
392 foreach my $code ( keys %$messages ) {
393
394     #    warn $code;
395     my %err;
396     my $exit_required_p = 0;
397     if ( $code eq 'BadBarcode' ) {
398         $err{badbarcode} = 1;
399         $err{msg}        = $messages->{'BadBarcode'};
400     }
401     elsif ( $code eq 'NotIssued' ) {
402         $err{notissued} = 1;
403         $err{msg} = $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
404     }
405     elsif ( $code eq 'WasLost' ) {
406         $err{waslost} = 1;
407     }
408     elsif ( $code eq 'ResFound' ) {
409         ;    # FIXME... anything to do here?
410     }
411     elsif ( $code eq 'WasReturned' ) {
412         ;    # FIXME... anything to do here?
413     }
414     elsif ( $code eq 'WasTransfered' ) {
415         ;    # FIXME... anything to do here?
416     }
417     elsif ( $code eq 'wthdrawn' ) {
418         $err{withdrawn} = 1;
419         $exit_required_p = 1;
420     }
421     elsif ( ( $code eq 'IsPermanent' ) && ( not $messages->{'ResFound'} ) ) {
422         if ( $messages->{'IsPermanent'} ne C4::Context->userenv->{'branch'} ) {
423             $err{ispermanent} = 1;
424             $err{msg}         =
425               $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
426         }
427     }
428     elsif ( $code eq 'WrongTransfer' ) {
429         ;    # FIXME... anything to do here?
430     }
431     elsif ( $code eq 'WrongTransferItem' ) {
432         ;    # FIXME... anything to do here?
433     }
434         elsif ( $code eq 'NeedsTransfer' ) {
435         }
436         elsif ( $code eq 'Wrongbranch' ) {
437         }
438                 
439     else {
440         die "Unknown error code $code";    # XXX
441     }
442     if (%err) {
443         push( @errmsgloop, \%err );
444     }
445     last if $exit_required_p;
446 }
447 $template->param( errmsgloop => \@errmsgloop );
448
449 # patrontable ....
450 if ($borrower) {
451     my $flags = $borrower->{'flags'};
452     my @flagloop;
453     my $flagset;
454     foreach my $flag ( sort keys %$flags ) {
455         my %flaginfo;
456         unless ($flagset) { $flagset = 1; }
457         $flaginfo{redfont} = ( $flags->{$flag}->{'noissues'} );
458         $flaginfo{flag}    = $flag;
459         if ( $flag eq 'CHARGES' ) {
460             $flaginfo{msg}            = $flag;
461             $flaginfo{charges}        = 1;
462             $flaginfo{chargeamount}   = $flags->{$flag}->{amount};
463             $flaginfo{borrowernumber} = $borrower->{borrowernumber};
464         }
465         elsif ( $flag eq 'WAITING' ) {
466             $flaginfo{msg}     = $flag;
467             $flaginfo{waiting} = 1;
468             my @waitingitemloop;
469             my $items = $flags->{$flag}->{'itemlist'};
470             foreach my $item (@$items) {
471                 my $biblio =
472                   GetBiblioFromItemNumber( $item->{'itemnumber'});
473                 my %waitingitem;
474                 $waitingitem{biblionum} = $biblio->{'biblionumber'};
475                 $waitingitem{barcode}   = $biblio->{'barcode'};
476                 $waitingitem{title}     = $biblio->{'title'};
477                 $waitingitem{brname}    =
478                   $branches->{ $biblio->{'holdingbranch'} }
479                   ->{'branchname'};
480                 push( @waitingitemloop, \%waitingitem );
481             }
482             $flaginfo{itemloop} = \@waitingitemloop;
483         }
484         elsif ( $flag eq 'ODUES' ) {
485             my $items = $flags->{$flag}->{'itemlist'};
486             my @itemloop;
487             foreach my $item ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
488                 @$items )
489             {
490                 my $biblio =
491                   GetBiblioFromItemNumber( $item->{'itemnumber'});
492                 my %overdueitem;
493                 $overdueitem{duedate}   = format_date( $item->{'date_due'} );
494                 $overdueitem{biblionum} = $biblio->{'biblionumber'};
495                 $overdueitem{barcode}   = $biblio->{'barcode'};
496                 $overdueitem{title}     = $biblio->{'title'};
497                 $overdueitem{brname}    =
498                   $branches->{ $biblio->{'holdingbranch'} }
499                   ->{'branchname'};
500                 push( @itemloop, \%overdueitem );
501             }
502             $flaginfo{itemloop} = \@itemloop;
503             $flaginfo{overdue}  = 1;
504         }
505         else {
506             $flaginfo{other} = 1;
507             $flaginfo{msg}   = $flags->{$flag}->{'message'};
508         }
509         push( @flagloop, \%flaginfo );
510     }
511     $template->param(
512         flagset          => $flagset,
513         flagloop         => \@flagloop,
514         riborrowernumber => $borrower->{'borrowernumber'},
515         riborcnum        => $borrower->{'cardnumber'},
516         riborsurname     => $borrower->{'surname'},
517         ribortitle       => $borrower->{'title'},
518         riborfirstname   => $borrower->{'firstname'}
519     );
520 }
521
522 #set up so only the last 8 returned items display (make for faster loading pages)
523 my $count = 0;
524 my @riloop;
525 foreach ( sort { $a <=> $b } keys %returneditems ) {
526     my %ri;
527     if ( $count < 8 ) {
528         my $barcode = $returneditems{$_};
529         my $duedate = $riduedate{$_};
530         my $overduetext;
531         my $borrowerinfo;
532         if ($duedate) {
533             my @tempdate = split( /-/, $duedate );
534             $ri{year}  = $tempdate[0];
535             $ri{month} = $tempdate[1];
536             $ri{day}   = $tempdate[2];
537             my $duedatenz  = "$tempdate[2]/$tempdate[1]/$tempdate[0]";
538             my @datearr    = localtime( time() );
539             my $todaysdate =
540                 $datearr[5] . '-'
541               . sprintf( "%0.2d", ( $datearr[4] + 1 ) ) . '-'
542               . sprintf( "%0.2d", $datearr[3] );
543                   # FIXME - todaysdate isn't used, and what date _is_ it ?
544             $ri{duedate} = format_date($duedate);
545             my ($borrower) =
546               GetMemberDetails( $riborrowernumber{$_}, 0 );
547             $ri{borrowernumber} = $borrower->{'borrowernumber'};
548             $ri{borcnum}        = $borrower->{'cardnumber'};
549             $ri{borfirstname}   = $borrower->{'firstname'};
550             $ri{borsurname}     = $borrower->{'surname'};
551             $ri{bortitle}       = $borrower->{'title'};
552             $ri{bornote}        = $borrower->{'borrowernotes'};
553             $ri{borcategorycode}   = $borrower->{'categorycode'};
554         }
555         else {
556             $ri{borrowernumber} = $riborrowernumber{$_};
557         }
558
559         #        my %ri;
560         my $biblio = GetBiblioFromItemNumber(GetItemnumberFromBarcode($barcode));
561         # fix up item type for display
562         $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
563         $ri{itembiblionumber} = $biblio->{'biblionumber'};
564         $ri{itemtitle}        = $biblio->{'title'};
565         $ri{itemauthor}       = $biblio->{'author'};
566         $ri{itemtype}         = $biblio->{'itemtype'};
567         $ri{itemnote}         = $biblio->{'itemnotes'};
568         $ri{ccode}            = $biblio->{'ccode'};
569         $ri{itemnumber}       = $biblio->{'itemnumber'};
570         $ri{barcode}          = $barcode;
571     }
572     else {
573         last;
574     }
575     $count++;
576     push( @riloop, \%ri );
577 }
578 $template->param( riloop => \@riloop );
579
580 $template->param(
581     genbrname               => $branches->{C4::Context->userenv->{'branch'}}->{'branchname'},
582     genprname               => $printers->{$printer}->{'printername'},
583     branchname              => $branches->{C4::Context->userenv->{'branch'}}->{'branchname'},
584     printer                 => $printer,
585     errmsgloop              => \@errmsgloop,
586     exemptfine              => $exemptfine,
587     dropboxmode              => $dropboxmode,
588     dropboxdate                         => $dropboxdate->output(),
589         overduecharges          => $overduecharges,
590 );
591
592 # actually print the page!
593 output_html_with_http_headers $query, $cookie, $template->output;