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