@renew_failed can cause enormous performance-killing array.
[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 $organisation   = $query->param('organisations');
120 my $print          = $query->param('print');
121 my $newexpiry      = $query->param('dateexpiry');
122 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
123
124 # Check if stickyduedate is turned off
125 if ( $barcode ) {
126     # was stickyduedate loaded from session?
127     if ( $stickyduedate && ! $query->param("stickyduedate") ) {
128         $session->clear( 'stickyduedate' );
129         $stickyduedate  = $query->param('stickyduedate');
130         $duedatespec    = $query->param('duedatespec');
131     }
132 }
133
134 #set up cookie.....
135 # my $branchcookie;
136 # my $printercookie;
137 # if ($query->param('setcookies')) {
138 #     $branchcookie = $query->cookie(-name=>'branch', -value=>"$branch", -expires=>'+1y');
139 #     $printercookie = $query->cookie(-name=>'printer', -value=>"$printer", -expires=>'+1y');
140 # }
141 #
142
143 my ($datedue,$invalidduedate,$globalduedate);
144
145 if(C4::Context->preference('globalDueDate') && (C4::Context->preference('globalDueDate') =~ C4::Dates->regexp('syspref'))){
146         $globalduedate = C4::Dates->new(C4::Context->preference('globalDueDate'));
147 }
148 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
149 if($duedatespec_allow){
150     if ($duedatespec) {
151         if ($duedatespec =~ C4::Dates->regexp('syspref')) {
152                 my $tempdate = C4::Dates->new($duedatespec);
153                 if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
154                         # i.e., it has to be later than today/now
155                         $datedue = $tempdate;
156                 } else {
157                         $invalidduedate = 1;
158                         $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
159                 }
160         } else {
161                 $invalidduedate = 1;
162                 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
163         }
164     } else {
165         # pass global due date to tmpl if specifyduedate is true 
166         # and we have no barcode (loading circ page but not checking out)
167         if($globalduedate &&  ! $barcode ){
168             $duedatespec = $globalduedate->output();
169             $stickyduedate = 1;
170         }
171     }
172 } else {
173     $datedue = $globalduedate if($globalduedate);
174 }
175
176 my $todaysdate = C4::Dates->new->output('iso');
177
178 # check and see if we should print
179 if ( $barcode eq '' && $print eq 'maybe' ) {
180     $print = 'yes';
181 }
182
183 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
184 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
185     $template->param(
186         PAYCHARGES     => 'yes',
187         borrowernumber => $borrowernumber
188     );
189 }
190
191 if ( $print eq 'yes' && $borrowernumber ne '' ) {
192     printslip( $borrowernumber );
193     $query->param( 'borrowernumber', '' );
194     $borrowernumber = '';
195 }
196
197 #
198 # STEP 2 : FIND BORROWER
199 # if there is a list of find borrowers....
200 #
201 my $borrowerslist;
202 my $message;
203 if ($findborrower) {
204     my ($count, $borrowers) = SearchMember($findborrower, 'cardnumber', 'web');
205     my @borrowers = @$borrowers;
206     if (C4::Context->preference("AddPatronLists")) {
207         $template->param(
208             "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
209         );
210         if (C4::Context->preference("AddPatronLists")=~/code/){
211             my $categories = GetBorrowercategoryList;
212             $categories->[0]->{'first'} = 1;
213             $template->param(categories=>$categories);
214         }
215     }
216     if ( $#borrowers == -1 ) {
217         $query->param( 'findborrower', '' );
218         $message = "'$findborrower'";
219     }
220     elsif ( $#borrowers == 0 ) {
221         $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
222         $query->param( 'barcode',           '' );
223         $borrowernumber = $borrowers[0]->{'borrowernumber'};
224     }
225     else {
226         $borrowerslist = \@borrowers;
227     }
228 }
229
230 # get the borrower information.....
231 my $borrower;
232 my @lines;
233 if ($borrowernumber) {
234     $borrower = GetMemberDetails( $borrowernumber, 0 );
235     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
236
237     # Warningdate is the date that the warning starts appearing
238     my (  $today_year,   $today_month,   $today_day) = Today();
239     my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
240     my (  $enrol_year,   $enrol_month,   $enrol_day) = split /-/, $borrower->{'dateenrolled'};
241     # Renew day is calculated by adding the enrolment period to today
242     my (  $renew_year,   $renew_month,   $renew_day) =
243       Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
244         0 , $borrower->{'enrolmentperiod'}) if ($enrol_year*$enrol_month*$enrol_day>0);
245     # if the expiry date is before today ie they have expired
246     if ( $warning_year*$warning_month*$warning_day==0 
247         || Date_to_Days($today_year,     $today_month, $today_day  ) 
248          > Date_to_Days($warning_year, $warning_month, $warning_day) )
249     {
250         #borrowercard expired, no issues
251         $template->param(
252             flagged  => "1",
253             noissues => "1",
254             expired     => format_date($borrower->{dateexpiry}),
255             renewaldate => format_date("$renew_year-$renew_month-$renew_day")
256         );
257     }
258     # check for NotifyBorrowerDeparture
259     elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
260             Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
261             Date_to_Days( $today_year, $today_month, $today_day ) ) 
262     {
263         # borrower card soon to expire warn librarian
264         $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
265         flagged       => "1",);
266         if (C4::Context->preference('ReturnBeforeExpiry')){
267             $template->param("returnbeforeexpiry" => 1);
268         }
269   }
270     $template->param(
271         overduecount => $od,
272         issuecount   => $issue,
273         finetotal    => $fines
274     );
275 }
276
277 #
278 # STEP 3 : ISSUING
279 #
280 #
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             }
297             $noerror = 0;
298         }
299     
300   if ($issueconfirmed && $noerror) {
301     # we have no blockers for issuing and any issues needing confirmation have been resolved
302         AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
303         $inprocess = 1;
304     }
305   elsif ($issueconfirmed){      # FIXME: Do something? Or is this to *intentionally* do nothing?
306     if (C4::Context->preference("AllowNotForLoanOverride")){
307         AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
308         $template->param(IMPOSSIBLE  => 0);
309         $inprocess = 1;
310     }
311   }
312   else {
313         my $noquestion = 1;
314 #         Get the item title for more information
315         my $getmessageiteminfo  = GetBiblioFromItemNumber(undef,$barcode);
316                 if ($noerror) {
317                         # only pass needsconfirmation to template if issuing is possible 
318                 foreach my $needsconfirmation ( keys %$question ) {
319                     $template->param(
320                         $needsconfirmation => $$question{$needsconfirmation},
321                         getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
322                         NEEDSCONFIRMATION  => 1
323                     );
324                     $noquestion = 0;
325                 }
326                         # Because of the weird conditional structure (empty elsif block),
327                         # if we reached here, $issueconfirmed must be false.
328                         # Also, since we moved inside the if ($noerror) conditional,
329                         # this old chunky conditional can be simplified:
330                     # if ( $noerror && ( $noquestion || $issueconfirmed ) ) {
331                         if ($noquestion) {
332                                 AddIssue( $borrower, $barcode, $datedue );
333                                 $inprocess = 1;
334                         }
335             }
336                 $template->param(
337                          itemhomebranch => $getmessageiteminfo->{'homebranch'} ,                     
338                          duedatespec => $duedatespec,
339         );
340     }
341     
342     # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue 
343     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
344     $template->param( issuecount   => $issue );
345 }
346
347 # reload the borrower info for the sake of reseting the flags.....
348 if ($borrowernumber) {
349     $borrower = GetMemberDetails( $borrowernumber, 0 );
350 }
351
352 ##################################################################################
353 # BUILD HTML
354 # show all reserves of this borrower, and the position of the reservation ....
355 my $borrowercategory;
356 my $category_type;
357 if ($borrowernumber) {
358
359     # new op dev
360     # now we show the status of the borrower's reservations
361     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
362     my @reservloop;
363     my @WaitingReserveLoop;
364     
365     foreach my $num_res (@borrowerreserv) {
366         my %getreserv;
367         my %getWaitingReserveInfo;
368         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
369         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
370         my ( $transfertwhen, $transfertfrom, $transfertto ) =
371           GetTransfers( $num_res->{'itemnumber'} );
372
373         $getreserv{waiting}       = 0;
374         $getreserv{transfered}    = 0;
375         $getreserv{nottransfered} = 0;
376
377         $getreserv{reservedate}    = format_date( $num_res->{'reservedate'} );
378         $getreserv{title}          = $getiteminfo->{'title'};
379         $getreserv{itemtype}       = $itemtypeinfo->{'description'};
380         $getreserv{author}         = $getiteminfo->{'author'};
381         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
382         $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
383         $getreserv{biblionumber}   = $getiteminfo->{'biblionumber'};
384         $getreserv{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
385         #         check if we have a waiting status for reservations
386         if ( $num_res->{'found'} eq 'W' ) {
387             $getreserv{color}   = 'reserved';
388             $getreserv{waiting} = 1;
389 #     genarate information displaying only waiting reserves
390         $getWaitingReserveInfo{title}        = $getiteminfo->{'title'};
391         $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
392         $getWaitingReserveInfo{itemtype}     = $itemtypeinfo->{'description'};
393         $getWaitingReserveInfo{author}       = $getiteminfo->{'author'};
394         $getWaitingReserveInfo{reservedate}  = format_date( $num_res->{'reservedate'} );
395         $getWaitingReserveInfo{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
396       if($num_res->{'branchcode'} eq $branch){ $getWaitingReserveInfo{waitinghere} = 1; }
397         }
398         #         check transfers with the itemnumber foud in th reservation loop
399         if ($transfertwhen) {
400             $getreserv{color}      = 'transfered';
401             $getreserv{transfered} = 1;
402             $getreserv{datesent}   = format_date($transfertwhen);
403             $getreserv{frombranch} = GetBranchName($transfertfrom);
404         }
405
406         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
407             and not $transfertwhen )
408         {
409             $getreserv{nottransfered}   = 1;
410             $getreserv{nottransferedby} =
411             GetBranchName( $getiteminfo->{'holdingbranch'} );
412         }
413
414 #         if we don't have a reserv on item, we put the biblio infos and the waiting position
415         if ( $getiteminfo->{'title'} eq '' ) {
416             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
417
418             $getreserv{color}           = 'inwait';
419             $getreserv{title}           = $getbibinfo->{'title'};
420             $getreserv{nottransfered}   = 0;
421             $getreserv{itemtype}        = $itemtypeinfo->{'description'};
422             $getreserv{author}          = $getbibinfo->{'author'};
423             $getreserv{biblionumber}    = $num_res->{'biblionumber'};
424         }
425         $getreserv{waitingposition} = $num_res->{'priority'};
426         push( @reservloop, \%getreserv );
427
428 #         if we have a reserve waiting, initiate waitingreserveloop
429         if ($getreserv{waiting} eq 1) {
430         push (@WaitingReserveLoop, \%getWaitingReserveInfo)
431         }
432       
433     }
434
435     # return result to the template
436     $template->param( 
437         countreserv => scalar @reservloop,
438         reservloop  => \@reservloop ,
439         WaitingReserveLoop  => \@WaitingReserveLoop,
440     );
441     $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
442 }
443
444 # make the issued books table.
445 my $todaysissues = '';
446 my $previssues   = '';
447 my @todaysissues;
448 my @previousissues;
449 my $allowborrow;
450 ## ADDED BY JF: new itemtype issuingrules counter stuff
451 my $issued_itemtypes_loop;
452 my $issued_itemtypes_count;
453 my $issued_itemtypes_allowed_count;    # hashref with total allowed by itemtype
454 my $issued_itemtypes_remaining;        # hashref with remaining
455 my $issued_itemtypes_flags;            #hashref that stores flags
456 my @issued_itemtypes_count_loop;
457
458 if ($borrower) {
459 # get each issue of the borrower & separate them in todayissues & previous issues
460     my ($issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
461
462     # split in 2 arrays for today & previous
463     foreach my $it ( @$issueslist ) {
464         # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
465         $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
466
467         ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
468             $it->{'itemnumber'}, $borrower->{'borrowernumber'}
469         );
470         $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
471         my ($can_renew, $can_renew_error) = CanBookBeRenewed( 
472             $borrower->{'borrowernumber'},$it->{'itemnumber'}
473         );
474         $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
475         my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
476                 $it->{'can_renew'} = $can_renew;
477                 $it->{'can_confirm'} = !$can_renew && !$restype;
478                 $it->{'renew_error'} = $restype;
479
480         $it->{'dd'} = format_date($it->{'date_due'});
481         $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
482         ($it->{'author'} eq '') and $it->{'author'} = ' ';
483         $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
484         # ADDED BY JF: NEW ITEMTYPE COUNT DISPLAY
485         $issued_itemtypes_count->{ $it->{'itemtype'} }++;
486
487         if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
488             push @todaysissues, $it;
489         } else {
490             push @previousissues, $it;
491         }
492     }
493     if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
494         @todaysissues   = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
495     }
496     else {
497         @todaysissues   = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
498     }
499     if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
500         @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
501     }
502     else {
503         @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
504     }
505 }
506
507 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
508 # FIXME: This should utilize all the issuingrules options rather than just the defaults
509 # and it should be moved to a module
510 my $dbh = C4::Context->dbh;
511
512 # how many of each is allowed?
513 my $issueqty_sth = $dbh->prepare( "
514 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
515 FROM issuingrules
516   LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
517   WHERE categorycode=?
518 " );
519 $issueqty_sth->execute("*");    # This is a literal asterisk, not a wildcard.
520
521 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
522
523     # subtract how many of each this borrower has
524     $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };  
525     $data->{'left'}  =
526       ( $data->{'maxissueqty'} -
527           $issued_itemtypes_count->{ $data->{'description'} } );
528
529     # can't have a negative number of remaining
530     if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
531     $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
532     unless ( ( $data->{'maxissueqty'} < 1 )
533         || ( $data->{'itemtype'} eq "*" )
534         || ( $data->{'itemtype'} eq "CIRC" ) )
535     {
536         push @issued_itemtypes_count_loop, $data;
537     }
538 }
539 $issued_itemtypes_loop = \@issued_itemtypes_count_loop;
540
541 #### / JF
542
543 my @values;
544 my %labels;
545 my $CGIselectborrower;
546 if ($borrowerslist) {
547     foreach (
548         sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
549         } @$borrowerslist
550       )
551     {
552         push @values, $_->{'borrowernumber'};
553         $labels{ $_->{'borrowernumber'} } =
554 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ...  $_->{'address'} ";
555     }
556     $CGIselectborrower = CGI::scrolling_list(
557         -name     => 'borrowernumber',
558         -class    => 'focus',
559         -id       => 'borrowernumber',
560         -values   => \@values,
561         -labels   => \%labels,
562         -onclick  => "window.location = '/cgi-bin/koha/circ/circulation.pl?borrowernumber=' + this.value;",
563         -size     => 7,
564         -tabindex => '',
565         -multiple => 0
566     );
567 }
568
569 #title
570 my $flags = $borrower->{'flags'};
571 my $flag;
572
573 foreach $flag ( sort keys %$flags ) {
574     $template->param( flagged=> 1);
575     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
576     if ( $flags->{$flag}->{'noissues'} ) {
577         $template->param(
578             flagged  => 1,
579             noissues => 'true',
580         );
581         if ( $flag eq 'GNA' ) {
582             $template->param( gna => 'true' );
583         }
584         if ( $flag eq 'LOST' ) {
585             $template->param( lost => 'true' );
586         }
587         if ( $flag eq 'DBARRED' ) {
588             $template->param( dbarred => 'true' );
589         }
590         if ( $flag eq 'CHARGES' ) {
591             $template->param(
592                 charges    => 'true',
593                 chargesmsg => $flags->{'CHARGES'}->{'message'},
594                 chargesamount => $flags->{'CHARGES'}->{'amount'},
595                 charges_is_blocker => 1
596             );
597         }
598         if ( $flag eq 'CREDITS' ) {
599             $template->param(
600                 credits    => 'true',
601                 creditsmsg => $flags->{'CREDITS'}->{'message'}
602             );
603         }
604     }
605     else {
606         if ( $flag eq 'CHARGES' ) {
607             $template->param(
608                 charges    => 'true',
609                 flagged    => 1,
610                 chargesmsg => $flags->{'CHARGES'}->{'message'},
611                 chargesamount => $flags->{'CHARGES'}->{'amount'},
612             );
613         }
614         if ( $flag eq 'CREDITS' ) {
615             $template->param(
616                 credits    => 'true',
617                 creditsmsg => $flags->{'CREDITS'}->{'message'}
618             );
619         }
620         if ( $flag eq 'ODUES' ) {
621             $template->param(
622                 odues    => 'true',
623                 flagged  => 1,
624                 oduesmsg => $flags->{'ODUES'}->{'message'}
625             );
626
627             my $items = $flags->{$flag}->{'itemlist'};
628 # useless ???
629 #             {
630 #                 my @itemswaiting;
631 #                 foreach my $item (@$items) {
632 #                     my ($iteminformation) =
633 #                         getiteminformation( $item->{'itemnumber'}, 0 );
634 #                     push @itemswaiting, $iteminformation;
635 #                 }
636 #             }
637             if ( $query->param('module') ne 'returns' ) {
638                 $template->param( nonreturns => 'true' );
639             }
640         }
641         if ( $flag eq 'NOTES' ) {
642             $template->param(
643                 notes    => 'true',
644                 flagged  => 1,
645                 notesmsg => $flags->{'NOTES'}->{'message'}
646             );
647         }
648     }
649 }
650
651 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
652 my @temp = split( /\$/, $amountold );
653
654 if ( $borrower->{'category_type'} eq 'C') {
655     my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
656     my $cnt = scalar(@$catcodes);
657     $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
658     $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
659 }
660
661 my $CGIorganisations;
662 my $member_of_institution;
663 if ( C4::Context->preference("memberofinstitution") ) {
664     my $organisations = get_institutions();
665     my @orgs;
666     my %org_labels;
667     foreach my $organisation ( keys %$organisations ) {
668         push @orgs, $organisation;
669         $org_labels{$organisation} =
670           $organisations->{$organisation}->{'surname'};
671     }
672     $member_of_institution = 1;
673     $CGIorganisations      = CGI::popup_menu(
674         -id     => 'organisations',
675         -name   => 'organisations',
676         -labels => \%org_labels,
677         -values => \@orgs,
678     );
679 }
680
681 $amountold = $temp[1];
682
683 $template->param(
684     issued_itemtypes_count_loop => $issued_itemtypes_loop,
685     findborrower                => $findborrower,
686     borrower                    => $borrower,
687     borrowernumber              => $borrowernumber,
688     branch                      => $branch,
689     branchname                  => GetBranchName($borrower->{'branchcode'}),
690     printer                     => $printer,
691     printername                 => $printer,
692     firstname                   => $borrower->{'firstname'},
693     surname                     => $borrower->{'surname'},
694     dateexpiry        => format_date($newexpiry),
695     expiry            => format_date($borrower->{'dateexpiry'}),
696     categorycode      => $borrower->{'categorycode'},
697     categoryname      => $borrower->{description},
698     address           => $borrower->{'address'},
699     address2          => $borrower->{'address2'},
700     email             => $borrower->{'email'},
701     emailpro          => $borrower->{'emailpro'},
702     borrowernotes     => $borrower->{'borrowernotes'},
703     city              => $borrower->{'city'},
704     zipcode               => $borrower->{'zipcode'},
705     phone             => $borrower->{'phone'} || $borrower->{'mobile'},
706     cardnumber        => $borrower->{'cardnumber'},
707     amountold         => $amountold,
708     barcode           => $barcode,
709     stickyduedate     => $stickyduedate,
710     duedatespec       => $duedatespec,
711     message           => $message,
712     CGIselectborrower => $CGIselectborrower,
713     todayissues       => \@todaysissues,
714     previssues        => \@previousissues,
715     inprocess         => $inprocess,
716     memberofinstution => $member_of_institution,
717     CGIorganisations  => $CGIorganisations,
718         is_child          => ($borrower->{'category_type'} eq 'C'),
719     circview => 1,
720 );
721
722 # save stickyduedate to session
723 if ($stickyduedate) {
724     $session->param( 'stickyduedate', $duedatespec );
725 }
726
727 #if ($branchcookie) {
728 #$cookie=[$cookie, $branchcookie, $printercookie];
729 #}
730
731 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
732 $template->param( picture => 1 ) if $picture;
733
734
735 $template->param(
736     debt_confirmed            => $debt_confirmed,
737     SpecifyDueDate            => $duedatespec_allow,
738     CircAutocompl             => C4::Context->preference("CircAutocompl"),
739         AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
740     dateformat                => C4::Context->preference("dateformat"),
741     DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar(),
742 );
743 output_html_with_http_headers $query, $cookie, $template->output;