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