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