[followup](bug #4334) fix duplicate entries in sql
[koha.git] / circ / circulation.pl
1 #!/usr/bin/perl
2
3 # written 8/5/2002 by Finlay
4 # script to execute issuing of books
5
6 # Copyright 2000-2002 Katipo Communications
7 #
8 # This file is part of Koha.
9 #
10 # Koha is free software; you can redistribute it and/or modify it under the
11 # terms of the GNU General Public License as published by the Free Software
12 # Foundation; either version 2 of the License, or (at your option) any later
13 # version.
14 #
15 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
16 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
17 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License along with
20 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
21 # Suite 330, Boston, MA  02111-1307 USA
22
23 use strict;
24 # use warnings;  # FIXME
25 use CGI;
26 use C4::Output;
27 use C4::Print;
28 use C4::Auth qw/:DEFAULT get_session/;
29 use C4::Dates qw/format_date/;
30 use C4::Branch; # GetBranches
31 use C4::Koha;   # GetPrinter
32 use C4::Circulation;
33 use C4::Members;
34 use C4::Biblio;
35 use C4::Reserves;
36 use C4::Context;
37 use CGI::Session;
38
39 use Date::Calc qw(
40   Today
41   Add_Delta_YM
42   Add_Delta_Days
43   Date_to_Days
44 );
45
46
47 #
48 # PARAMETERS READING
49 #
50 my $query = new CGI;
51
52 my $sessionID = $query->cookie("CGISESSID") ;
53 my $session = get_session($sessionID);
54
55 # new op dev the branch and the printer are now defined by the userenv
56 # but first we have to check if someone has tried to change them
57
58 my $branch = $query->param('branch');
59 if ($branch){
60     # update our session so the userenv is updated
61     $session->param('branch',$branch);
62     my $branchname = GetBranchName($branch);
63     $session->param('branchname',$branchname);
64 }
65
66 my $printer = $query->param('printer');
67 if ($printer){
68     # update our session so the userenv is updated
69     $session->param('branchprinter',$printer);
70 }
71
72 if (!C4::Context->userenv && !$branch){
73   if ($session->param('branch') eq 'NO_LIBRARY_SET'){
74     # no branch set we can't issue
75     print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
76     exit;
77   }
78 }
79
80 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
81     {
82         template_name   => 'circ/circulation.tmpl',
83         query           => $query,
84         type            => "intranet",
85         authnotrequired => 0,
86         flagsrequired   => { circulate => 'circulate_remaining_permissions' },
87     }
88 );
89
90 my $branches = GetBranches();
91 my $printers = GetPrinters();
92
93 my @failedrenews = $query->param('failedrenew');
94 my %renew_failed;
95 for (@failedrenews) { $renew_failed{$_} = 1; } 
96
97 my $findborrower = $query->param('findborrower');
98 $findborrower =~ s|,| |g;
99 #$findborrower =~ s|'| |g;
100 my $borrowernumber = $query->param('borrowernumber');
101
102 $branch  = C4::Context->userenv->{'branch'};  
103 $printer = C4::Context->userenv->{'branchprinter'};
104
105
106 # If Autolocated is not activated, we show the Circulation Parameters to chage settings of librarian
107 if (C4::Context->preference("AutoLocation") ne 1) { # FIXME: string comparison to number
108     $template->param(ManualLocation => 1);
109 }
110
111 my $barcode        = $query->param('barcode') || '';
112 $barcode =~  s/^\s*|\s*$//g; # remove leading/trailing whitespace
113
114 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
115 my $stickyduedate  = $query->param('stickyduedate') || $session->param('stickyduedate');
116 my $duedatespec    = $query->param('duedatespec')   || $session->param('stickyduedate');
117 my $issueconfirmed = $query->param('issueconfirmed');
118 my $cancelreserve  = $query->param('cancelreserve');
119 my $print          = $query->param('print');
120 my $newexpiry      = $query->param('dateexpiry');
121 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
122
123 # Check if stickyduedate is turned off
124 if ( $barcode ) {
125     # was stickyduedate loaded from session?
126     if ( $stickyduedate && ! $query->param("stickyduedate") ) {
127         $session->clear( 'stickyduedate' );
128         $stickyduedate  = $query->param('stickyduedate');
129         $duedatespec    = $query->param('duedatespec');
130     }
131 }
132
133 #set up cookie.....
134 # my $branchcookie;
135 # my $printercookie;
136 # if ($query->param('setcookies')) {
137 #     $branchcookie = $query->cookie(-name=>'branch', -value=>"$branch", -expires=>'+1y');
138 #     $printercookie = $query->cookie(-name=>'printer', -value=>"$printer", -expires=>'+1y');
139 # }
140 #
141
142 my ($datedue,$invalidduedate,$globalduedate);
143
144 if(C4::Context->preference('globalDueDate') && (C4::Context->preference('globalDueDate') =~ C4::Dates->regexp('syspref'))){
145         $globalduedate = C4::Dates->new(C4::Context->preference('globalDueDate'));
146 }
147 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
148 if($duedatespec_allow){
149     if ($duedatespec) {
150         if ($duedatespec =~ C4::Dates->regexp('syspref')) {
151                 my $tempdate = C4::Dates->new($duedatespec);
152                 if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
153                         # i.e., it has to be later than today/now
154                         $datedue = $tempdate;
155                 } else {
156                         $invalidduedate = 1;
157                         $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
158                 }
159         } else {
160                 $invalidduedate = 1;
161                 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
162         }
163     } else {
164         # pass global due date to tmpl if specifyduedate is true 
165         # and we have no barcode (loading circ page but not checking out)
166         if($globalduedate &&  ! $barcode ){
167             $duedatespec = $globalduedate->output();
168             $stickyduedate = 1;
169         }
170     }
171 } else {
172     $datedue = $globalduedate if($globalduedate);
173 }
174
175 my $todaysdate = C4::Dates->new->output('iso');
176
177 # check and see if we should print
178 if ( $barcode eq '' && $print eq 'maybe' ) {
179     $print = 'yes';
180 }
181
182 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
183 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
184     $template->param(
185         PAYCHARGES     => 'yes',
186         borrowernumber => $borrowernumber
187     );
188 }
189
190 if ( $print eq 'yes' && $borrowernumber ne '' ) {
191     printslip( $borrowernumber );
192     $query->param( 'borrowernumber', '' );
193     $borrowernumber = '';
194 }
195
196 #
197 # STEP 2 : FIND BORROWER
198 # if there is a list of find borrowers....
199 #
200 my $borrowerslist;
201 my $message;
202 if ($findborrower) {
203     my ($count, $borrowers) = SearchMember($findborrower, 'cardnumber', 'web');
204     my @borrowers = @$borrowers;
205     if (C4::Context->preference("AddPatronLists")) {
206         $template->param(
207             "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
208         );
209         if (C4::Context->preference("AddPatronLists")=~/code/){
210             my $categories = GetBorrowercategoryList;
211             $categories->[0]->{'first'} = 1;
212             $template->param(categories=>$categories);
213         }
214     }
215     if ( $#borrowers == -1 ) {
216         $query->param( 'findborrower', '' );
217         $message = "'$findborrower'";
218     }
219     elsif ( $#borrowers == 0 ) {
220         $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
221         $query->param( 'barcode',           '' );
222         $borrowernumber = $borrowers[0]->{'borrowernumber'};
223     }
224     else {
225         $borrowerslist = \@borrowers;
226     }
227 }
228
229 # get the borrower information.....
230 my $borrower;
231 my @lines;
232 if ($borrowernumber) {
233     $borrower = GetMemberDetails( $borrowernumber, 0 );
234     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
235
236     # Warningdate is the date that the warning starts appearing
237     my (  $today_year,   $today_month,   $today_day) = Today();
238     my ($warning_year, $warning_month, $warning_day) = split (/-/, $borrower->{'dateexpiry'});
239     my (  $enrol_year,   $enrol_month,   $enrol_day) = split (/-/, $borrower->{'dateenrolled'});
240     # Renew day is calculated by adding the enrolment period to today
241     my (  $renew_year,   $renew_month,   $renew_day) =
242       Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
243         0 , $borrower->{'enrolmentperiod'}) if ($enrol_year*$enrol_month*$enrol_day>0);
244     # if the expiry date is before today ie they have expired
245     if ( $warning_year*$warning_month*$warning_day==0 
246         || Date_to_Days($today_year,     $today_month, $today_day  ) 
247          > Date_to_Days($warning_year, $warning_month, $warning_day) )
248     {
249         #borrowercard expired, no issues
250         $template->param(
251             flagged  => "1",
252             noissues => "1",
253             expired     => format_date($borrower->{dateexpiry}),
254             renewaldate => format_date("$renew_year-$renew_month-$renew_day")
255         );
256     }
257     # check for NotifyBorrowerDeparture
258     elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
259             Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
260             Date_to_Days( $today_year, $today_month, $today_day ) ) 
261     {
262         # borrower card soon to expire warn librarian
263         $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
264         flagged       => "1",);
265         if (C4::Context->preference('ReturnBeforeExpiry')){
266             $template->param("returnbeforeexpiry" => 1);
267         }
268   }
269     $template->param(
270         overduecount => $od,
271         issuecount   => $issue,
272         finetotal    => $fines
273     );
274 }
275
276 #
277 # STEP 3 : ISSUING
278 #
279 #
280 my $noerror = 1;
281 if ($barcode) {
282   # always check for blockers on issuing
283   my ( $error, $question ) =
284     CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
285   my $blocker = $invalidduedate ? 1 : 0;
286
287   delete $question->{'DEBT'} if ($debt_confirmed);
288   foreach my $impossible ( keys %$error ) {
289             if ($impossible eq "NOT_FOR_LOAN_CAN_FORCE"){
290                 $$question{$impossible}=$$error{$impossible};
291             } else {
292             $template->param(
293                 $impossible => $$error{$impossible},
294                 IMPOSSIBLE  => 1
295             );
296             $blocker = 1;
297         }
298   }
299     if( !$blocker ){
300         my $confirm_required = 0;
301         unless($issueconfirmed){
302             #  Get the item title for more information
303             my $getmessageiteminfo  = GetBiblioFromItemNumber(undef,$barcode);
304                     $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
305
306                     # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
307             foreach my $needsconfirmation ( keys %$question ) {
308                 $template->param(
309                     $needsconfirmation => $$question{$needsconfirmation},
310                     getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
311                     NEEDSCONFIRMATION  => 1
312                 );
313                 $confirm_required = 1;
314             }
315                 }
316         unless($confirm_required) {
317             AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
318                         $inprocess = 1;
319             if($globalduedate && ! $stickyduedate && $duedatespec_allow ){
320                 $duedatespec = $globalduedate->output();
321                 $stickyduedate = 1;
322             }
323             $noerror = 0;
324         }
325     
326   if ($issueconfirmed && $noerror) {
327     # we have no blockers for issuing and any issues needing confirmation have been resolved
328         AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
329         $inprocess = 1;
330     }
331   elsif ($issueconfirmed){      # FIXME: Do something? Or is this to *intentionally* do nothing?
332     if (C4::Context->preference("AllowNotForLoanOverride")){
333         AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
334         $template->param(IMPOSSIBLE  => 0);
335         $inprocess = 1;
336     }
337   }
338   else {
339         my $noquestion = 1;
340 #         Get the item title for more information
341         my $getmessageiteminfo  = GetBiblioFromItemNumber(undef,$barcode);
342                 if ($noerror) {
343                         # only pass needsconfirmation to template if issuing is possible 
344                 foreach my $needsconfirmation ( keys %$question ) {
345                     $template->param(
346                         $needsconfirmation => $$question{$needsconfirmation},
347                         getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
348                         NEEDSCONFIRMATION  => 1
349                     );
350                     $noquestion = 0;
351                 }
352                         # Because of the weird conditional structure (empty elsif block),
353                         # if we reached here, $issueconfirmed must be false.
354                         # Also, since we moved inside the if ($noerror) conditional,
355                         # this old chunky conditional can be simplified:
356                     # if ( $noerror && ( $noquestion || $issueconfirmed ) ) {
357                         if ($noquestion) {
358                                 AddIssue( $borrower, $barcode, $datedue );
359                                 $inprocess = 1;
360                         }
361             }
362                 $template->param(
363                          itemhomebranch => $getmessageiteminfo->{'homebranch'} ,                     
364                          duedatespec => $duedatespec,
365         );
366     }
367     
368     # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue 
369     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
370     $template->param( issuecount   => $issue );
371 }
372 }    
373
374 # reload the borrower info for the sake of reseting the flags.....
375 if ($borrowernumber) {
376     $borrower = GetMemberDetails( $borrowernumber, 0 );
377 }
378
379 ##################################################################################
380 # BUILD HTML
381 # show all reserves of this borrower, and the position of the reservation ....
382 my $borrowercategory;
383 my $category_type;
384 if ($borrowernumber) {
385
386     # new op dev
387     # now we show the status of the borrower's reservations
388     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
389     my @reservloop;
390     my @WaitingReserveLoop;
391     
392     foreach my $num_res (@borrowerreserv) {
393         my %getreserv;
394         my %getWaitingReserveInfo;
395         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
396         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
397         my ( $transfertwhen, $transfertfrom, $transfertto ) =
398           GetTransfers( $num_res->{'itemnumber'} );
399
400         $getreserv{waiting}       = 0;
401         $getreserv{transfered}    = 0;
402         $getreserv{nottransfered} = 0;
403
404         $getreserv{reservedate}    = format_date( $num_res->{'reservedate'} );
405         $getreserv{title}          = $getiteminfo->{'title'};
406         $getreserv{itemtype}       = $itemtypeinfo->{'description'};
407         $getreserv{author}         = $getiteminfo->{'author'};
408         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
409         $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
410         $getreserv{biblionumber}   = $getiteminfo->{'biblionumber'};
411         $getreserv{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
412         #         check if we have a waiting status for reservations
413         if ( $num_res->{'found'} eq 'W' ) {
414             $getreserv{color}   = 'reserved';
415             $getreserv{waiting} = 1;
416 #     genarate information displaying only waiting reserves
417         $getWaitingReserveInfo{title}        = $getiteminfo->{'title'};
418         $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
419         $getWaitingReserveInfo{itemtype}     = $itemtypeinfo->{'description'};
420         $getWaitingReserveInfo{author}       = $getiteminfo->{'author'};
421         $getWaitingReserveInfo{reservedate}  = format_date( $num_res->{'reservedate'} );
422         $getWaitingReserveInfo{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
423       if($num_res->{'branchcode'} eq $branch){ $getWaitingReserveInfo{waitinghere} = 1; }
424         }
425         #         check transfers with the itemnumber foud in th reservation loop
426         if ($transfertwhen) {
427             $getreserv{color}      = 'transfered';
428             $getreserv{transfered} = 1;
429             $getreserv{datesent}   = format_date($transfertwhen);
430             $getreserv{frombranch} = GetBranchName($transfertfrom);
431         }
432
433         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
434             and not $transfertwhen )
435         {
436             $getreserv{nottransfered}   = 1;
437             $getreserv{nottransferedby} =
438             GetBranchName( $getiteminfo->{'holdingbranch'} );
439         }
440
441 #         if we don't have a reserv on item, we put the biblio infos and the waiting position
442         if ( $getiteminfo->{'title'} eq '' ) {
443             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
444
445             $getreserv{color}           = 'inwait';
446             $getreserv{title}           = $getbibinfo->{'title'};
447             $getreserv{nottransfered}   = 0;
448             $getreserv{itemtype}        = $itemtypeinfo->{'description'};
449             $getreserv{author}          = $getbibinfo->{'author'};
450             $getreserv{biblionumber}    = $num_res->{'biblionumber'};
451         }
452         $getreserv{waitingposition} = $num_res->{'priority'};
453         push( @reservloop, \%getreserv );
454
455 #         if we have a reserve waiting, initiate waitingreserveloop
456         if ($getreserv{waiting} eq 1) {
457         push (@WaitingReserveLoop, \%getWaitingReserveInfo)
458         }
459       
460     }
461
462     # return result to the template
463     $template->param( 
464         countreserv => scalar @reservloop,
465         reservloop  => \@reservloop ,
466         WaitingReserveLoop  => \@WaitingReserveLoop,
467     );
468     $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
469 }
470
471 # make the issued books table.
472 my $todaysissues = '';
473 my $previssues   = '';
474 my @todaysissues;
475 my @previousissues;
476 my $allowborrow;
477 ## ADDED BY JF: new itemtype issuingrules counter stuff
478 my $issued_itemtypes_loop;
479 my $issued_itemtypes_count;
480 my $issued_itemtypes_allowed_count;    # hashref with total allowed by itemtype
481 my $issued_itemtypes_remaining;        # hashref with remaining
482 my $issued_itemtypes_flags;            #hashref that stores flags
483 my @issued_itemtypes_count_loop;
484
485 if ($borrower) {
486 # get each issue of the borrower & separate them in todayissues & previous issues
487     my ($issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
488
489     # split in 2 arrays for today & previous
490     foreach my $it ( @$issueslist ) {
491         # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
492         $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
493
494         ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
495             $it->{'itemnumber'}, $borrower->{'borrowernumber'}
496         );
497         $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
498         my ($can_renew, $can_renew_error) = CanBookBeRenewed( 
499             $borrower->{'borrowernumber'},$it->{'itemnumber'}
500         );
501         $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
502         my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
503                 $it->{'can_renew'} = $can_renew;
504                 $it->{'can_confirm'} = !$can_renew && !$restype;
505                 $it->{'renew_error'} = $restype;
506
507         $it->{'dd'} = format_date($it->{'date_due'});
508         $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
509         ($it->{'author'} eq '') and $it->{'author'} = ' ';
510         $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
511         # ADDED BY JF: NEW ITEMTYPE COUNT DISPLAY
512         $issued_itemtypes_count->{ $it->{'itemtype'} }++;
513
514         if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
515             push @todaysissues, $it;
516         } else {
517             push @previousissues, $it;
518         }
519     }
520     if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
521         @todaysissues   = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
522     }
523     else {
524         @todaysissues   = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
525     }
526     if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
527         @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
528     }
529     else {
530         @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
531     }
532 }
533
534 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
535 # FIXME: This should utilize all the issuingrules options rather than just the defaults
536 # and it should be moved to a module
537 my $dbh = C4::Context->dbh;
538
539 # how many of each is allowed?
540 my $issueqty_sth = $dbh->prepare( "
541 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
542 FROM issuingrules
543   LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
544   WHERE categorycode=?
545 " );
546 $issueqty_sth->execute("*");    # This is a literal asterisk, not a wildcard.
547
548 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
549
550     # subtract how many of each this borrower has
551     $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };  
552     $data->{'left'}  =
553       ( $data->{'maxissueqty'} -
554           $issued_itemtypes_count->{ $data->{'description'} } );
555
556     # can't have a negative number of remaining
557     if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
558     $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
559     unless ( ( $data->{'maxissueqty'} < 1 )
560         || ( $data->{'itemtype'} eq "*" )
561         || ( $data->{'itemtype'} eq "CIRC" ) )
562     {
563         push @issued_itemtypes_count_loop, $data;
564     }
565 }
566 $issued_itemtypes_loop = \@issued_itemtypes_count_loop;
567
568 #### / JF
569
570 my @values;
571 my %labels;
572 my $CGIselectborrower;
573 if ($borrowerslist) {
574     foreach (
575         sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
576         } @$borrowerslist
577       )
578     {
579         push @values, $_->{'borrowernumber'};
580         $labels{ $_->{'borrowernumber'} } =
581 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ...  $_->{'address'} ";
582     }
583     $CGIselectborrower = CGI::scrolling_list(
584         -name     => 'borrowernumber',
585         -class    => 'focus',
586         -id       => 'borrowernumber',
587         -values   => \@values,
588         -labels   => \%labels,
589         -onclick  => "window.location = '/cgi-bin/koha/circ/circulation.pl?borrowernumber=' + this.value;",
590         -size     => 7,
591         -tabindex => '',
592         -multiple => 0
593     );
594 }
595
596 #title
597 my $flags = $borrower->{'flags'};
598 my $flag;
599
600 foreach $flag ( sort keys %$flags ) {
601     $template->param( flagged=> 1);
602     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
603     if ( $flags->{$flag}->{'noissues'} ) {
604         $template->param(
605             flagged  => 1,
606             noissues => 'true',
607         );
608         if ( $flag eq 'GNA' ) {
609             $template->param( gna => 'true' );
610         }
611         if ( $flag eq 'LOST' ) {
612             $template->param( lost => 'true' );
613         }
614         if ( $flag eq 'DBARRED' ) {
615             $template->param( dbarred => 'true' );
616         }
617         if ( $flag eq 'CHARGES' ) {
618             $template->param(
619                 charges    => 'true',
620                 chargesmsg => $flags->{'CHARGES'}->{'message'},
621                 chargesamount => $flags->{'CHARGES'}->{'amount'},
622                 charges_is_blocker => 1
623             );
624         }
625         if ( $flag eq 'CREDITS' ) {
626             $template->param(
627                 credits    => 'true',
628                 creditsmsg => $flags->{'CREDITS'}->{'message'}
629             );
630         }
631     }
632     else {
633         if ( $flag eq 'CHARGES' ) {
634             $template->param(
635                 charges    => 'true',
636                 flagged    => 1,
637                 chargesmsg => $flags->{'CHARGES'}->{'message'},
638                 chargesamount => $flags->{'CHARGES'}->{'amount'},
639             );
640         }
641         if ( $flag eq 'CREDITS' ) {
642             $template->param(
643                 credits    => 'true',
644                 creditsmsg => $flags->{'CREDITS'}->{'message'}
645             );
646         }
647         if ( $flag eq 'ODUES' ) {
648             $template->param(
649                 odues    => 'true',
650                 flagged  => 1,
651                 oduesmsg => $flags->{'ODUES'}->{'message'}
652             );
653
654             my $items = $flags->{$flag}->{'itemlist'};
655 # useless ???
656 #             {
657 #                 my @itemswaiting;
658 #                 foreach my $item (@$items) {
659 #                     my ($iteminformation) =
660 #                         getiteminformation( $item->{'itemnumber'}, 0 );
661 #                     push @itemswaiting, $iteminformation;
662 #                 }
663 #             }
664             if ( $query->param('module') ne 'returns' ) {
665                 $template->param( nonreturns => 'true' );
666             }
667         }
668         if ( $flag eq 'NOTES' ) {
669             $template->param(
670                 notes    => 'true',
671                 flagged  => 1,
672                 notesmsg => $flags->{'NOTES'}->{'message'}
673             );
674         }
675     }
676 }
677
678 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
679 my @temp = split( /\$/, $amountold );
680
681 if ( $borrower->{'category_type'} eq 'C') {
682     my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
683     my $cnt = scalar(@$catcodes);
684     $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
685     $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
686 }
687
688
689 $amountold = $temp[1];
690
691 $template->param(
692     issued_itemtypes_count_loop => $issued_itemtypes_loop,
693     findborrower                => $findborrower,
694     borrower                    => $borrower,
695     borrowernumber              => $borrowernumber,
696     branch                      => $branch,
697     branchname                  => GetBranchName($borrower->{'branchcode'}),
698     printer                     => $printer,
699     printername                 => $printer,
700     firstname                   => $borrower->{'firstname'},
701     surname                     => $borrower->{'surname'},
702     dateexpiry        => format_date($newexpiry),
703     expiry            => format_date($borrower->{'dateexpiry'}),
704     categorycode      => $borrower->{'categorycode'},
705     categoryname      => $borrower->{description},
706     address           => $borrower->{'address'},
707     address2          => $borrower->{'address2'},
708     email             => $borrower->{'email'},
709     emailpro          => $borrower->{'emailpro'},
710     borrowernotes     => $borrower->{'borrowernotes'},
711     city              => $borrower->{'city'},
712     zipcode               => $borrower->{'zipcode'},
713     phone             => $borrower->{'phone'} || $borrower->{'mobile'},
714     cardnumber        => $borrower->{'cardnumber'},
715     amountold         => $amountold,
716     barcode           => $barcode,
717     stickyduedate     => $stickyduedate,
718     duedatespec       => $duedatespec,
719     message           => $message,
720     CGIselectborrower => $CGIselectborrower,
721     todayissues       => \@todaysissues,
722     previssues        => \@previousissues,
723     inprocess         => $inprocess,
724         is_child          => ($borrower->{'category_type'} eq 'C'),
725     circview => 1,
726 );
727
728 # save stickyduedate to session
729 if ($stickyduedate) {
730     $session->param( 'stickyduedate', $duedatespec );
731 }
732
733 #if ($branchcookie) {
734 #$cookie=[$cookie, $branchcookie, $printercookie];
735 #}
736
737 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
738 $template->param( picture => 1 ) if $picture;
739
740
741 $template->param(
742     debt_confirmed            => $debt_confirmed,
743     SpecifyDueDate            => $duedatespec_allow,
744     CircAutocompl             => C4::Context->preference("CircAutocompl"),
745         AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
746     dateformat                => C4::Context->preference("dateformat"),
747     DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar(),
748 );
749 output_html_with_http_headers $query, $cookie, $template->output;