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