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