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