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