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