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