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