bug: sticky due date isn't stick if there is a question about an issue
[koha.git] / circ / circulation.pl
1 #!/usr/bin/perl
2
3 # Please use 8-character tabs for this file (indents are every 4 characters)
4
5 # written 8/5/2002 by Finlay
6 # script to execute issuing of books
7
8 # Copyright 2000-2002 Katipo Communications
9 #
10 # This file is part of Koha.
11 #
12 # Koha is free software; you can redistribute it and/or modify it under the
13 # terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 2 of the License, or (at your option) any later
15 # version.
16 #
17 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
18 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License along with
22 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
23 # Suite 330, Boston, MA  02111-1307 USA
24
25 use strict;
26 use CGI;
27 use C4::Output;
28 use C4::Print;
29 use C4::Auth qw/:DEFAULT get_session/;
30 use C4::Dates qw/format_date/;
31 use C4::Branch; # GetBranches
32 use C4::Koha;   # GetPrinter
33 use C4::Circulation;
34 use C4::Members;
35 use C4::Biblio;
36 use C4::Reserves;
37 use C4::Context;
38 use CGI::Session;
39
40 use Date::Calc qw(
41   Today
42   Add_Delta_YM
43   Add_Delta_Days
44   Date_to_Days
45 );
46
47
48 #
49 # PARAMETERS READING
50 #
51 my $query = new CGI;
52
53 # new op dev the branch and the printer are now defined by the userenv
54 # but first we have to check if someone has tried to change them
55
56 my $branch = $query->param('branch');
57 if ($branch){
58     # update our session so the userenv is updated
59     my $dbh=C4::Context->dbh;
60     my $sessionID = $query->cookie("CGISESSID") ;
61     my $session = get_session($sessionID);
62     $session->param('branch',$branch);
63     my $branchname = GetBranchName($branch);
64     $session->param('branchname',$branchname);
65 }
66
67 my $printer = $query->param('printer');
68 if ($printer){
69     # update our session so the userenv is updated
70   my $dbh=C4::Context->dbh;
71   my $sessionID = $query->cookie("CGISESSID") ;
72   my $session = get_session($sessionID);
73   $session->param('branchprinter',$printer);
74
75 }
76 if (!C4::Context->userenv && !$branch){
77   my $sessionID = $query->cookie("CGISESSID") ;
78   my $session = get_session($sessionID);
79   if ($session->param('branch') eq 'NO_LIBRARY_SET'){
80     # no branch set we can't issue
81     print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
82     exit;
83   }
84 }
85
86 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
87     {
88         template_name   => 'circ/circulation.tmpl',
89         query           => $query,
90         type            => "intranet",
91         authnotrequired => 0,
92         flagsrequired   => { circulate => 1 },
93     }
94 );
95
96 my $branches = GetBranches();
97
98 my $printers = GetPrinters();
99
100 my @failedrenews = $query->param('failedrenew');
101 my @renew_failed;
102 for (@failedrenews) { $renew_failed[$_] = 1; } 
103
104 my $findborrower = $query->param('findborrower');
105 $findborrower =~ s|,| |g;
106 #$findborrower =~ s|'| |g;
107 my $borrowernumber = $query->param('borrowernumber');
108
109 $branch  = C4::Context->userenv->{'branch'};  
110 $printer = C4::Context->userenv->{'branchprinter'};
111
112
113 # If Autolocated is not activated, we show the Circulation Parameters to chage settings of librarian
114     if (C4::Context->preference("AutoLocation") ne 1)
115         {
116             $template->param(
117             ManualLocation => 1,
118             );
119         }
120
121 my $barcode        = $query->param('barcode') || '';
122
123 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
124 my $stickyduedate  = $query->param('stickyduedate');
125 my $duedatespec    = $query->param('duedatespec');
126 my $issueconfirmed = $query->param('issueconfirmed');
127 my $cancelreserve  = $query->param('cancelreserve');
128 my $organisation   = $query->param('organisations');
129 my $print          = $query->param('print');
130 my $newexpiry      = $query->param('dateexpiry');
131 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
132
133 #set up cookie.....
134 # my $branchcookie;
135 # my $printercookie;
136 # if ($query->param('setcookies')) {
137 #     $branchcookie = $query->cookie(-name=>'branch', -value=>"$branch", -expires=>'+1y');
138 #     $printercookie = $query->cookie(-name=>'printer', -value=>"$printer", -expires=>'+1y');
139 # }
140 #
141
142 my ($datedue,$invalidduedate);
143 if ($duedatespec) {
144         if ($duedatespec =~ C4::Dates->regexp('syspref')) {
145                 my $tempdate = C4::Dates->new($duedatespec);
146                 if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
147                         # i.e., it has to be later than today/now
148                         $datedue = $tempdate;
149                 } else {
150                         $invalidduedate = 1;
151                         $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
152                 }
153         } else {
154                 $invalidduedate = 1;
155                 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
156         }
157 }
158
159 my $todaysdate = C4::Dates->new->output('iso');
160
161 # check and see if we should print
162 if ( $barcode eq '' && $print eq 'maybe' ) {
163     $print = 'yes';
164 }
165
166 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
167
168 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
169     $template->param(
170         PAYCHARGES     => 'yes',
171         borrowernumber => $borrowernumber
172     );
173 }
174
175 if ( $print eq 'yes' && $borrowernumber ne '' ) {
176     printslip( $borrowernumber );
177     $query->param( 'borrowernumber', '' );
178     $borrowernumber = '';
179 }
180
181 #
182 # STEP 2 : FIND BORROWER
183 # if there is a list of find borrowers....
184 #
185 my $borrowerslist;
186 my $message;
187 if ($findborrower) {
188     my ( $count, $borrowers ) =
189       SearchMember($findborrower, 'cardnumber', 'web' );
190     my @borrowers = @$borrowers;
191     if ( $#borrowers == -1 ) {
192         $query->param( 'findborrower', '' );
193         $message = "'$findborrower'";
194     }
195     elsif ( $#borrowers == 0 ) {
196         $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
197         $query->param( 'barcode',           '' );
198         $borrowernumber = $borrowers[0]->{'borrowernumber'};
199     }
200     else {
201         $borrowerslist = \@borrowers;
202     }
203 }
204
205 # get the borrower information.....
206 my $borrower;
207 my @lines;
208 if ($borrowernumber) {
209     $borrower = GetMemberDetails( $borrowernumber, 0 );
210     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
211
212     # Warningdate is the date that the warning starts appearing
213     my ( $today_year,   $today_month,   $today_day )   = Today();
214     my ( $warning_year, $warning_month, $warning_day ) = split /-/,
215       $borrower->{'dateexpiry'};
216     my ( $enrol_year, $enrol_month, $enrol_day ) = split /-/,
217       $borrower->{'dateenrolled'};
218     # Renew day is calculated by adding the enrolment period to today
219     my ( $renew_year, $renew_month, $renew_day ) =
220       Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
221         0 , $borrower->{'enrolmentperiod'}) if ($enrol_year*$enrol_month*$enrol_day>0);
222     # if the expiry date is before today ie they have expired
223     if ( $warning_year*$warning_month*$warning_day==0 
224       || Date_to_Days( $today_year, $today_month, $today_day ) 
225          > Date_to_Days( $warning_year, $warning_month, $warning_day ) )
226     {
227         #borrowercard expired, no issues
228         $template->param(
229       flagged => "1",
230             noissues       => "1",
231             expired => format_date($borrower->{dateexpiry}),
232             renewaldate   => format_date("$renew_year-$renew_month-$renew_day")
233         );
234     }
235     # check for NotifyBorrowerDeparture
236   elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
237     Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
238     Date_to_Days( $today_year, $today_month, $today_day ) ) 
239   {
240     # borrower card soon to expire warn librarian
241     $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
242       flagged       => "1",);
243     if ( C4::Context->preference('ReturnBeforeExpiry')){
244       $template->param("returnbeforeexpiry" => 1);
245     }
246   }
247     $template->param(
248         overduecount => $od,
249         issuecount   => $issue,
250         finetotal    => $fines
251     );
252 }
253
254 #
255 # STEP 3 : ISSUING
256 #
257 #
258 if ($barcode) {
259   # always check for blockers on issuing
260   my ( $error, $question ) =
261     CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
262   my $noerror = $invalidduedate ? 0 : 1;
263
264   delete $question->{'DEBT'} if ($debt_confirmed);
265   foreach my $impossible ( keys %$error ) {
266             $template->param(
267                 $impossible => $$error{$impossible},
268                 IMPOSSIBLE  => 1
269             );
270             $noerror = 0;
271         }
272     
273   if ($issueconfirmed && $noerror) {
274     # we have no blockers for issuing and any issues needing confirmation have been resolved
275         AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
276         $inprocess = 1;
277     }
278   elsif ($issueconfirmed){      # FIXME: Do something? Or is this to *intentionally* do nothing?
279   }
280   else {
281         my $noquestion = 1;
282 #         Get the item title for more information
283         my $getmessageiteminfo  = GetBiblioFromItemNumber(undef,$barcode);
284                 if ($noerror) {
285                         # only pass needsconfirmation to template if issuing is possible 
286                 foreach my $needsconfirmation ( keys %$question ) {
287                     $template->param(
288                         $needsconfirmation => $$question{$needsconfirmation},
289                         getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
290                         NEEDSCONFIRMATION  => 1
291                     );
292                     $noquestion = 0;
293                 }
294                         # Because of the weird conditional structure (empty elsif block),
295                         # if we reached here, $issueconfirmed must be false.
296                         # Also, since we moved inside the if ($noerror) conditional,
297                         # this old chunky conditional can be simplified:
298                     # if ( $noerror && ( $noquestion || $issueconfirmed ) ) {
299                         if ($noquestion) {
300                                 AddIssue( $borrower, $barcode, $datedue );
301                                 $inprocess = 1;
302                         }
303             }
304                 $template->param(
305                          itemhomebranch => $getmessageiteminfo->{'homebranch'} ,                     
306                          duedatespec => $duedatespec,
307         );
308     }
309     
310 # FIXME If the issue is confirmed, we launch another time borrdata2, now display the issue count after issue 
311         my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
312         $template->param(
313         issuecount   => $issue,
314         );
315 }
316
317 # reload the borrower info for the sake of reseting the flags.....
318 if ($borrowernumber) {
319     $borrower = GetMemberDetails( $borrowernumber, 0 );
320 }
321
322 ##################################################################################
323 # BUILD HTML
324 # show all reserves of this borrower, and the position of the reservation ....
325 my $borrowercategory;
326 my $category_type;
327 if ($borrowernumber) {
328
329     # new op dev
330     # now we show the status of the borrower's reservations
331     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
332     my @reservloop;
333     my @WaitingReserveLoop;
334     
335     foreach my $num_res (@borrowerreserv) {
336         my %getreserv;
337         my %getWaitingReserveInfo;
338         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
339         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
340         my ( $transfertwhen, $transfertfrom, $transfertto ) =
341           GetTransfers( $num_res->{'itemnumber'} );
342
343         $getreserv{waiting}       = 0;
344         $getreserv{transfered}    = 0;
345         $getreserv{nottransfered} = 0;
346
347         $getreserv{reservedate}    = format_date( $num_res->{'reservedate'} );
348         $getreserv{title}          = $getiteminfo->{'title'};
349         $getreserv{itemtype}       = $itemtypeinfo->{'description'};
350         $getreserv{author}         = $getiteminfo->{'author'};
351         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
352         $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
353         $getreserv{biblionumber}   = $getiteminfo->{'biblionumber'};
354         $getreserv{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
355         #         check if we have a waiting status for reservations
356         if ( $num_res->{'found'} eq 'W' ) {
357             $getreserv{color}   = 'reserved';
358             $getreserv{waiting} = 1;
359 #     genarate information displaying only waiting reserves
360         $getWaitingReserveInfo{title}        = $getiteminfo->{'title'};
361         $getWaitingReserveInfo{biblionumber}   = $getiteminfo->{'biblionumber'};
362         $getWaitingReserveInfo{itemtype}    = $itemtypeinfo->{'description'};
363         $getWaitingReserveInfo{author}        = $getiteminfo->{'author'};
364         $getWaitingReserveInfo{reservedate}    = format_date( $num_res->{'reservedate'} );
365         $getWaitingReserveInfo{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
366       if($num_res->{'branchcode'} eq $branch){ $getWaitingReserveInfo{waitinghere} = 1; }
367         }
368         #         check transfers with the itemnumber foud in th reservation loop
369         if ($transfertwhen) {
370             $getreserv{color}      = 'transfered';
371             $getreserv{transfered} = 1;
372             $getreserv{datesent}   = format_date($transfertwhen);
373             $getreserv{frombranch} = GetBranchName($transfertfrom);
374         }
375
376         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
377             and not $transfertwhen )
378         {
379             $getreserv{nottransfered}   = 1;
380             $getreserv{nottransferedby} =
381               GetBranchName( $getiteminfo->{'holdingbranch'} );
382         }
383
384 #         if we don't have a reserv on item, we put the biblio infos and the waiting position
385         if ( $getiteminfo->{'title'} eq '' ) {
386             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
387             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );  # fixme - we should have item-level reserves here ?
388             $getreserv{color}           = 'inwait';
389             $getreserv{title}           = $getbibinfo->{'title'};
390             $getreserv{nottransfered}   = 0;
391             $getreserv{itemtype}        = $getbibtype->{'description'};
392             $getreserv{author}          = $getbibinfo->{'author'};
393           $getreserv{biblionumber}    = $num_res->{'biblionumber'};
394         }
395         $getreserv{waitingposition} = $num_res->{'priority'};
396         push( @reservloop, \%getreserv );
397
398 #         if we have a reserve waiting, initiate waitingreserveloop
399         if ($getreserv{waiting} eq 1) {
400         push (@WaitingReserveLoop, \%getWaitingReserveInfo)
401         }
402       
403     }
404
405     # return result to the template
406     $template->param( 
407         countreserv => scalar @reservloop,
408         reservloop  => \@reservloop ,
409         WaitingReserveLoop  => \@WaitingReserveLoop,
410     );
411     $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
412 }
413
414 # make the issued books table.
415 my $todaysissues = '';
416 my $previssues   = '';
417 my @todaysissues;
418 my @previousissues;
419 my $allowborrow;
420 ## ADDED BY JF: new itemtype issuingrules counter stuff
421 my $issued_itemtypes_loop;
422 my $issued_itemtypes_count;
423 my $issued_itemtypes_allowed_count;    # hashref with total allowed by itemtype
424 my $issued_itemtypes_remaining;        # hashref with remaining
425 my $issued_itemtypes_flags;            #hashref that stores flags
426 my @issued_itemtypes_count_loop;
427
428 if ($borrower) {
429 # get each issue of the borrower & separate them in todayissues & previous issues
430     my ($countissues,$issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
431
432     # split in 2 arrays for today & previous
433     foreach my $it ( @$issueslist ) {
434         # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
435         $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
436
437         ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
438             $it->{'itemnumber'}, $borrower->{'borrowernumber'}
439         );
440         $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
441         my $can_renew_error;
442         ($it->{'can_renew'}, $can_renew_error) = CanBookBeRenewed( 
443             $borrower->{'borrowernumber'},$it->{'itemnumber'}
444         );
445         $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
446         my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
447         ( $restype ) and $it->{'can_renew'} = 0;
448
449         $it->{'dd'} = format_date($it->{'date_due'});
450         $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
451         ($it->{'author'} eq '') and $it->{'author'} = ' ';
452         $it->{'renew_failed'} = $renew_failed[$it->{'itemnumber'}];
453         # ADDED BY JF: NEW ITEMTYPE COUNT DISPLAY
454         $issued_itemtypes_count->{ $it->{'itemtype'} }++;
455
456         if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
457             push @todaysissues, $it;
458         } else {
459             push @previousissues, $it;
460         }
461     }
462     if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
463         @todaysissues   = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
464     }
465     else {
466         @todaysissues   = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
467     }
468     if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
469         @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
470     }
471     else {
472         @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
473     }
474     my $i = 1;
475     foreach my $book ( @todaysissues ) {
476         $book->{'togglecolor'} = ( ++$i % 2 ) ? 0 : 1 ;
477     }
478     $i = 1;
479     foreach my $book ( @previousissues ) {
480         $book->{'togglecolor'} = ( ++$i % 2 ) ? 0 : 1 ;
481     }
482 }
483
484 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
485 # FIXME: This should utilize all the issuingrules options rather than just the defaults
486 # and it should be moved to a module
487 my $dbh = C4::Context->dbh;
488
489 # how many of each is allowed?
490 my $issueqty_sth = $dbh->prepare( "
491 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
492 FROM issuingrules
493   LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
494   WHERE categorycode=?
495 " );
496 #my @issued_itemtypes_count;  # huh?
497 $issueqty_sth->execute("*");    # FIXME: Why have a WHERE clause at all with a hardcoded "*"?
498
499 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
500
501     # subtract how many of each this borrower has
502     $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };  
503     $data->{'left'}  =
504       ( $data->{'maxissueqty'} -
505           $issued_itemtypes_count->{ $data->{'description'} } );
506
507     # can't have a negative number of remaining
508     if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
509     $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
510     unless ( ( $data->{'maxissueqty'} < 1 )
511         || ( $data->{'itemtype'} eq "*" )
512         || ( $data->{'itemtype'} eq "CIRC" ) )
513     {
514         push @issued_itemtypes_count_loop, $data;
515     }
516 }
517 $issued_itemtypes_loop = \@issued_itemtypes_count_loop;
518
519 #### / JF
520
521 my @values;
522 my %labels;
523 my $CGIselectborrower;
524 if ($borrowerslist) {
525     foreach (
526         sort {(lc $a->{'surname'} cmp lc $b->{'surname'} ?lc $a->{'surname'} cmp lc $b->{'surname'}:lc $a->{'firstname'} cmp lc $b->{'firstname'})
527         } @$borrowerslist
528       )
529     {
530         push @values, $_->{'borrowernumber'};
531         $labels{ $_->{'borrowernumber'} } =
532 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ...  $_->{'address'} ";
533     }
534     $CGIselectborrower = CGI::scrolling_list(
535         -name     => 'borrowernumber',
536         -class    => 'focus',
537         -id       => 'borrowernumber',
538         -values   => \@values,
539         -labels   => \%labels,
540         -size     => 7,
541         -tabindex => '',
542         -multiple => 0
543     );
544 }
545
546 #title
547 my $flags = $borrower->{'flags'};
548 my $flag;
549
550 foreach $flag ( sort keys %$flags ) {
551     $template->param( flagged=> 1);
552     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
553     if ( $flags->{$flag}->{'noissues'} ) {
554         $template->param(
555             flagged  => 1,
556             noissues => 'true',
557         );
558         if ( $flag eq 'GNA' ) {
559             $template->param( gna => 'true' );
560         }
561         if ( $flag eq 'LOST' ) {
562             $template->param( lost => 'true' );
563         }
564         if ( $flag eq 'DBARRED' ) {
565             $template->param( dbarred => 'true' );
566         }
567         if ( $flag eq 'CHARGES' ) {
568             $template->param(
569                 charges    => 'true',
570                 chargesmsg => $flags->{'CHARGES'}->{'message'},
571                 charges_is_blocker => 1
572             );
573         }
574         if ( $flag eq 'CREDITS' ) {
575             $template->param(
576                 credits    => 'true',
577                 creditsmsg => $flags->{'CREDITS'}->{'message'}
578             );
579         }
580     }
581     else {
582         if ( $flag eq 'CHARGES' ) {
583             $template->param(
584                 charges    => 'true',
585                 flagged    => 1,
586                 chargesmsg => $flags->{'CHARGES'}->{'message'}
587             );
588         }
589         if ( $flag eq 'CREDITS' ) {
590             $template->param(
591                 credits    => 'true',
592                 creditsmsg => $flags->{'CREDITS'}->{'message'}
593             );
594         }
595         if ( $flag eq 'ODUES' ) {
596             $template->param(
597                 odues    => 'true',
598                 flagged  => 1,
599                 oduesmsg => $flags->{'ODUES'}->{'message'}
600             );
601
602             my $items = $flags->{$flag}->{'itemlist'};
603 # useless ???
604 #             {
605 #                 my @itemswaiting;
606 #                 foreach my $item (@$items) {
607 #                     my ($iteminformation) =
608 #                         getiteminformation( $item->{'itemnumber'}, 0 );
609 #                     push @itemswaiting, $iteminformation;
610 #                 }
611 #             }
612             if ( $query->param('module') ne 'returns' ) {
613                 $template->param( nonreturns => 'true' );
614             }
615         }
616         if ( $flag eq 'NOTES' ) {
617             $template->param(
618                 notes    => 'true',
619                 flagged  => 1,
620                 notesmsg => $flags->{'NOTES'}->{'message'}
621             );
622         }
623     }
624 }
625
626 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
627 my @temp = split( /\$/, $amountold );
628
629     if ( $borrower->{'category_type'} eq 'C') {
630         my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
631         my $cnt = scalar(@$catcodes);
632         $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
633         $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
634     }
635
636 my $CGIorganisations;
637 my $member_of_institution;
638 if ( C4::Context->preference("memberofinstitution") ) {
639     my $organisations = get_institutions();
640     my @orgs;
641     my %org_labels;
642     foreach my $organisation ( keys %$organisations ) {
643         push @orgs, $organisation;
644         $org_labels{$organisation} =
645           $organisations->{$organisation}->{'surname'};
646     }
647     $member_of_institution = 1;
648     $CGIorganisations      = CGI::popup_menu(
649         -id     => 'organisations',
650         -name   => 'organisations',
651         -labels => \%org_labels,
652         -values => \@orgs,
653     );
654 }
655
656 $amountold = $temp[1];
657
658
659 $template->param(
660     issued_itemtypes_count_loop => $issued_itemtypes_loop,
661     findborrower                => $findborrower,
662     borrower                    => $borrower,
663     borrowernumber              => $borrowernumber,
664     branch                      => $branch,
665     branchname                  => GetBranchName($borrower->{'branchcode'}),
666     printer                     => $printer,
667     printername                 => $printer,
668     firstname                   => $borrower->{'firstname'},
669     surname                     => $borrower->{'surname'},
670     dateexpiry        => format_date($newexpiry),
671     expiry            => format_date($borrower->{'dateexpiry'}),
672     categorycode      => $borrower->{'categorycode'},
673     categoryname      => $borrower->{description},
674     address           => $borrower->{'address'},
675     address2          => $borrower->{'address2'},
676     email             => $borrower->{'email'},
677     emailpro          => $borrower->{'emailpro'},
678     borrowernotes     => $borrower->{'borrowernotes'},
679     city              => $borrower->{'city'},
680     zipcode           => $borrower->{'zipcode'},
681     phone             => $borrower->{'phone'} || $borrower->{'mobile'},
682     cardnumber        => $borrower->{'cardnumber'},
683     amountold         => $amountold,
684     barcode           => $barcode,
685     stickyduedate     => $stickyduedate,
686     message           => $message,
687     CGIselectborrower => $CGIselectborrower,
688     todayissues       => \@todaysissues,
689     previssues        => \@previousissues,
690     inprocess         => $inprocess,
691     memberofinstution => $member_of_institution,
692     CGIorganisations  => $CGIorganisations,
693         is_child        => ($borrower->{'category_type'} eq 'C'),
694   circview => 1,
695   
696 );
697
698 # set return date if stickyduedate
699 if ($stickyduedate) {
700     $template->param(
701         duedatespec => $duedatespec,
702     );
703 }
704
705 #if ($branchcookie) {
706 #$cookie=[$cookie, $branchcookie, $printercookie];
707 #}
708
709 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
710 $template->param( picture => 1 ) if $picture;
711
712
713 $template->param(
714     debt_confirmed           => $debt_confirmed,
715     SpecifyDueDate           => C4::Context->preference("SpecifyDueDate"),
716     CircAutocompl            => C4::Context->preference("CircAutocompl"),
717     dateformat               => C4::Context->preference("dateformat"),
718     DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
719 );
720 output_html_with_http_headers $query, $cookie, $template->output;