5a5b4a314c87275c13f40bb92d7d1a05c81ca3a1
[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     $itemnumber = GetItemnumberFromBarcode($barcode);
181
182     ( $returned, $messages, $issueinformation, $borrower ) =
183       AddReturn( $barcode, $userenv_branch, $exemptfine, $dropboxmode);     # do the return
184
185     # get biblio description
186     my $biblio = GetBiblioFromItemNumber($itemnumber);
187     # fix up item type for display
188     $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
189
190     $template->param(
191         title            => $biblio->{'title'},
192         homebranch       => $biblio->{'homebranch'},
193         author           => $biblio->{'author'},
194         itembarcode      => $biblio->{'barcode'},
195         itemtype         => $biblio->{'itemtype'},
196         ccode            => $biblio->{'ccode'},
197         itembiblionumber => $biblio->{'biblionumber'},    
198     );
199
200     my %input = (
201         counter => 0,
202         first   => 1,
203         barcode => $barcode,
204     );
205
206     if ($returned) {
207         my $duedate = $issueinformation->{'date_due'};
208         $returneditems{0}      = $barcode;
209         $riborrowernumber{0}   = $borrower->{'borrowernumber'};
210         $riduedate{0}          = $duedate;
211         $input{borrowernumber} = $borrower->{'borrowernumber'};
212         $input{duedate}        = $duedate;
213         $input{return_overdue} = 1 if ($duedate and $duedate lt $today->output('iso'));
214         push( @inputloop, \%input );
215     }
216     elsif ( !$messages->{'BadBarcode'} ) {
217         $input{duedate}   = 0;
218         $returneditems{0} = $barcode;
219         $riduedate{0}     = 0;
220         if ( $messages->{'wthdrawn'} ) {
221             $input{withdrawn}      = 1;
222             $input{borrowernumber} = 'Item Cancelled';  # FIXME: should be in display layer ?
223             $riborrowernumber{0}   = 'Item Cancelled';
224         }
225         else {
226             $input{borrowernumber} = ' ';  # This seems clearly bogus.
227             $riborrowernumber{0}   = ' ';
228         }
229         push( @inputloop, \%input );
230     }
231 }
232 $template->param( inputloop => \@inputloop );
233
234 my $found    = 0;
235 my $waiting  = 0;
236 my $reserved = 0;
237
238 # new op dev : we check if the document must be returned to his homebranch directly,
239 #  if the document is transfered, we have warning message .
240
241 if ( $messages->{'WasTransfered'} ) {
242     $template->param(
243         found          => 1,
244         transfer       => 1,
245     );
246 }
247
248 if ( $messages->{'NeedsTransfer'} ){
249         $template->param(
250                 found          => 1,
251                 needstransfer  => 1,
252                 itemnumber     => $itemnumber,
253         );
254 }
255
256 if ( $messages->{'Wrongbranch'} ){
257         $template->param(
258                 wrongbranch => 1,
259         );
260 }
261
262 # case of wrong transfert, if the document wasn't transfered to the right library (according to branchtransfer (tobranch) BDD)
263
264 if ( $messages->{'WrongTransfer'} and not $messages->{'WasTransfered'}) {
265         $template->param(
266         WrongTransfer  => 1,
267         TransferWaitingAt => $messages->{'WrongTransfer'},
268         WrongTransferItem => $messages->{'WrongTransferItem'},
269     );
270
271     my $reserve    = $messages->{'ResFound'};
272     my $branchname = $branches->{ $reserve->{'branchcode'} }->{'branchname'};
273     my ($borr) = GetMemberDetails( $reserve->{'borrowernumber'}, 0 );
274     my $name = $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'};
275     $template->param(
276             wname           => $name,
277             wborfirstname   => $borr->{'firstname'},
278             wborsurname     => $borr->{'surname'},
279             wbortitle       => $borr->{'title'},
280             wborphone       => $borr->{'phone'},
281             wboremail       => $borr->{'email'},
282             wboraddress     => $borr->{'address'},
283             wboraddress2    => $borr->{'address2'},
284             wborcity        => $borr->{'city'},
285             wborzip         => $borr->{'zipcode'},
286             wborrowernumber => $reserve->{'borrowernumber'},
287             wborcnum        => $borr->{'cardnumber'},
288             wtransfertFrom  => $userenv_branch,
289     );
290 }
291
292 #
293 # reserve found and item arrived at the expected branch
294 #
295 if ( $messages->{'ResFound'}) {
296     my $reserve    = $messages->{'ResFound'};
297     my $branchname = $branches->{ $reserve->{'branchcode'} }->{'branchname'};
298     my ($borr) = GetMemberDetails( $reserve->{'borrowernumber'}, 0 );
299
300     if ( $reserve->{'ResFound'} eq "Waiting" or $reserve->{'ResFound'} eq "Reserved" ) {
301         if ( $reserve->{'ResFound'} eq "Waiting" ) {
302             $template->param(
303                 waiting      => ($userenv_branch eq $reserve->{'branchcode'} ? 1 : 0 ),
304             );
305         } elsif ( $reserve->{'ResFound'} eq "Reserved" ) {
306             $template->param(
307                 intransit    => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
308                 transfertodo => ($userenv_branch eq $reserve->{'branchcode'} ? 0 : 1 ),
309                 resbarcode   => $barcode,
310                 reserved     => 1,
311             );
312         }
313
314         # same params for Waiting or Reserved
315         $template->param(
316             found          => 1,
317             currentbranch  => $branches->{$userenv_branch}->{'branchname'},
318             destbranchname => $branches->{ $reserve->{'branchcode'} }->{'branchname'},
319             name           => $borr->{'surname'} . ", " . $borr->{'title'} . " " . $borr->{'firstname'},
320             borfirstname   => $borr->{'firstname'},
321             borsurname     => $borr->{'surname'},
322             bortitle       => $borr->{'title'},
323             borphone       => $borr->{'phone'},
324             boremail       => $borr->{'email'},
325             boraddress     => $borr->{'address'},
326             boraddress2    => $borr->{'address2'},
327             borcity        => $borr->{'city'},
328             borzip         => $borr->{'zipcode'},
329             borcnum        => $borr->{'cardnumber'},
330             debarred       => $borr->{'debarred'},
331             gonenoaddress  => $borr->{'gonenoaddress'},
332             barcode        => $barcode,
333             destbranch     => $reserve->{'branchcode'},
334             borrowernumber => $reserve->{'borrowernumber'},
335             itemnumber     => $reserve->{'itemnumber'},
336         );
337     } # else { ; }  # error?
338 }
339
340 # Error Messages
341 my @errmsgloop;
342 foreach my $code ( keys %$messages ) {
343     my %err;
344     my $exit_required_p = 0;
345     if ( $code eq 'BadBarcode' ) {
346         $err{badbarcode} = 1;
347         $err{msg}        = $messages->{'BadBarcode'};
348     }
349     elsif ( $code eq 'NotIssued' ) {
350         $err{notissued} = 1;
351         $err{msg} = $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
352     }
353     elsif ( $code eq 'WasLost' ) {
354         $err{waslost} = 1;
355     }
356     elsif ( $code eq 'ResFound' ) {
357         ;    # FIXME... anything to do here?
358     }
359     elsif ( $code eq 'WasReturned' ) {
360         ;    # FIXME... anything to do here?
361     }
362     elsif ( $code eq 'WasTransfered' ) {
363         ;    # FIXME... anything to do here?
364     }
365     elsif ( $code eq 'wthdrawn' ) {
366         $err{withdrawn} = 1;
367         $exit_required_p = 1;
368     }
369     elsif ( ( $code eq 'IsPermanent' ) && ( not $messages->{'ResFound'} ) ) {
370         if ( $messages->{'IsPermanent'} ne $userenv_branch ) {
371             $err{ispermanent} = 1;
372             $err{msg}         =
373               $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
374         }
375     }
376     elsif ( $code eq 'WrongTransfer' ) {
377         ;    # FIXME... anything to do here?
378     }
379     elsif ( $code eq 'WrongTransferItem' ) {
380         ;    # FIXME... anything to do here?
381     }
382     elsif ( $code eq 'NeedsTransfer' ) {
383     }
384     elsif ( $code eq 'Wrongbranch' ) {
385     }
386                 
387     else {
388         die "Unknown error code $code";    # note we need all the (empty) elsif's above, or we die.
389         # This forces the issue of staying in sync w/ Circulation.pm
390     }
391     if (%err) {
392         push( @errmsgloop, \%err );
393     }
394     last if $exit_required_p;
395 }
396 $template->param( errmsgloop => \@errmsgloop );
397
398 # patrontable ....
399 if ($borrower) {
400     my $flags = $borrower->{'flags'};
401     my @flagloop;
402     my $flagset;
403     foreach my $flag ( sort keys %$flags ) {
404         my %flaginfo;
405         unless ($flagset) { $flagset = 1; }
406         $flaginfo{redfont} = ( $flags->{$flag}->{'noissues'} );
407         $flaginfo{flag}    = $flag;
408         if ( $flag eq 'CHARGES' ) {
409             $flaginfo{msg}            = $flag;
410             $flaginfo{charges}        = 1;
411             $flaginfo{chargeamount}   = $flags->{$flag}->{amount};
412             $flaginfo{borrowernumber} = $borrower->{borrowernumber};
413         }
414         elsif ( $flag eq 'WAITING' ) {
415             $flaginfo{msg}     = $flag;
416             $flaginfo{waiting} = 1;
417             my @waitingitemloop;
418             my $items = $flags->{$flag}->{'itemlist'};
419             foreach my $item (@$items) {
420                 my $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'});
421                 push @waitingitemloop, {
422                     biblionum => $biblio->{'biblionumber'},
423                     barcode   => $biblio->{'barcode'},
424                     title     => $biblio->{'title'},
425                     brname    => $branches->{ $biblio->{'holdingbranch'} }->{'branchname'},
426                 };
427             }
428             $flaginfo{itemloop} = \@waitingitemloop;
429         }
430         elsif ( $flag eq 'ODUES' ) {
431             my $items = $flags->{$flag}->{'itemlist'};
432             my @itemloop;
433             foreach my $item ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
434                 @$items )
435             {
436                 my $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'});
437                 push @itemloop, {
438                     duedate   => format_date($item->{'date_due'}),
439                     biblionum => $biblio->{'biblionumber'},
440                     barcode   => $biblio->{'barcode'},
441                     title     => $biblio->{'title'},
442                     brname    => $branches->{ $biblio->{'holdingbranch'} }->{'branchname'},
443                 };
444             }
445             $flaginfo{itemloop} = \@itemloop;
446             $flaginfo{overdue}  = 1;
447         }
448         else {
449             $flaginfo{other} = 1;
450             $flaginfo{msg}   = $flags->{$flag}->{'message'};
451         }
452         push( @flagloop, \%flaginfo );
453     }
454     $template->param(
455         flagset          => $flagset,
456         flagloop         => \@flagloop,
457         riborrowernumber => $borrower->{'borrowernumber'},
458         riborcnum        => $borrower->{'cardnumber'},
459         riborsurname     => $borrower->{'surname'},
460         ribortitle       => $borrower->{'title'},
461         riborfirstname   => $borrower->{'firstname'}
462     );
463 }
464
465 #set up so only the last 8 returned items display (make for faster loading pages)
466 my $count = 0;
467 my @riloop;
468 foreach ( sort { $a <=> $b } keys %returneditems ) {
469     my %ri;
470     if ( $count++ < 8 ) {
471         my $barcode = $returneditems{$_};
472         my $duedate = $riduedate{$_};
473         my $overduetext;
474         my $borrowerinfo;
475         if ($duedate) {
476             my @tempdate = split( /-/, $duedate );
477             $ri{year}  = $tempdate[0];
478             $ri{month} = $tempdate[1];
479             $ri{day}   = $tempdate[2];
480             $ri{duedate} = format_date($duedate);
481             my ($borrower) = GetMemberDetails( $riborrowernumber{$_}, 0 );
482             $ri{return_overdue} = 1 if ($duedate lt $today->output('iso'));
483             $ri{borrowernumber} = $borrower->{'borrowernumber'};
484             $ri{borcnum}        = $borrower->{'cardnumber'};
485             $ri{borfirstname}   = $borrower->{'firstname'};
486             $ri{borsurname}     = $borrower->{'surname'};
487             $ri{bortitle}       = $borrower->{'title'};
488             $ri{bornote}        = $borrower->{'borrowernotes'};
489             $ri{borcategorycode}= $borrower->{'categorycode'};
490         }
491         else {
492             $ri{borrowernumber} = $riborrowernumber{$_};
493         }
494
495         #        my %ri;
496         my $biblio = GetBiblioFromItemNumber(GetItemnumberFromBarcode($barcode));
497         # fix up item type for display
498         $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
499         $ri{itembiblionumber} = $biblio->{'biblionumber'};
500         $ri{itemtitle}        = $biblio->{'title'};
501         $ri{itemauthor}       = $biblio->{'author'};
502         $ri{itemtype}         = $biblio->{'itemtype'};
503         $ri{itemnote}         = $biblio->{'itemnotes'};
504         $ri{ccode}            = $biblio->{'ccode'};
505         $ri{itemnumber}       = $biblio->{'itemnumber'};
506         $ri{barcode}          = $barcode;
507     }
508     else {
509         last;
510     }
511     push( @riloop, \%ri );
512 }
513
514 $template->param(
515     riloop         => \@riloop,
516     genbrname      => $branches->{$userenv_branch}->{'branchname'},
517     genprname      => $printers->{$printer}->{'printername'},
518     branchname     => $branches->{$userenv_branch}->{'branchname'},
519     printer        => $printer,
520     errmsgloop     => \@errmsgloop,
521     exemptfine     => $exemptfine,
522     dropboxmode    => $dropboxmode,
523     dropboxdate    => $dropboxdate->output(),
524     overduecharges => $overduecharges,
525 );
526
527 # actually print the page!
528 output_html_with_http_headers $query, $cookie, $template->output;