Bug 7272 setting NULL to debarred field, to avoid having 0000-00-00
[koha.git] / circ / circulation.pl
1 #!/usr/bin/perl
2
3 # script to execute issuing of books
4
5 # Copyright 2000-2002 Katipo Communications
6 # copyright 2010 BibLibre
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::Overdues qw/CheckBorrowerDebarred/;
34 use C4::Members;
35 use C4::Biblio;
36 use C4::Reserves;
37 use C4::Context;
38 use CGI::Session;
39 use C4::Members::Attributes qw(GetBorrowerAttributes);
40
41 use Date::Calc qw(
42   Today
43   Add_Delta_YM
44   Add_Delta_Days
45   Date_to_Days
46 );
47 use List::MoreUtils qw/uniq/;
48
49
50 #
51 # PARAMETERS READING
52 #
53 my $query = new CGI;
54
55 my $sessionID = $query->cookie("CGISESSID") ;
56 my $session = get_session($sessionID);
57
58 # branch and printer are now defined by the userenv
59 # but first we have to check if someone has tried to change them
60
61 my $branch = $query->param('branch');
62 if ($branch){
63     # update our session so the userenv is updated
64     $session->param('branch', $branch);
65     $session->param('branchname', GetBranchName($branch));
66 }
67
68 my $printer = $query->param('printer');
69 if ($printer){
70     # update our session so the userenv is updated
71     $session->param('branchprinter', $printer);
72 }
73
74 if (!C4::Context->userenv && !$branch){
75     if ($session->param('branch') eq 'NO_LIBRARY_SET'){
76         # no branch set we can't issue
77         print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
78         exit;
79     }
80 }
81
82 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
83     {
84         template_name   => 'circ/circulation.tmpl',
85         query           => $query,
86         type            => "intranet",
87         authnotrequired => 0,
88         flagsrequired   => { circulate => 'circulate_remaining_permissions' },
89     }
90 );
91
92 my $branches = GetBranches();
93
94 my @failedrenews = $query->param('failedrenew');    # expected to be itemnumbers 
95 my %renew_failed;
96 for (@failedrenews) { $renew_failed{$_} = 1; }
97
98 my $findborrower = $query->param('findborrower');
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 AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
107 if (C4::Context->preference("AutoLocation") != 1) {
108     $template->param(ManualLocation => 1);
109 }
110
111 if (C4::Context->preference("DisplayClearScreenButton")) {
112     $template->param(DisplayClearScreenButton => 1);
113 }
114
115 if (C4::Context->preference("UseTablesortForCirc")) {
116     $template->param(UseTablesortForCirc => 1);
117 }
118
119 my $barcode        = $query->param('barcode') || '';
120 $barcode =~  s/^\s*|\s*$//g; # remove leading/trailing whitespace
121
122 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
123 my $stickyduedate  = $query->param('stickyduedate') || $session->param('stickyduedate');
124 my $duedatespec    = $query->param('duedatespec')   || $session->param('stickyduedate');
125 my $issueconfirmed = $query->param('issueconfirmed');
126 my $cancelreserve  = $query->param('cancelreserve');
127 my $organisation   = $query->param('organisations');
128 my $print          = $query->param('print');
129 my $newexpiry      = $query->param('dateexpiry');
130 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
131
132 # Check if stickyduedate is turned off
133 if ( $barcode ) {
134     # was stickyduedate loaded from session?
135     if ( $stickyduedate && ! $query->param("stickyduedate") ) {
136         $session->clear( 'stickyduedate' );
137         $stickyduedate  = $query->param('stickyduedate');
138         $duedatespec    = $query->param('duedatespec');
139     }
140 }
141
142 my ($datedue,$invalidduedate);
143
144 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
145 if($duedatespec_allow){
146     if ($duedatespec) {
147         if ($duedatespec =~ C4::Dates->regexp('syspref')) {
148             my $tempdate = C4::Dates->new($duedatespec);
149 #           if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
150 #               # i.e., it has to be later than today/now
151                 $datedue = $tempdate;
152 #           } else {
153 #               $invalidduedate = 1;
154 #               $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
155 #           }
156         } else {
157             $invalidduedate = 1;
158             $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
159         }
160     }
161 }
162
163 my $todaysdate = C4::Dates->new->output('iso');
164
165 # check and see if we should print
166 if ( $barcode eq '' && $print eq 'maybe' ) {
167     $print = 'yes';
168 }
169
170 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
171 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
172     $template->param(
173         PAYCHARGES     => 'yes',
174         borrowernumber => $borrowernumber
175     );
176 }
177
178 if ( $print eq 'yes' && $borrowernumber ne '' ) {
179     printslip( $borrowernumber );
180     $query->param( 'borrowernumber', '' );
181     $borrowernumber = '';
182 }
183
184 #
185 # STEP 2 : FIND BORROWER
186 # if there is a list of find borrowers....
187 #
188 my $borrowerslist;
189 my $message;
190 if ($findborrower) {
191     my $borrowers = Search($findborrower, 'cardnumber');
192     my @borrowers = @$borrowers;
193     if (C4::Context->preference("AddPatronLists")) {
194         $template->param(
195             "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
196         );
197         if (C4::Context->preference("AddPatronLists")=~/code/){
198             my $categories = GetBorrowercategoryList;
199             $categories->[0]->{'first'} = 1;
200             $template->param(categories=>$categories);
201         }
202     }
203     if ( $#borrowers == -1 ) {
204         $query->param( 'findborrower', '' );
205         $message = "'$findborrower'";
206     }
207     elsif ( $#borrowers == 0 ) {
208         $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
209         $query->param( 'barcode',           '' );
210         $borrowernumber = $borrowers[0]->{'borrowernumber'};
211     }
212     else {
213         $borrowerslist = \@borrowers;
214     }
215 }
216
217 # get the borrower information.....
218 my $borrower;
219 if ($borrowernumber) {
220     $borrower = GetMemberDetails( $borrowernumber, 0 );
221     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
222
223     # Warningdate is the date that the warning starts appearing
224     my (  $today_year,   $today_month,   $today_day) = Today();
225     my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
226     my (  $enrol_year,   $enrol_month,   $enrol_day) = split /-/, $borrower->{'dateenrolled'};
227     # Renew day is calculated by adding the enrolment period to today
228     my (  $renew_year,   $renew_month,   $renew_day);
229     if ($enrol_year*$enrol_month*$enrol_day>0) {
230         (  $renew_year,   $renew_month,   $renew_day) =
231         Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
232             0 , $borrower->{'enrolmentperiod'});
233     }
234     # if the expiry date is before today ie they have expired
235     if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
236         || Date_to_Days($today_year,     $today_month, $today_day  ) 
237          > Date_to_Days($warning_year, $warning_month, $warning_day) )
238     {
239         #borrowercard expired, no issues
240         $template->param(
241             flagged  => "1",
242             noissues => "1",
243             expired => "1",
244             renewaldate => format_date("$renew_year-$renew_month-$renew_day")
245         );
246     }
247     # check for NotifyBorrowerDeparture
248     elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
249             Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
250             Date_to_Days( $today_year, $today_month, $today_day ) ) 
251     {
252         # borrower card soon to expire warn librarian
253         $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
254         flagged       => "1",);
255         if (C4::Context->preference('ReturnBeforeExpiry')){
256             $template->param("returnbeforeexpiry" => 1);
257         }
258     }
259     $template->param(
260         overduecount => $od,
261         issuecount   => $issue,
262         finetotal    => $fines
263     );
264
265     my $debar = CheckBorrowerDebarred($borrowernumber);
266     if ($debar) {
267         $template->param( 'userdebarred'    => 1 );
268         $template->param( 'debarredcomment' => $borrower->{debarredcomment} );
269         if ( $debar ne "9999-12-31" ) {
270             $template->param( 'userdebarreddate' => C4::Dates::format_date($debar) );
271         }
272     }
273
274 }
275
276 #
277 # STEP 3 : ISSUING
278 #
279 #
280 if ($barcode) {
281     # always check for blockers on issuing
282     my ( $error, $question ) =
283     CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
284     my $blocker = $invalidduedate ? 1 : 0;
285
286     delete $question->{'DEBT'} if ($debt_confirmed);
287     foreach my $impossible ( keys %$error ) {
288         $template->param(
289             $impossible => $$error{$impossible},
290             IMPOSSIBLE  => 1
291         );
292         $blocker = 1;
293     }
294     if( !$blocker ){
295         my $confirm_required = 0;
296         unless($issueconfirmed){
297             #  Get the item title for more information
298             my $getmessageiteminfo  = GetBiblioFromItemNumber(undef,$barcode);
299             $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
300
301             # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
302             foreach my $needsconfirmation ( keys %$question ) {
303                 $template->param(
304                     $needsconfirmation => $$question{$needsconfirmation},
305                     getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
306                     getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
307                     NEEDSCONFIRMATION  => 1
308                 );
309                 $confirm_required = 1;
310             }
311         }
312         unless($confirm_required) {
313             AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
314             $inprocess = 1;
315         }
316     }
317     
318     # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue 
319     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
320     $template->param( issuecount   => $issue );
321 }
322
323 # reload the borrower info for the sake of reseting the flags.....
324 if ($borrowernumber) {
325     $borrower = GetMemberDetails( $borrowernumber, 0 );
326 }
327
328 ##################################################################################
329 # BUILD HTML
330 # show all reserves of this borrower, and the position of the reservation ....
331 if ($borrowernumber) {
332
333     # new op dev
334     # now we show the status of the borrower's reservations
335     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
336     my @reservloop;
337     my @WaitingReserveLoop;
338     
339     foreach my $num_res (@borrowerreserv) {
340         my %getreserv;
341         my %getWaitingReserveInfo;
342         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
343         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
344         my ( $transfertwhen, $transfertfrom, $transfertto ) =
345           GetTransfers( $num_res->{'itemnumber'} );
346
347         $getreserv{waiting}       = 0;
348         $getreserv{transfered}    = 0;
349         $getreserv{nottransfered} = 0;
350
351         $getreserv{reservedate}    = format_date( $num_res->{'reservedate'} );
352         $getreserv{reservenumber}  = $num_res->{'reservenumber'};
353         $getreserv{title}          = $getiteminfo->{'title'};
354         $getreserv{itemtype}       = $itemtypeinfo->{'description'};
355         $getreserv{author}         = $getiteminfo->{'author'};
356         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
357         $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
358         $getreserv{biblionumber}   = $getiteminfo->{'biblionumber'};
359         $getreserv{waitingat}      = GetBranchName( $num_res->{'branchcode'} );
360         #         check if we have a waiting status for reservations
361         if ( $num_res->{'found'} eq 'W' ) {
362             $getreserv{color}   = 'reserved';
363             $getreserv{waiting} = 1;
364 #     genarate information displaying only waiting reserves
365         $getWaitingReserveInfo{title}        = $getiteminfo->{'title'};
366         $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
367         $getWaitingReserveInfo{itemtype}     = $itemtypeinfo->{'description'};
368         $getWaitingReserveInfo{author}       = $getiteminfo->{'author'};
369         $getWaitingReserveInfo{reservedate}  = format_date( $num_res->{'reservedate'} );
370         $getWaitingReserveInfo{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
371         $getWaitingReserveInfo{waitinghere}  = 1 if $num_res->{'branchcode'} eq $branch;
372         }
373         #         check transfers with the itemnumber foud in th reservation loop
374         if ($transfertwhen) {
375             $getreserv{color}      = 'transfered';
376             $getreserv{transfered} = 1;
377             $getreserv{datesent}   = format_date($transfertwhen);
378             $getreserv{frombranch} = GetBranchName($transfertfrom);
379         } elsif ($getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'}) {
380             $getreserv{nottransfered}   = 1;
381             $getreserv{nottransferedby} = 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
388             $getreserv{color}           = 'inwait';
389             $getreserv{title}           = $getbibinfo->{'title'};
390             $getreserv{nottransfered}   = 0;
391             $getreserv{itemtype}        = $itemtypeinfo->{'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} == 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 @relissues;
420 my @relprevissues;
421 my $displayrelissues;
422
423 my $totalprice = 0;
424
425 sub build_issue_data {
426     my $issueslist = shift;
427     my $relatives = shift;
428
429     # split in 2 arrays for today & previous
430     foreach my $it ( @$issueslist ) {
431         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $it->{'itype'} : $it->{'itemtype'} );
432
433         # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
434         $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
435
436         ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
437             $it->{'itemnumber'}, $it->{'borrowernumber'}
438         );
439         $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
440         my ($can_renew, $can_renew_error) = CanBookBeRenewed( 
441             $it->{'borrowernumber'},$it->{'itemnumber'}
442         );
443         $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
444         my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
445         $it->{'can_renew'} = $can_renew;
446         $it->{'can_confirm'} = !$can_renew && !$restype;
447         $it->{'renew_error'} = $restype;
448         $it->{'checkoutdate'} = C4::Dates->new($it->{'issuedate'},'iso')->output('syspref');
449         $it->{'issuingbranchname'} = GetBranchName($it->{'branchcode'});
450
451         $totalprice += $it->{'replacementprice'};
452         $it->{'itemtype'} = $itemtypeinfo->{'description'};
453         $it->{'itemtype_image'} = $itemtypeinfo->{'imageurl'};
454         $it->{'dd'} = format_date($it->{'date_due'});
455         $it->{'displaydate'} = format_date($it->{'issuedate'});
456         $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
457         ($it->{'author'} eq '') and $it->{'author'} = ' ';
458         $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
459
460         if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
461             (!$relatives) ? push @todaysissues, $it : push @relissues, $it;
462         } else {
463             (!$relatives) ? push @previousissues, $it : push @relprevissues, $it;
464         }
465     }
466 }
467
468 if ($borrower) {
469
470     # Getting borrower relatives
471     my @relborrowernumbers = GetMemberRelatives($borrower->{'borrowernumber'});
472     #push @borrowernumbers, $borrower->{'borrowernumber'};
473
474     # get each issue of the borrower & separate them in todayissues & previous issues
475     my $issueslist = GetPendingIssues($borrower->{'borrowernumber'});
476     my $relissueslist = [];
477     if ( @relborrowernumbers ) {
478         $relissueslist = GetPendingIssues(@relborrowernumbers);
479     }
480
481     build_issue_data($issueslist, 0);
482     build_issue_data($relissueslist, 1);
483   
484     $displayrelissues = scalar($relissueslist);
485
486     if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
487         @todaysissues   = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
488     }
489     else {
490         @todaysissues   = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
491     }
492
493     if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
494         @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
495     }
496     else {
497         @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
498     }
499 }
500
501
502 my @values;
503 my %labels;
504 my $CGIselectborrower;
505 if ($borrowerslist) {
506     foreach (
507         sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
508         } @$borrowerslist
509       )
510     {
511         push @values, $_->{'borrowernumber'};
512         $labels{ $_->{'borrowernumber'} } =
513 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ...  $_->{'address'} ";
514     }
515     $CGIselectborrower = CGI::scrolling_list(
516         -name     => 'borrowernumber',
517         -class    => 'focus',
518         -id       => 'borrowernumber',
519         -values   => \@values,
520         -labels   => \%labels,
521         -ondblclick => 'document.forms[\'mainform\'].submit()',
522         -size     => 7,
523         -tabindex => '',
524         -multiple => 0
525     );
526 }
527
528 #title
529 my $flags = $borrower->{'flags'};
530 foreach my $flag ( sort keys %$flags ) {
531     $template->param( flagged=> 1);
532     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
533     if ( $flags->{$flag}->{'noissues'} ) {
534         $template->param(
535             flagged  => 1,
536             noissues => 'true',
537         );
538         if ( $flag eq 'GNA' ) {
539             $template->param( gna => 'true' );
540         }
541         elsif ( $flag eq 'LOST' ) {
542             $template->param( lost => 'true' );
543         }
544         elsif ( $flag eq 'DBARRED' ) {
545             $template->param( dbarred => 'true' );
546         }
547         elsif ( $flag eq 'CHARGES' ) {
548             $template->param(
549                 charges    => 'true',
550                 chargesmsg => $flags->{'CHARGES'}->{'message'},
551                 chargesamount => $flags->{'CHARGES'}->{'amount'},
552                 charges_is_blocker => 1
553             );
554         }
555         elsif ( $flag eq 'CREDITS' ) {
556             $template->param(
557                 credits    => 'true',
558                 creditsmsg => $flags->{'CREDITS'}->{'message'},
559                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
560             );
561         }
562     }
563     else {
564         if ( $flag eq 'CHARGES' ) {
565             $template->param(
566                 charges    => 'true',
567                 flagged    => 1,
568                 chargesmsg => $flags->{'CHARGES'}->{'message'},
569                 chargesamount => $flags->{'CHARGES'}->{'amount'},
570             );
571         }
572         elsif ( $flag eq 'CREDITS' ) {
573             $template->param(
574                 credits    => 'true',
575                 creditsmsg => $flags->{'CREDITS'}->{'message'},
576                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
577             );
578         }
579         elsif ( $flag eq 'ODUES' ) {
580             $template->param(
581                 odues    => 'true',
582                 flagged  => 1,
583                 oduesmsg => $flags->{'ODUES'}->{'message'}
584             );
585
586             my $items = $flags->{$flag}->{'itemlist'};
587             if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
588                 $template->param( nonreturns => 'true' );
589             }
590         }
591         elsif ( $flag eq 'NOTES' ) {
592             $template->param(
593                 notes    => 'true',
594                 flagged  => 1,
595                 notesmsg => $flags->{'NOTES'}->{'message'}
596             );
597         }
598     }
599 }
600
601 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
602 $amountold =~ s/^.*\$//;    # remove upto the $, if any
603
604 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
605
606 if ( $borrower->{'category_type'} eq 'C') {
607     my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
608     my $cnt = scalar(@$catcodes);
609     $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
610     $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
611 }
612
613 my $CGIorganisations;
614 my $member_of_institution;
615 if ( C4::Context->preference("memberofinstitution") ) {
616     my $organisations = get_institutions();
617     my @orgs;
618     my %org_labels;
619     foreach my $organisation ( keys %$organisations ) {
620         push @orgs, $organisation;
621         $org_labels{$organisation} = $organisations->{$organisation}->{'surname'};
622     }
623     $member_of_institution = 1;
624     $CGIorganisations      = CGI::popup_menu(
625         -id     => 'organisations',
626         -name   => 'organisations',
627         -labels => \%org_labels,
628         -values => \@orgs,
629     );
630 }
631
632 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
633 if($lib_messages_loop){ $template->param(flagged => 1 ); }
634
635 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
636 if($bor_messages_loop){ $template->param(flagged => 1 ); }
637
638 # Computes full borrower address
639 my (undef, $roadttype_hashref) = &GetRoadTypes();
640 my $address = $borrower->{'streetnumber'}.' '.$roadttype_hashref->{$borrower->{'streettype'}}.' '.$borrower->{'address'};
641
642 my $fast_cataloging = 0;
643 if (defined getframeworkinfo('FA')) {
644     $fast_cataloging = 1 
645 }
646
647 if (C4::Context->preference('ExtendedPatronAttributes')) {
648     my $attributes = GetBorrowerAttributes($borrowernumber);
649     $template->param(
650         ExtendedPatronAttributes => 1,
651         extendedattributes => $attributes
652     );
653 }
654
655 $template->param(
656     lib_messages_loop => $lib_messages_loop,
657     bor_messages_loop => $bor_messages_loop,
658     all_messages_del  => C4::Context->preference('AllowAllMessageDeletion'),
659     findborrower      => $findborrower,
660     borrower          => $borrower,
661     borrowernumber    => $borrowernumber,
662     branch            => $branch,
663     branchname        => GetBranchName($borrower->{'branchcode'}),
664     printer           => $printer,
665     printername       => $printer,
666     firstname         => $borrower->{'firstname'},
667     surname           => $borrower->{'surname'},
668     showname          => $borrower->{'showname'},
669     category_type     => $borrower->{'category_type'},
670     dateexpiry        => format_date($newexpiry),
671     expiry            => format_date($borrower->{'dateexpiry'}),
672     categorycode      => $borrower->{'categorycode'},
673     categoryname      => $borrower->{description},
674     address           => $address,
675     address2          => $borrower->{'address2'},
676     email             => $borrower->{'email'},
677     emailpro          => $borrower->{'emailpro'},
678     borrowernotes     => $borrower->{'borrowernotes'},
679     city              => $borrower->{'city'},
680     state              => $borrower->{'state'},
681     zipcode           => $borrower->{'zipcode'},
682     country           => $borrower->{'country'},
683     phone             => $borrower->{'phone'} || $borrower->{'mobile'},
684     cardnumber        => $borrower->{'cardnumber'},
685     othernames        => $borrower->{'othernames'},
686     amountold         => $amountold,
687     barcode           => $barcode,
688     stickyduedate     => $stickyduedate,
689     duedatespec       => $duedatespec,
690     message           => $message,
691     CGIselectborrower => $CGIselectborrower,
692     totalprice        => sprintf('%.2f', $totalprice),
693     totaldue          => sprintf('%.2f', $total),
694     todayissues       => \@todaysissues,
695     previssues        => \@previousissues,
696     relissues                   => \@relissues,
697     relprevissues               => \@relprevissues,
698     displayrelissues            => $displayrelissues,
699     inprocess         => $inprocess,
700     memberofinstution => $member_of_institution,
701     CGIorganisations  => $CGIorganisations,
702     is_child          => ($borrower->{'category_type'} eq 'C'),
703     circview => 1,
704     soundon           => C4::Context->preference("SoundOn"),
705     fast_cataloging   => $fast_cataloging,
706 );
707
708 # save stickyduedate to session
709 if ($stickyduedate) {
710     $session->param( 'stickyduedate', $duedatespec );
711 }
712
713 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
714 $template->param( picture => 1 ) if $picture;
715
716 # get authorised values with type of BOR_NOTES
717
718 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
719
720 $template->param(
721     debt_confirmed            => $debt_confirmed,
722     SpecifyDueDate            => $duedatespec_allow,
723     CircAutocompl             => C4::Context->preference("CircAutocompl"),
724         AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
725     dateformat                => C4::Context->preference("dateformat"),
726     DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar(),
727     canned_bor_notes_loop     => $canned_notes,
728 );
729 output_html_with_http_headers $query, $cookie, $template->output;