synch'ing 2.0.0 branch (RC4 tag) and head
[koha.git] / circ / circulation.pl
1 #!/usr/bin/perl
2 # Please use 8-character tabs for this file (indents are every 4 characters)
3
4 #written 8/5/2002 by Finlay
5 #script to execute issuing of books
6
7
8 # Copyright 2000-2002 Katipo Communications
9 #
10 # This file is part of Koha.
11 #
12 # Koha is free software; you can redistribute it and/or modify it under the
13 # terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 2 of the License, or (at your option) any later
15 # version.
16 #
17 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
18 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License along with
22 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
23 # Suite 330, Boston, MA  02111-1307 USA
24
25 use strict;
26 use CGI;
27 use C4::Circulation::Circ2;
28 use C4::Search;
29 use C4::Output;
30 use C4::Print;
31 use DBI;
32 use C4::Auth;
33 use C4::Interface::CGI::Output;
34 use C4::Koha;
35 use HTML::Template;
36 use C4::Date;
37
38 my $query=new CGI;
39 #my ($loggedinuser, $sessioncookie, $sessionID) = checkauth
40 #       ($query, 0, { circulate => 1 });
41
42 my ($template, $loggedinuser, $cookie) = get_template_and_user
43     ({
44         template_name   => 'circ/circulation.tmpl',
45         query           => $query,
46         type            => "intranet",
47         authnotrequired => 0,
48         flagsrequired   => { circulate => 1 },
49     });
50
51
52 my %env;
53 my $linecolor1='#ffffcc';
54 my $linecolor2='white';
55
56 my $branches = getbranches();
57 my $printers = getprinters(\%env);
58
59 my $branch = getbranch($query, $branches);
60 my $printer = getprinter($query, $printers);
61
62
63 #set up cookie.....
64 my $branchcookie;
65 my $printercookie;
66 if ($query->param('setcookies')) {
67         $branchcookie = $query->cookie(-name=>'branch', -value=>"$branch", -expires=>'+1y');
68         $printercookie = $query->cookie(-name=>'printer', -value=>"$printer", -expires=>'+1y');
69 }
70
71 $env{'branchcode'}=$branch;
72 $env{'printer'}=$printer;
73 $env{'queue'}=$printer;
74
75 my @datearr = localtime(time());
76 # FIXME - Could just use POSIX::strftime("%Y%m%d", localtime);
77 my $todaysdate = (1900+$datearr[5]).sprintf ("%0.2d", ($datearr[4]+1)).sprintf ("%0.2d", ($datearr[3]));
78 #warn $todaysdate;
79
80
81 my $message;
82 my $borrowerslist;
83 # if there is a list of find borrowers....
84 my $findborrower = $query->param('findborrower');
85 if ($findborrower) {
86         my ($count,$borrowers)=BornameSearch(\%env,$findborrower,'web');
87         my @borrowers=@$borrowers;
88         if ($#borrowers == -1) {
89                 $query->param('findborrower', '');
90                 $message =  "No borrower matched '$findborrower'";
91         } elsif ($#borrowers == 0) {
92                 $query->param('borrnumber', $borrowers[0]->{'borrowernumber'});
93                 $query->param('barcode','');
94         } else {
95                 $borrowerslist = \@borrowers;
96         }
97 }
98
99 my $borrowernumber = $query->param('borrnumber');
100 my $bornum = $query->param('borrnumber');
101 # check and see if we should print
102 my $print=$query->param('print');
103 my $barcode = $query->param('barcode');
104 if ($barcode eq ''  && $print eq 'maybe'){
105         $print = 'yes';
106 }
107 if ($print eq 'yes' && $borrowernumber ne ''){
108         printslip(\%env,$borrowernumber);
109         $query->param('borrnumber','');
110         $borrowernumber='';
111 }
112
113 # get the borrower information.....
114 my $borrower;
115 my $flags;
116 if ($borrowernumber) {
117     ($borrower, $flags) = getpatroninformation(\%env,$borrowernumber,0);
118 }
119
120 # get the responses to any questions.....
121 my %responses;
122 foreach (sort $query->param) {
123         if ($_ =~ /response-(\d*)/) {
124                 $responses{$1} = $query->param($_);
125         }
126 }
127 if (my $qnumber = $query->param('questionnumber')) {
128         $responses{$qnumber} = $query->param('answer');
129 }
130
131 my ($iteminformation, $duedate, $rejected, $question, $questionnumber, $defaultanswer);
132
133 my $year=$query->param('year');
134 my $month=$query->param('month');
135 my $day=$query->param('day');
136
137 # if the barcode is set
138 if ($barcode) {
139         $barcode = cuecatbarcodedecode($barcode);
140         my ($datedue, $invalidduedate) = fixdate($year, $month, $day);
141         unless ($invalidduedate) {
142                 $env{'datedue'}=$datedue;
143                 my @time=localtime(time);
144                 my $date= (1900+$time[5])."-".($time[4]+1)."-".$time[3];
145                 ($iteminformation, $duedate, $rejected, $question, $questionnumber, $defaultanswer, $message)
146                                         = issuebook(\%env, $borrower, $barcode, \%responses, $date);
147         }
148 }
149
150 # reload the borrower info for the sake of reseting the flags.....
151 if ($borrowernumber) {
152         ($borrower, $flags) = getpatroninformation(\%env,$borrowernumber,0);
153 }
154
155 ##################################################################################
156 # HTML code....
157
158 my %responseform;
159 my @responsearray;
160 foreach (keys %responses) {
161 #    $responsesform.="<input type=hidden name=response-$_ value=$responses{$_}>\n";
162     $responseform{'name'}=$_;
163     $responseform{'value'}=$responses{$_};
164     push @responsearray,\%responseform;
165 }
166 my $questionform;
167 my $stickyduedate;
168 if ($question) {
169     $stickyduedate=$query->param('stickyduedate');
170 }
171
172
173 # Barcode entry box, with hidden inputs attached....
174
175 # FIXME - How can we move this HTML into the template?  Can we create
176 # arrays of the months, dates, etc and use <TMPL_LOOP> in the template to 
177 # output the data that's getting built here?
178 my $counter = 1;
179 my $dayoptions = '';
180 my $monthoptions = '';
181 my $yearoptions = '';
182 for (my $i=1; $i<32; $i++) {
183     my $selected='';
184     if (($query->param('stickyduedate')) && ($day==$i)) {
185         $selected='selected';
186     }
187     $dayoptions.="<option value=$i $selected>$i";
188 }
189 foreach (('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) {
190     my $selected='';
191     if (($query->param('stickyduedate')) && ($month==$counter)) {
192         $selected='selected';
193     }
194     $monthoptions.="<option value=$counter $selected>$_";
195     $counter++;
196 }
197 for (my $i=$datearr[5]+1900; $i<$datearr[5]+1905; $i++) {
198     my $selected='';
199     if (($query->param('stickyduedate')) && ($year==$i)) {
200         $selected='selected';
201     }
202     $yearoptions.="<option value=$i $selected>$i";
203 }
204 my $selected='';
205 ($query->param('stickyduedate')) && ($selected='checked');
206
207
208 # make the issued books table.....
209 my $todaysissues='';
210 my $previssues='';
211 my @realtodayissues;
212 my @realprevissues;
213 my $allowborrow;
214 my $hash;
215 if ($borrower) {
216     ($borrower, $flags,$hash) = getpatroninformation(\%env,$borrowernumber,0);
217     $allowborrow= $hash->{'borrow'};
218     my @todaysissues;
219     my @previousissues;
220     my $issueslist = getissues($borrower);
221     foreach my $it (keys %$issueslist) {
222         my $issuedate = $issueslist->{$it}->{'timestamp'};
223         $issuedate = substr($issuedate, 0, 8);
224         if ($todaysdate == $issuedate) {
225             push @todaysissues, $issueslist->{$it};
226         } else {
227             push @previousissues, $issueslist->{$it};
228         }
229     }
230         my $tcolor = '';
231         my $pcolor = '';
232         foreach my $book (sort {$b->{'timestamp'} <=> $a->{'timestamp'}} @todaysissues){
233                 my $dd = $book->{'date_due'};
234                 my $datedue = $book->{'date_due'};
235                 $dd=format_date($dd);
236                 $datedue=~s/-//g;
237 # FIXME - Instead of declaring the font color here, can we set a variable 
238 # that says 'overdue'?  Then the template can check for it: <TMPL_IF
239 # NAME="overdue"><font color="red"></TMPL_IF>
240                 if ($datedue < $todaysdate) {
241                         $dd="<font color=red>$dd</font>\n";
242                 }
243                 ($tcolor eq $linecolor1) ? ($tcolor=$linecolor2) : ($tcolor=$linecolor1);
244                 $book->{'dd'}=$dd;
245                 $book->{'tcolor'}=$tcolor;
246                 if ($book->{'author'} eq ''){
247                     $book->{'author'}=' ';
248                 }    
249                 push @realtodayissues,$book;
250         }
251     
252
253     # FIXME - For small and private libraries, it'd be nice if this
254     # table included a "Return" link next to each book, so that you
255     # don't have to remember the book's bar code and type it in on the
256     # "Returns" page.
257
258     # This is in the template now, so its possible for a small library to make that link in their
259     # template
260
261     foreach my $book (sort {$a->{'date_due'} cmp $b->{'date_due'}} @previousissues){
262         my $dd = $book->{'date_due'};
263         my $datedue = $book->{'date_due'};
264         $dd=format_date($dd);
265         my $pcolor = '';
266         $datedue=~s/-//g;
267         if ($datedue < $todaysdate) {
268 # FIXME - See line 233 above regarding overdues
269             $dd="<font color=red>$dd</font>\n";
270         }
271         ($pcolor eq $linecolor1) ? ($pcolor=$linecolor2) : ($pcolor=$linecolor1); 
272         $book->{'dd'}=$dd; 
273         $book->{'tcolor'}=$pcolor;
274         if ($book->{'author'} eq ''){
275             $book->{'author'}=' ';
276         }    
277         push @realprevissues,$book
278    }
279 }
280
281 my @values;
282 my %labels;
283 my $CGIselectborrower;
284 if ($borrowerslist) {
285         foreach (sort {$a->{'surname'}.$a->{'firstname'} cmp $b->{'surname'}.$b->{'firstname'}} @$borrowerslist){
286                 push @values,$_->{'borrowernumber'};
287                 $labels{$_->{'borrowernumber'}} ="$_->{'surname'}, $_->{'firstname'} ($_->{'cardnumber'})";
288         }
289         $CGIselectborrower=CGI::scrolling_list( -name     => 'borrnumber',
290                                 -values   => \@values,
291                                 -labels   => \%labels,
292                                 -size     => 7,
293                                 -multiple => 0 );
294 }
295 #title
296
297 my ($patrontable, $flaginfotable) = patrontable($borrower);
298 my $amountold=$flags->{'CHARGES'}->{'message'};
299 my @temp=split(/\$/,$amountold);
300 $amountold=$temp[1];
301 $template->param(
302                 findborrower => $findborrower,
303                 borrower => $borrower,
304                 borrowernumber => $borrowernumber,
305                 branch => $branch,
306                 printer => $printer,
307                 branchname => $branches->{$branch}->{'branchname'},
308                 printername => $printers->{$printer}->{'printername'},
309                 allowborrow =>$allowborrow,
310                 #question form
311                 question => $question,
312                 title => $iteminformation->{'title'},
313                 author => $iteminformation->{'author'},
314                 firstname => $borrower->{'firstname'},
315                 surname => $borrower->{'surname'},
316                 categorycode => $borrower->{'categorycode'},
317                 streetaddress => $borrower->{'streetaddress'},
318                 city => $borrower->{'city'},
319                 phone => $borrower->{'phone'},
320                 cardnumber => $borrower->{'cardnumber'},
321                 question => $question,
322                 barcode => $barcode,
323                 questionnumber => $questionnumber,
324                 dayoptions => $dayoptions,
325                 monthoptions => $monthoptions,
326                 yearoptions => $yearoptions,
327                 stickyduedate => $stickyduedate,
328                 rejected => $rejected,
329                 message => $message,
330                 CGIselectborrower => $CGIselectborrower,
331                 amountold => $amountold,
332                 todayissues => \@realtodayissues,
333                 previssues => \@realprevissues,
334                 responseloop => \@responsearray,
335                  month=>$month,
336                  day=>$day,
337                  year=>$year
338                  
339         );
340
341 if ($branchcookie) {
342     $cookie=[$cookie, $branchcookie, $printercookie];
343 }
344
345 output_html_with_http_headers $query, $cookie, $template->output;
346
347 ####################################################################
348 # Extra subroutines,,,
349
350 sub cuecatbarcodedecode {
351     my ($barcode) = @_;
352     chomp($barcode);
353     my @fields = split(/\./,$barcode);
354     my @results = map(decode($_), @fields[1..$#fields]);
355     if ($#results == 2){
356         return $results[2];
357     } else {
358         return $barcode;
359     }
360 }
361
362 sub fixdate {
363     my ($year, $month, $day) = @_;
364     my $invalidduedate;
365     my $date;
366     if (($year eq 0) && ($month eq 0) && ($year eq 0)) {
367         $env{'datedue'}='';
368     } else {
369         
370 # FIXME - Can we set two flags here, one that says 'invalidduedate', so that 
371 # the template can check for it, and then one for a particular message?
372 # Ex: <TMPL_IF NAME="invalidduedate">  <TMPL_IF NAME="daysinFeb">
373 # Invalid Due Date Specified. Book was not issued.  Never that many days
374 # in February! </TMPL_IF> </TMPL_IF>
375
376         if (($year eq 0) || ($month eq 0) || ($year eq 0)) {
377             $invalidduedate="Invalid Due Date Specified. Book was not issued.<p>\n";
378         } else {
379             if (($day>30) && (($month==4) || ($month==6) || ($month==9) || ($month==11))) {
380                 $invalidduedate = "Invalid Due Date Specified. Book was not issued. Only 30 days in $month month.<p>\n";
381             } elsif (($day > 29) && ($month == 2)) {
382                 $invalidduedate="Invalid Due Date Specified. Book was not issued.  Never that many days in February!<p>\n";
383             } elsif (($month == 2) && ($day > 28) && (($year%4) && ((!($year%100) || ($year%400))))) {
384                 $invalidduedate="Invalid Due Date Specified. Book was not issued.  $year is not a leap year.<p>\n";
385             } else {
386                 $date="$year-$month-$day";
387             }
388         }
389     }
390     return ($date, $invalidduedate);
391 }
392
393
394 sub patrontable {
395     my ($borrower) = @_;
396     my $flags = $borrower->{'flags'};
397     my $flaginfotable='';
398     my $flaginfotext;
399     #my $flaginfotext='';
400     my $flag;
401     my $color='';
402     foreach $flag (sort keys %$flags) {
403         warn $flag;
404 #       my @itemswaiting='';
405         ($color eq $linecolor1) ? ($color=$linecolor2) : ($color=$linecolor1);
406         $flags->{$flag}->{'message'}=~s/\n/<br>/g;
407         if ($flags->{$flag}->{'noissues'}) {
408                 $template->param(
409                         noissues => 'true',
410                         color => $color,
411                          );
412                 if ($flag eq 'GNA'){
413                         $template->param(
414                                 gna => 'true'
415                                 );
416                         }
417                 if ($flag eq 'LOST'){
418                         $template->param(
419                                 lost => 'true'
420                         );
421                         }
422                 if ($flag eq 'DBARRED'){
423                         $template->param(
424                                 dbarred => 'true'
425                         );
426                         }
427                 if ($flag eq 'CHARGES') {
428                         $template->param(
429                                 charges => 'true',
430                                 chargesmsg => $flags->{'CHARGES'}->{'message'}
431                                  );
432                 }
433         } else {
434                  if ($flag eq 'CHARGES') {
435                         $template->param(
436                                 charges => 'true',
437                                 chargesmsg => $flags->{'CHARGES'}->{'message'}
438                          );
439                 }
440                 if ($flag eq 'WAITING') {
441                         my $items=$flags->{$flag}->{'itemlist'};
442                         my @itemswaiting;
443                         foreach my $item (@$items) {
444                         my ($iteminformation) = getiteminformation(\%env, $item->{'itemnumber'}, 0);
445                         $iteminformation->{'branchname'} = $branches->{$iteminformation->{'holdingbranch'}}->{'branchname'};
446                         push @itemswaiting, $iteminformation;
447                         }
448                         $template->param(
449                                 waiting => 'true',
450                                 waitingmsg => $flags->{'WAITING'}->{'message'},
451                                 itemswaiting => \@itemswaiting,
452                                  );
453                 }
454                 if ($flag eq 'ODUES') {
455                         $template->param(
456                                 odues => 'true',
457                                 oduesmsg => $flags->{'ODUES'}->{'message'}
458                                  );
459
460                         my $items=$flags->{$flag}->{'itemlist'};
461                         my $currentcolor=$color;
462                         {
463                         my $color=$currentcolor;
464                             my @itemswaiting;
465                         foreach my $item (@$items) {
466                                 ($color eq $linecolor1) ? ($color=$linecolor2) : ($color=$linecolor1);
467                                 my ($iteminformation) = getiteminformation(\%env, $item->{'itemnumber'}, 0);
468                                 push @itemswaiting, $iteminformation;
469                         }
470                         }
471                         if ($query->param('module') ne 'returns'){
472                                 $template->param( nonreturns => 'true' );
473                         }
474                 }
475                 if ($flag eq 'NOTES') {
476                         $template->param(
477                                 notes => 'true',
478                                 notesmsg => $flags->{'NOTES'}->{'message'}
479                                  );
480                 }
481         }
482     }
483     return($patrontable, $flaginfotext);
484 }
485
486
487 # FIXME - This clashes with &C4::Print::printslip
488 sub printslip {
489     my ($env,$borrowernumber)=@_;
490     my ($borrower, $flags) = getpatroninformation($env,$borrowernumber,0);
491     $env->{'todaysissues'}=1;
492     my ($borrowerissues) = currentissues($env, $borrower);
493     $env->{'nottodaysissues'}=1;
494     $env->{'todaysissues'}=0;
495     my ($borroweriss2)=currentissues($env, $borrower);
496     $env->{'nottodaysissues'}=0;
497     my $i=0;
498     my @issues;
499     foreach (sort {$a <=> $b} keys %$borrowerissues) {
500         $issues[$i]=$borrowerissues->{$_};
501         my $dd=$issues[$i]->{'date_due'};
502         #convert to nz style dates
503         #this should be set with some kinda config variable
504         my @tempdate=split(/-/,$dd);
505         $issues[$i]->{'date_due'}="$tempdate[2]/$tempdate[1]/$tempdate[0]";
506         $i++;
507     }
508     foreach (sort {$a <=> $b} keys %$borroweriss2) {
509         $issues[$i]=$borroweriss2->{$_};
510         my $dd=$issues[$i]->{'date_due'};
511         #convert to nz style dates
512         #this should be set with some kinda config variable
513         my @tempdate=split(/-/,$dd);
514         $issues[$i]->{'date_due'}="$tempdate[2]/$tempdate[1]/$tempdate[0]";
515         $i++;
516     }
517     remoteprint($env,\@issues,$borrower);
518 }
519
520 # Local Variables:
521 # tab-width: 8
522 # End: