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