Bug 8043 - today's checkouts are in Previous checkouts in circulation.pl
[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 # Copyright 2011 PTFS-Europe Ltd.
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it under the
12 # terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 2 of the License, or (at your option) any later
14 # version.
15 #
16 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
17 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License along
21 # with Koha; if not, write to the Free Software Foundation, Inc.,
22 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23
24 use strict;
25 use warnings;
26 use CGI;
27 use C4::Output;
28 use C4::Print;
29 use C4::Auth qw/:DEFAULT get_session/;
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 use C4::Members::Attributes qw(GetBorrowerAttributes);
39 use Koha::DateUtils;
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 our %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                 $datedue = dt_from_string($duedatespec);
149                 $datedue->set_hour(23);
150                 $datedue->set_minute(59);
151         } else {
152             $invalidduedate = 1;
153             $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
154         }
155     }
156 }
157
158 our $todaysdate = C4::Dates->new->output('iso');
159
160 # check and see if we should print
161 if ( $barcode eq '' && $print eq 'maybe' ) {
162     $print = 'yes';
163 }
164
165 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
166 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
167     $template->param(
168         PAYCHARGES     => 'yes',
169         borrowernumber => $borrowernumber
170     );
171 }
172
173 if ( $print eq 'yes' && $borrowernumber ne '' ) {
174     if ( C4::Context->boolean_preference('printcirculationslips') ) {
175         my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
176         NetworkPrint($letter->{content});
177     }
178     $query->param( 'borrowernumber', '' );
179     $borrowernumber = '';
180 }
181
182 #
183 # STEP 2 : FIND BORROWER
184 # if there is a list of find borrowers....
185 #
186 my $borrowerslist;
187 my $message;
188 if ($findborrower) {
189     my $borrowers = Search($findborrower, 'cardnumber');
190     my @borrowers = @$borrowers;
191     if (C4::Context->preference("AddPatronLists")) {
192         $template->param(
193             "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
194         );
195         if (C4::Context->preference("AddPatronLists")=~/code/){
196             my $categories = GetBorrowercategoryList;
197             $categories->[0]->{'first'} = 1;
198             $template->param(categories=>$categories);
199         }
200     }
201     if ( $#borrowers == -1 ) {
202         $query->param( 'findborrower', '' );
203         $message = "'$findborrower'";
204     }
205     elsif ( $#borrowers == 0 ) {
206         $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
207         $query->param( 'barcode',           '' );
208         $borrowernumber = $borrowers[0]->{'borrowernumber'};
209     }
210     else {
211         $borrowerslist = \@borrowers;
212     }
213 }
214
215 # get the borrower information.....
216 my $borrower;
217 if ($borrowernumber) {
218     $borrower = GetMemberDetails( $borrowernumber, 0 );
219     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
220
221     # Warningdate is the date that the warning starts appearing
222     my (  $today_year,   $today_month,   $today_day) = Today();
223     my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
224     my (  $enrol_year,   $enrol_month,   $enrol_day) = split /-/, $borrower->{'dateenrolled'};
225     # Renew day is calculated by adding the enrolment period to today
226     my (  $renew_year,   $renew_month,   $renew_day);
227     if ($enrol_year*$enrol_month*$enrol_day>0) {
228         (  $renew_year,   $renew_month,   $renew_day) =
229         Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
230             0 , $borrower->{'enrolmentperiod'});
231     }
232     # if the expiry date is before today ie they have expired
233     if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
234         || Date_to_Days($today_year,     $today_month, $today_day  ) 
235          > Date_to_Days($warning_year, $warning_month, $warning_day) )
236     {
237         #borrowercard expired, no issues
238         $template->param(
239             flagged  => "1",
240             noissues => "1",
241             expired => "1",
242             renewaldate => "$renew_year-$renew_month-$renew_day",
243         );
244     }
245     # check for NotifyBorrowerDeparture
246     elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
247             Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
248             Date_to_Days( $today_year, $today_month, $today_day ) ) 
249     {
250         # borrower card soon to expire warn librarian
251         $template->param("warndeparture" => $borrower->{dateexpiry},
252         flagged       => "1",);
253         if (C4::Context->preference('ReturnBeforeExpiry')){
254             $template->param("returnbeforeexpiry" => 1);
255         }
256     }
257     $template->param(
258         overduecount => $od,
259         issuecount   => $issue,
260         finetotal    => $fines
261     );
262
263     my $debar = $borrower->{debarred};
264     if ($debar) {
265         $template->param( 'userdebarred'    => 1 );
266         $template->param( 'debarredcomment' => $borrower->{debarredcomment} );
267         if ( $debar ne "9999-12-31" ) {
268             $template->param( 'userdebarreddate' => $debar );
269         }
270     }
271
272 }
273
274 #
275 # STEP 3 : ISSUING
276 #
277 #
278 if ($barcode) {
279     # always check for blockers on issuing
280     my ( $error, $question, $alerts ) =
281     CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
282     my $blocker = $invalidduedate ? 1 : 0;
283
284     $template->param( alert => $alerts );
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->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
300             $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
301
302             # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
303             foreach my $needsconfirmation ( keys %$question ) {
304                 $template->param(
305                     $needsconfirmation => $$question{$needsconfirmation},
306                     getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
307                     getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
308                     NEEDSCONFIRMATION  => 1
309                 );
310                 $confirm_required = 1;
311             }
312         }
313         unless($confirm_required) {
314             AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
315             $inprocess = 1;
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 if ($borrowernumber) {
333
334     # new op dev
335     # now we show the status of the borrower's reservations
336     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
337     my @reservloop;
338     my @WaitingReserveLoop;
339     
340     foreach my $num_res (@borrowerreserv) {
341         my %getreserv;
342         my %getWaitingReserveInfo;
343         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
344         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
345         my ( $transfertwhen, $transfertfrom, $transfertto ) =
346           GetTransfers( $num_res->{'itemnumber'} );
347
348         $getreserv{waiting}       = 0;
349         $getreserv{transfered}    = 0;
350         $getreserv{nottransfered} = 0;
351
352         $getreserv{reservedate}    = $num_res->{'reservedate'};
353         $getreserv{reservenumber}  = $num_res->{'reservenumber'};
354         $getreserv{title}          = $getiteminfo->{'title'};
355         $getreserv{itemtype}       = $itemtypeinfo->{'description'};
356         $getreserv{author}         = $getiteminfo->{'author'};
357         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
358         $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
359         $getreserv{biblionumber}   = $getiteminfo->{'biblionumber'};
360         $getreserv{waitingat}      = GetBranchName( $num_res->{'branchcode'} );
361         $getreserv{suspend}        = $num_res->{'suspend'};
362         $getreserv{suspend_until}  = $num_res->{'suspend_until'};
363         #         check if we have a waiting status for reservations
364         if ( $num_res->{'found'} eq 'W' ) {
365             $getreserv{color}   = 'reserved';
366             $getreserv{waiting} = 1;
367 #     genarate information displaying only waiting reserves
368         $getWaitingReserveInfo{title}        = $getiteminfo->{'title'};
369         $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
370         $getWaitingReserveInfo{itemtype}     = $itemtypeinfo->{'description'};
371         $getWaitingReserveInfo{author}       = $getiteminfo->{'author'};
372         $getWaitingReserveInfo{reservedate}  = $num_res->{'reservedate'};
373         $getWaitingReserveInfo{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
374         $getWaitingReserveInfo{waitinghere}  = 1 if $num_res->{'branchcode'} eq $branch;
375         }
376         #         check transfers with the itemnumber foud in th reservation loop
377         if ($transfertwhen) {
378             $getreserv{color}      = 'transfered';
379             $getreserv{transfered} = 1;
380             $getreserv{datesent}   = $transfertwhen;
381             $getreserv{frombranch} = GetBranchName($transfertfrom);
382         } elsif ($getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'}) {
383             $getreserv{nottransfered}   = 1;
384             $getreserv{nottransferedby} = GetBranchName( $getiteminfo->{'holdingbranch'} );
385         }
386
387 #         if we don't have a reserv on item, we put the biblio infos and the waiting position
388         if ( $getiteminfo->{'title'} eq '' ) {
389             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
390
391             $getreserv{color}           = 'inwait';
392             $getreserv{title}           = $getbibinfo->{'title'};
393             $getreserv{nottransfered}   = 0;
394             $getreserv{itemtype}        = $itemtypeinfo->{'description'};
395             $getreserv{author}          = $getbibinfo->{'author'};
396             $getreserv{biblionumber}    = $num_res->{'biblionumber'};
397         }
398         $getreserv{waitingposition} = $num_res->{'priority'};
399         push( @reservloop, \%getreserv );
400
401 #         if we have a reserve waiting, initiate waitingreserveloop
402         if ($getreserv{waiting} == 1) {
403         push (@WaitingReserveLoop, \%getWaitingReserveInfo)
404         }
405       
406     }
407
408     # return result to the template
409     $template->param( 
410         countreserv => scalar @reservloop,
411         reservloop  => \@reservloop ,
412         WaitingReserveLoop  => \@WaitingReserveLoop,
413     );
414     $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
415 }
416
417 # make the issued books table.
418 my $todaysissues = '';
419 my $previssues   = '';
420 our @todaysissues   = ();
421 our @previousissues = ();
422 our @relissues      = ();
423 our @relprevissues  = ();
424 my $displayrelissues;
425
426 our $totalprice = 0;
427
428 sub build_issue_data {
429     my $issueslist = shift;
430     my $relatives = shift;
431
432     # split in 2 arrays for today & previous
433     foreach my $it ( @$issueslist ) {
434         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $it->{'itype'} : $it->{'itemtype'} );
435
436         # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
437         $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
438
439         ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
440             $it->{'itemnumber'}, $it->{'borrowernumber'}
441         );
442         $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
443         my ($can_renew, $can_renew_error) = CanBookBeRenewed( 
444             $it->{'borrowernumber'},$it->{'itemnumber'}
445         );
446         $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
447         my ( $restype, $reserves, undef ) = CheckReserves( $it->{'itemnumber'} );
448         $it->{'can_renew'} = $can_renew;
449         $it->{'can_confirm'} = !$can_renew && !$restype;
450         $it->{'renew_error'} = $restype;
451         $it->{'checkoutdate'} = $it->{'issuedate'};
452         $it->{'duedate'} = $it->{'date_due'};
453         $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
454         $it->{'issuingbranchname'} = GetBranchName($it->{'branchcode'});
455
456         $totalprice += $it->{'replacementprice'};
457         $it->{'itemtype'} = $itemtypeinfo->{'description'};
458         $it->{'itemtype_image'} = $itemtypeinfo->{'imageurl'};
459         ($it->{'author'} eq '') and $it->{'author'} = ' ';
460         $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
461
462         if ( $it->{'issuedate'} gt $todaysdate or $it->{'lastreneweddate'} gt $todaysdate ) {
463             (!$relatives) ? push @todaysissues, $it : push @relissues, $it;
464         } else {
465             (!$relatives) ? push @previousissues, $it : push @relprevissues, $it;
466         }
467     }
468 }
469
470 if ($borrower) {
471
472     # Getting borrower relatives
473     my @relborrowernumbers = GetMemberRelatives($borrower->{'borrowernumber'});
474     #push @borrowernumbers, $borrower->{'borrowernumber'};
475
476     # get each issue of the borrower & separate them in todayissues & previous issues
477     my $issueslist = GetPendingIssues($borrower->{'borrowernumber'});
478     my $relissueslist = [];
479     if ( @relborrowernumbers ) {
480         $relissueslist = GetPendingIssues(@relborrowernumbers);
481     }
482
483     build_issue_data($issueslist, 0);
484     build_issue_data($relissueslist, 1);
485   
486     $displayrelissues = scalar($relissueslist);
487
488     if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
489         @todaysissues   = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
490     }
491     else {
492         @todaysissues   = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
493     }
494
495     if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
496         @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
497     }
498     else {
499         @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
500     }
501 }
502
503
504 my @values;
505 my %labels;
506 my $CGIselectborrower;
507 if ($borrowerslist) {
508     foreach (
509         sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
510         } @$borrowerslist
511       )
512     {
513         push @values, $_->{'borrowernumber'};
514         $labels{ $_->{'borrowernumber'} } =
515 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ...  $_->{'address'} ";
516     }
517     $CGIselectborrower = CGI::scrolling_list(
518         -name     => 'borrowernumber',
519         -class    => 'focus',
520         -id       => 'borrowernumber',
521         -values   => \@values,
522         -labels   => \%labels,
523         -ondblclick => 'document.forms[\'mainform\'].submit()',
524         -size     => 7,
525         -tabindex => '',
526         -multiple => 0
527     );
528 }
529
530 #title
531 my $flags = $borrower->{'flags'};
532 foreach my $flag ( sort keys %$flags ) {
533     $template->param( flagged=> 1);
534     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
535     if ( $flags->{$flag}->{'noissues'} ) {
536         $template->param(
537             flagged  => 1,
538             noissues => 'true',
539         );
540         if ( $flag eq 'GNA' ) {
541             $template->param( gna => 'true' );
542         }
543         elsif ( $flag eq 'LOST' ) {
544             $template->param( lost => 'true' );
545         }
546         elsif ( $flag eq 'DBARRED' ) {
547             $template->param( dbarred => 'true' );
548         }
549         elsif ( $flag eq 'CHARGES' ) {
550             $template->param(
551                 charges    => 'true',
552                 chargesmsg => $flags->{'CHARGES'}->{'message'},
553                 chargesamount => $flags->{'CHARGES'}->{'amount'},
554                 charges_is_blocker => 1
555             );
556         }
557         elsif ( $flag eq 'CREDITS' ) {
558             $template->param(
559                 credits    => 'true',
560                 creditsmsg => $flags->{'CREDITS'}->{'message'},
561                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
562             );
563         }
564     }
565     else {
566         if ( $flag eq 'CHARGES' ) {
567             $template->param(
568                 charges    => 'true',
569                 flagged    => 1,
570                 chargesmsg => $flags->{'CHARGES'}->{'message'},
571                 chargesamount => $flags->{'CHARGES'}->{'amount'},
572             );
573         }
574         elsif ( $flag eq 'CREDITS' ) {
575             $template->param(
576                 credits    => 'true',
577                 creditsmsg => $flags->{'CREDITS'}->{'message'},
578                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
579             );
580         }
581         elsif ( $flag eq 'ODUES' ) {
582             $template->param(
583                 odues    => 'true',
584                 flagged  => 1,
585                 oduesmsg => $flags->{'ODUES'}->{'message'}
586             );
587
588             my $items = $flags->{$flag}->{'itemlist'};
589             if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
590                 $template->param( nonreturns => 'true' );
591             }
592         }
593         elsif ( $flag eq 'NOTES' ) {
594             $template->param(
595                 notes    => 'true',
596                 flagged  => 1,
597                 notesmsg => $flags->{'NOTES'}->{'message'}
598             );
599         }
600     }
601 }
602
603 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
604 $amountold =~ s/^.*\$//;    # remove upto the $, if any
605
606 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
607
608 if ( $borrower->{'category_type'} eq 'C') {
609     my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
610     my $cnt = scalar(@$catcodes);
611     $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
612     $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
613 }
614
615 my $CGIorganisations;
616 my $member_of_institution;
617 if ( C4::Context->preference("memberofinstitution") ) {
618     my $organisations = get_institutions();
619     my @orgs;
620     my %org_labels;
621     foreach my $organisation ( keys %$organisations ) {
622         push @orgs, $organisation;
623         $org_labels{$organisation} = $organisations->{$organisation}->{'surname'};
624     }
625     $member_of_institution = 1;
626     $CGIorganisations      = CGI::popup_menu(
627         -id     => 'organisations',
628         -name   => 'organisations',
629         -labels => \%org_labels,
630         -values => \@orgs,
631     );
632 }
633
634 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
635 if($lib_messages_loop){ $template->param(flagged => 1 ); }
636
637 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
638 if($bor_messages_loop){ $template->param(flagged => 1 ); }
639
640 # Computes full borrower address
641 my (undef, $roadttype_hashref) = &GetRoadTypes();
642 my $address = $borrower->{'streetnumber'}.' '.$roadttype_hashref->{$borrower->{'streettype'}}.' '.$borrower->{'address'};
643
644 my $fast_cataloging = 0;
645 if (defined getframeworkinfo('FA')) {
646     $fast_cataloging = 1 
647 }
648
649 if (C4::Context->preference('ExtendedPatronAttributes')) {
650     my $attributes = GetBorrowerAttributes($borrowernumber);
651     $template->param(
652         ExtendedPatronAttributes => 1,
653         extendedattributes => $attributes
654     );
655 }
656
657 $template->param(
658     lib_messages_loop => $lib_messages_loop,
659     bor_messages_loop => $bor_messages_loop,
660     all_messages_del  => C4::Context->preference('AllowAllMessageDeletion'),
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     showname          => $borrower->{'showname'},
671     category_type     => $borrower->{'category_type'},
672     dateexpiry        => $newexpiry,
673     expiry            => $borrower->{'dateexpiry'},
674     categorycode      => $borrower->{'categorycode'},
675     categoryname      => $borrower->{description},
676     address           => $address,
677     address2          => $borrower->{'address2'},
678     email             => $borrower->{'email'},
679     emailpro          => $borrower->{'emailpro'},
680     borrowernotes     => $borrower->{'borrowernotes'},
681     city              => $borrower->{'city'},
682     state              => $borrower->{'state'},
683     zipcode           => $borrower->{'zipcode'},
684     country           => $borrower->{'country'},
685     phone             => $borrower->{'phone'} || $borrower->{'mobile'},
686     cardnumber        => $borrower->{'cardnumber'},
687     othernames        => $borrower->{'othernames'},
688     amountold         => $amountold,
689     barcode           => $barcode,
690     stickyduedate     => $stickyduedate,
691     duedatespec       => $duedatespec,
692     message           => $message,
693     CGIselectborrower => $CGIselectborrower,
694     totalprice        => sprintf('%.2f', $totalprice),
695     totaldue          => sprintf('%.2f', $total),
696     todayissues       => \@todaysissues,
697     previssues        => \@previousissues,
698     relissues                   => \@relissues,
699     relprevissues               => \@relprevissues,
700     displayrelissues            => $displayrelissues,
701     inprocess         => $inprocess,
702     memberofinstution => $member_of_institution,
703     CGIorganisations  => $CGIorganisations,
704     is_child          => ($borrower->{'category_type'} eq 'C'),
705     circview => 1,
706     soundon           => C4::Context->preference("SoundOn"),
707     fast_cataloging   => $fast_cataloging,
708     CircAutoPrintQuickSlip   => C4::Context->preference("CircAutoPrintQuickSlip"),
709     activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
710     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
711     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
712 );
713
714 # save stickyduedate to session
715 if ($stickyduedate) {
716     $session->param( 'stickyduedate', $duedatespec );
717 }
718
719 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
720 $template->param( picture => 1 ) if $picture;
721
722 # get authorised values with type of BOR_NOTES
723
724 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
725
726 $template->param(
727     debt_confirmed            => $debt_confirmed,
728     SpecifyDueDate            => $duedatespec_allow,
729     CircAutocompl             => C4::Context->preference("CircAutocompl"),
730         AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
731     dateformat                => C4::Context->preference("dateformat"),
732     DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar(),
733     canned_bor_notes_loop     => $canned_notes,
734 );
735
736 output_html_with_http_headers $query, $cookie, $template->output;