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