Merge remote-tracking branch 'origin/new/bug_5327'
[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->{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}    = format_date( $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         #         check if we have a waiting status for reservations
362         if ( $num_res->{'found'} eq 'W' ) {
363             $getreserv{color}   = 'reserved';
364             $getreserv{waiting} = 1;
365 #     genarate information displaying only waiting reserves
366         $getWaitingReserveInfo{title}        = $getiteminfo->{'title'};
367         $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
368         $getWaitingReserveInfo{itemtype}     = $itemtypeinfo->{'description'};
369         $getWaitingReserveInfo{author}       = $getiteminfo->{'author'};
370         $getWaitingReserveInfo{reservedate}  = format_date( $num_res->{'reservedate'} );
371         $getWaitingReserveInfo{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
372         $getWaitingReserveInfo{waitinghere}  = 1 if $num_res->{'branchcode'} eq $branch;
373         }
374         #         check transfers with the itemnumber foud in th reservation loop
375         if ($transfertwhen) {
376             $getreserv{color}      = 'transfered';
377             $getreserv{transfered} = 1;
378             $getreserv{datesent}   = format_date($transfertwhen);
379             $getreserv{frombranch} = GetBranchName($transfertfrom);
380         } elsif ($getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'}) {
381             $getreserv{nottransfered}   = 1;
382             $getreserv{nottransferedby} = GetBranchName( $getiteminfo->{'holdingbranch'} );
383         }
384
385 #         if we don't have a reserv on item, we put the biblio infos and the waiting position
386         if ( $getiteminfo->{'title'} eq '' ) {
387             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
388
389             $getreserv{color}           = 'inwait';
390             $getreserv{title}           = $getbibinfo->{'title'};
391             $getreserv{nottransfered}   = 0;
392             $getreserv{itemtype}        = $itemtypeinfo->{'description'};
393             $getreserv{author}          = $getbibinfo->{'author'};
394             $getreserv{biblionumber}    = $num_res->{'biblionumber'};
395         }
396         $getreserv{waitingposition} = $num_res->{'priority'};
397         push( @reservloop, \%getreserv );
398
399 #         if we have a reserve waiting, initiate waitingreserveloop
400         if ($getreserv{waiting} == 1) {
401         push (@WaitingReserveLoop, \%getWaitingReserveInfo)
402         }
403       
404     }
405
406     # return result to the template
407     $template->param( 
408         countreserv => scalar @reservloop,
409         reservloop  => \@reservloop ,
410         WaitingReserveLoop  => \@WaitingReserveLoop,
411     );
412     $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
413 }
414
415 # make the issued books table.
416 my $todaysissues = '';
417 my $previssues   = '';
418 my @todaysissues;
419 my @previousissues;
420 my @relissues;
421 my @relprevissues;
422 my $displayrelissues;
423
424 my $totalprice = 0;
425
426 sub build_issue_data {
427     my $issueslist = shift;
428     my $relatives = shift;
429
430     # split in 2 arrays for today & previous
431     foreach my $it ( @$issueslist ) {
432         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $it->{'itype'} : $it->{'itemtype'} );
433
434         # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
435         $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
436
437         ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
438             $it->{'itemnumber'}, $it->{'borrowernumber'}
439         );
440         $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
441         my ($can_renew, $can_renew_error) = CanBookBeRenewed( 
442             $it->{'borrowernumber'},$it->{'itemnumber'}
443         );
444         $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
445         my ( $restype, $reserves, undef ) = CheckReserves( $it->{'itemnumber'} );
446         $it->{'can_renew'} = $can_renew;
447         $it->{'can_confirm'} = !$can_renew && !$restype;
448         $it->{'renew_error'} = $restype;
449         $it->{'checkoutdate'} = C4::Dates->new($it->{'issuedate'},'iso')->output('syspref');
450         $it->{'issuingbranchname'} = GetBranchName($it->{'branchcode'});
451
452         $totalprice += $it->{'replacementprice'};
453         $it->{'itemtype'} = $itemtypeinfo->{'description'};
454         $it->{'itemtype_image'} = $itemtypeinfo->{'imageurl'};
455         $it->{'dd'} = format_date($it->{'date_due'});
456         $it->{'displaydate'} = format_date($it->{'issuedate'});
457         $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
458         ($it->{'author'} eq '') and $it->{'author'} = ' ';
459         $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
460
461         if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
462             (!$relatives) ? push @todaysissues, $it : push @relissues, $it;
463         } else {
464             (!$relatives) ? push @previousissues, $it : push @relprevissues, $it;
465         }
466     }
467 }
468
469 if ($borrower) {
470
471     # Getting borrower relatives
472     my @relborrowernumbers = GetMemberRelatives($borrower->{'borrowernumber'});
473     #push @borrowernumbers, $borrower->{'borrowernumber'};
474
475     # get each issue of the borrower & separate them in todayissues & previous issues
476     my $issueslist = GetPendingIssues($borrower->{'borrowernumber'});
477     my $relissueslist = [];
478     if ( @relborrowernumbers ) {
479         $relissueslist = GetPendingIssues(@relborrowernumbers);
480     }
481
482     build_issue_data($issueslist, 0);
483     build_issue_data($relissueslist, 1);
484   
485     $displayrelissues = scalar($relissueslist);
486
487     if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
488         @todaysissues   = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
489     }
490     else {
491         @todaysissues   = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
492     }
493
494     if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
495         @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
496     }
497     else {
498         @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
499     }
500 }
501
502
503 my @values;
504 my %labels;
505 my $CGIselectborrower;
506 if ($borrowerslist) {
507     foreach (
508         sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
509         } @$borrowerslist
510       )
511     {
512         push @values, $_->{'borrowernumber'};
513         $labels{ $_->{'borrowernumber'} } =
514 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ...  $_->{'address'} ";
515     }
516     $CGIselectborrower = CGI::scrolling_list(
517         -name     => 'borrowernumber',
518         -class    => 'focus',
519         -id       => 'borrowernumber',
520         -values   => \@values,
521         -labels   => \%labels,
522         -ondblclick => 'document.forms[\'mainform\'].submit()',
523         -size     => 7,
524         -tabindex => '',
525         -multiple => 0
526     );
527 }
528
529 #title
530 my $flags = $borrower->{'flags'};
531 foreach my $flag ( sort keys %$flags ) {
532     $template->param( flagged=> 1);
533     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
534     if ( $flags->{$flag}->{'noissues'} ) {
535         $template->param(
536             flagged  => 1,
537             noissues => 'true',
538         );
539         if ( $flag eq 'GNA' ) {
540             $template->param( gna => 'true' );
541         }
542         elsif ( $flag eq 'LOST' ) {
543             $template->param( lost => 'true' );
544         }
545         elsif ( $flag eq 'DBARRED' ) {
546             $template->param( dbarred => 'true' );
547         }
548         elsif ( $flag eq 'CHARGES' ) {
549             $template->param(
550                 charges    => 'true',
551                 chargesmsg => $flags->{'CHARGES'}->{'message'},
552                 chargesamount => $flags->{'CHARGES'}->{'amount'},
553                 charges_is_blocker => 1
554             );
555         }
556         elsif ( $flag eq 'CREDITS' ) {
557             $template->param(
558                 credits    => 'true',
559                 creditsmsg => $flags->{'CREDITS'}->{'message'},
560                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
561             );
562         }
563     }
564     else {
565         if ( $flag eq 'CHARGES' ) {
566             $template->param(
567                 charges    => 'true',
568                 flagged    => 1,
569                 chargesmsg => $flags->{'CHARGES'}->{'message'},
570                 chargesamount => $flags->{'CHARGES'}->{'amount'},
571             );
572         }
573         elsif ( $flag eq 'CREDITS' ) {
574             $template->param(
575                 credits    => 'true',
576                 creditsmsg => $flags->{'CREDITS'}->{'message'},
577                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
578             );
579         }
580         elsif ( $flag eq 'ODUES' ) {
581             $template->param(
582                 odues    => 'true',
583                 flagged  => 1,
584                 oduesmsg => $flags->{'ODUES'}->{'message'}
585             );
586
587             my $items = $flags->{$flag}->{'itemlist'};
588             if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
589                 $template->param( nonreturns => 'true' );
590             }
591         }
592         elsif ( $flag eq 'NOTES' ) {
593             $template->param(
594                 notes    => 'true',
595                 flagged  => 1,
596                 notesmsg => $flags->{'NOTES'}->{'message'}
597             );
598         }
599     }
600 }
601
602 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
603 $amountold =~ s/^.*\$//;    # remove upto the $, if any
604
605 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
606
607 if ( $borrower->{'category_type'} eq 'C') {
608     my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
609     my $cnt = scalar(@$catcodes);
610     $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
611     $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
612 }
613
614 my $CGIorganisations;
615 my $member_of_institution;
616 if ( C4::Context->preference("memberofinstitution") ) {
617     my $organisations = get_institutions();
618     my @orgs;
619     my %org_labels;
620     foreach my $organisation ( keys %$organisations ) {
621         push @orgs, $organisation;
622         $org_labels{$organisation} = $organisations->{$organisation}->{'surname'};
623     }
624     $member_of_institution = 1;
625     $CGIorganisations      = CGI::popup_menu(
626         -id     => 'organisations',
627         -name   => 'organisations',
628         -labels => \%org_labels,
629         -values => \@orgs,
630     );
631 }
632
633 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
634 if($lib_messages_loop){ $template->param(flagged => 1 ); }
635
636 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
637 if($bor_messages_loop){ $template->param(flagged => 1 ); }
638
639 # Computes full borrower address
640 my (undef, $roadttype_hashref) = &GetRoadTypes();
641 my $address = $borrower->{'streetnumber'}.' '.$roadttype_hashref->{$borrower->{'streettype'}}.' '.$borrower->{'address'};
642
643 my $fast_cataloging = 0;
644 if (defined getframeworkinfo('FA')) {
645     $fast_cataloging = 1 
646 }
647
648 if (C4::Context->preference('ExtendedPatronAttributes')) {
649     my $attributes = GetBorrowerAttributes($borrowernumber);
650     $template->param(
651         ExtendedPatronAttributes => 1,
652         extendedattributes => $attributes
653     );
654 }
655
656 $template->param(
657     lib_messages_loop => $lib_messages_loop,
658     bor_messages_loop => $bor_messages_loop,
659     all_messages_del  => C4::Context->preference('AllowAllMessageDeletion'),
660     findborrower      => $findborrower,
661     borrower          => $borrower,
662     borrowernumber    => $borrowernumber,
663     branch            => $branch,
664     branchname        => GetBranchName($borrower->{'branchcode'}),
665     printer           => $printer,
666     printername       => $printer,
667     firstname         => $borrower->{'firstname'},
668     surname           => $borrower->{'surname'},
669     showname          => $borrower->{'showname'},
670     category_type     => $borrower->{'category_type'},
671     dateexpiry        => format_date($newexpiry),
672     expiry            => format_date($borrower->{'dateexpiry'}),
673     categorycode      => $borrower->{'categorycode'},
674     categoryname      => $borrower->{description},
675     address           => $address,
676     address2          => $borrower->{'address2'},
677     email             => $borrower->{'email'},
678     emailpro          => $borrower->{'emailpro'},
679     borrowernotes     => $borrower->{'borrowernotes'},
680     city              => $borrower->{'city'},
681     state              => $borrower->{'state'},
682     zipcode           => $borrower->{'zipcode'},
683     country           => $borrower->{'country'},
684     phone             => $borrower->{'phone'} || $borrower->{'mobile'},
685     cardnumber        => $borrower->{'cardnumber'},
686     othernames        => $borrower->{'othernames'},
687     amountold         => $amountold,
688     barcode           => $barcode,
689     stickyduedate     => $stickyduedate,
690     duedatespec       => $duedatespec,
691     message           => $message,
692     CGIselectborrower => $CGIselectborrower,
693     totalprice        => sprintf('%.2f', $totalprice),
694     totaldue          => sprintf('%.2f', $total),
695     todayissues       => \@todaysissues,
696     previssues        => \@previousissues,
697     relissues                   => \@relissues,
698     relprevissues               => \@relprevissues,
699     displayrelissues            => $displayrelissues,
700     inprocess         => $inprocess,
701     memberofinstution => $member_of_institution,
702     CGIorganisations  => $CGIorganisations,
703     is_child          => ($borrower->{'category_type'} eq 'C'),
704     circview => 1,
705     soundon           => C4::Context->preference("SoundOn"),
706     fast_cataloging   => $fast_cataloging,
707     CircAutoPrintQuickSlip   => C4::Context->preference("CircAutoPrintQuickSlip"),
708 );
709
710 # save stickyduedate to session
711 if ($stickyduedate) {
712     $session->param( 'stickyduedate', $duedatespec );
713 }
714
715 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
716 $template->param( picture => 1 ) if $picture;
717
718 # get authorised values with type of BOR_NOTES
719
720 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
721
722 $template->param(
723     debt_confirmed            => $debt_confirmed,
724     SpecifyDueDate            => $duedatespec_allow,
725     CircAutocompl             => C4::Context->preference("CircAutocompl"),
726         AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
727     dateformat                => C4::Context->preference("dateformat"),
728     DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar(),
729     canned_bor_notes_loop     => $canned_notes,
730 );
731 output_html_with_http_headers $query, $cookie, $template->output;