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