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