Bug#: 3358 File 1 of 3 patch for reserve notes (show)
[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             reservenotes   => $reserve->{'reservenotes'},
337         );
338     } # else { ; }  # error?
339 }
340
341 # Error Messages
342 my @errmsgloop;
343 foreach my $code ( keys %$messages ) {
344     my %err;
345     my $exit_required_p = 0;
346     if ( $code eq 'BadBarcode' ) {
347         $err{badbarcode} = 1;
348         $err{msg}        = $messages->{'BadBarcode'};
349     }
350     elsif ( $code eq 'NotIssued' ) {
351         $err{notissued} = 1;
352         $err{msg} = $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
353     }
354     elsif ( $code eq 'WasLost' ) {
355         $err{waslost} = 1;
356     }
357     elsif ( $code eq 'ResFound' ) {
358         ;    # FIXME... anything to do here?
359     }
360     elsif ( $code eq 'WasReturned' ) {
361         ;    # FIXME... anything to do here?
362     }
363     elsif ( $code eq 'WasTransfered' ) {
364         ;    # FIXME... anything to do here?
365     }
366     elsif ( $code eq 'wthdrawn' ) {
367         $err{withdrawn} = 1;
368         $exit_required_p = 1;
369     }
370     elsif ( ( $code eq 'IsPermanent' ) && ( not $messages->{'ResFound'} ) ) {
371         if ( $messages->{'IsPermanent'} ne $userenv_branch ) {
372             $err{ispermanent} = 1;
373             $err{msg}         =
374               $branches->{ $messages->{'IsPermanent'} }->{'branchname'};
375         }
376     }
377     elsif ( $code eq 'WrongTransfer' ) {
378         ;    # FIXME... anything to do here?
379     }
380     elsif ( $code eq 'WrongTransferItem' ) {
381         ;    # FIXME... anything to do here?
382     }
383     elsif ( $code eq 'NeedsTransfer' ) {
384     }
385     elsif ( $code eq 'Wrongbranch' ) {
386     }
387                 
388     else {
389         die "Unknown error code $code";    # note we need all the (empty) elsif's above, or we die.
390         # This forces the issue of staying in sync w/ Circulation.pm
391     }
392     if (%err) {
393         push( @errmsgloop, \%err );
394     }
395     last if $exit_required_p;
396 }
397 $template->param( errmsgloop => \@errmsgloop );
398
399 # patrontable ....
400 if ($borrower) {
401     my $flags = $borrower->{'flags'};
402     my @flagloop;
403     my $flagset;
404     foreach my $flag ( sort keys %$flags ) {
405         my %flaginfo;
406         unless ($flagset) { $flagset = 1; }
407         $flaginfo{redfont} = ( $flags->{$flag}->{'noissues'} );
408         $flaginfo{flag}    = $flag;
409         if ( $flag eq 'CHARGES' ) {
410             $flaginfo{msg}            = $flag;
411             $flaginfo{charges}        = 1;
412             $flaginfo{chargeamount}   = $flags->{$flag}->{amount};
413             $flaginfo{borrowernumber} = $borrower->{borrowernumber};
414         }
415         elsif ( $flag eq 'WAITING' ) {
416             $flaginfo{msg}     = $flag;
417             $flaginfo{waiting} = 1;
418             my @waitingitemloop;
419             my $items = $flags->{$flag}->{'itemlist'};
420             foreach my $item (@$items) {
421                 my $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'});
422                 push @waitingitemloop, {
423                     biblionum => $biblio->{'biblionumber'},
424                     barcode   => $biblio->{'barcode'},
425                     title     => $biblio->{'title'},
426                     brname    => $branches->{ $biblio->{'holdingbranch'} }->{'branchname'},
427                 };
428             }
429             $flaginfo{itemloop} = \@waitingitemloop;
430         }
431         elsif ( $flag eq 'ODUES' ) {
432             my $items = $flags->{$flag}->{'itemlist'};
433             my @itemloop;
434             foreach my $item ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
435                 @$items )
436             {
437                 my $biblio = GetBiblioFromItemNumber( $item->{'itemnumber'});
438                 push @itemloop, {
439                     duedate   => format_date($item->{'date_due'}),
440                     biblionum => $biblio->{'biblionumber'},
441                     barcode   => $biblio->{'barcode'},
442                     title     => $biblio->{'title'},
443                     brname    => $branches->{ $biblio->{'holdingbranch'} }->{'branchname'},
444                 };
445             }
446             $flaginfo{itemloop} = \@itemloop;
447             $flaginfo{overdue}  = 1;
448         }
449         else {
450             $flaginfo{other} = 1;
451             $flaginfo{msg}   = $flags->{$flag}->{'message'};
452         }
453         push( @flagloop, \%flaginfo );
454     }
455     $template->param(
456         flagset          => $flagset,
457         flagloop         => \@flagloop,
458         riborrowernumber => $borrower->{'borrowernumber'},
459         riborcnum        => $borrower->{'cardnumber'},
460         riborsurname     => $borrower->{'surname'},
461         ribortitle       => $borrower->{'title'},
462         riborfirstname   => $borrower->{'firstname'}
463     );
464 }
465
466 #set up so only the last 8 returned items display (make for faster loading pages)
467 my $returned_counter = ( C4::Context->preference('numReturnedItemsToShow') ) ? C4::Context->preference('numReturnedItemsToShow') : 8;
468 my $count = 0;
469 my @riloop;
470 foreach ( sort { $a <=> $b } keys %returneditems ) {
471     my %ri;
472     if ( $count++ < $returned_counter ) {
473         my $barcode = $returneditems{$_};
474         my $duedate = $riduedate{$_};
475         my $overduetext;
476         my $borrowerinfo;
477         if ($duedate) {
478             my @tempdate = split( /-/, $duedate );
479             $ri{year}  = $tempdate[0];
480             $ri{month} = $tempdate[1];
481             $ri{day}   = $tempdate[2];
482             $ri{duedate} = format_date($duedate);
483             my ($borrower) = GetMemberDetails( $riborrowernumber{$_}, 0 );
484             $ri{return_overdue} = 1 if ($duedate lt $today->output('iso'));
485             $ri{borrowernumber} = $borrower->{'borrowernumber'};
486             $ri{borcnum}        = $borrower->{'cardnumber'};
487             $ri{borfirstname}   = $borrower->{'firstname'};
488             $ri{borsurname}     = $borrower->{'surname'};
489             $ri{bortitle}       = $borrower->{'title'};
490             $ri{bornote}        = $borrower->{'borrowernotes'};
491             $ri{borcategorycode}= $borrower->{'categorycode'};
492         }
493         else {
494             $ri{borrowernumber} = $riborrowernumber{$_};
495         }
496
497         #        my %ri;
498         my $biblio = GetBiblioFromItemNumber(GetItemnumberFromBarcode($barcode));
499         # fix up item type for display
500         $biblio->{'itemtype'} = C4::Context->preference('item-level_itypes') ? $biblio->{'itype'} : $biblio->{'itemtype'};
501         $ri{itembiblionumber} = $biblio->{'biblionumber'};
502         $ri{itemtitle}        = $biblio->{'title'};
503         $ri{itemauthor}       = $biblio->{'author'};
504         $ri{itemtype}         = $biblio->{'itemtype'};
505         $ri{itemnote}         = $biblio->{'itemnotes'};
506         $ri{ccode}            = $biblio->{'ccode'};
507         $ri{itemnumber}       = $biblio->{'itemnumber'};
508         $ri{barcode}          = $barcode;
509     }
510     else {
511         last;
512     }
513     push( @riloop, \%ri );
514 }
515
516 $template->param(
517     riloop         => \@riloop,
518     genbrname      => $branches->{$userenv_branch}->{'branchname'},
519     genprname      => $printers->{$printer}->{'printername'},
520     branchname     => $branches->{$userenv_branch}->{'branchname'},
521     printer        => $printer,
522     errmsgloop     => \@errmsgloop,
523     exemptfine     => $exemptfine,
524     dropboxmode    => $dropboxmode,
525     dropboxdate    => $dropboxdate->output(),
526     overduecharges => $overduecharges,
527 );
528
529 # actually print the page!
530 output_html_with_http_headers $query, $cookie, $template->output;