Bug 5396: New system preference UseTablesortForCirc
[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                     NEEDSCONFIRMATION  => 1
306                 );
307                 $confirm_required = 1;
308             }
309         }
310         unless($confirm_required) {
311             AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
312             $inprocess = 1;
313             if($globalduedate && ! $stickyduedate && $duedatespec_allow ){
314                 $duedatespec = $globalduedate->output();
315                 $stickyduedate = 1;
316             }
317         }
318     }
319     
320     # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue 
321     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
322     $template->param( issuecount   => $issue );
323 }
324
325 # reload the borrower info for the sake of reseting the flags.....
326 if ($borrowernumber) {
327     $borrower = GetMemberDetails( $borrowernumber, 0 );
328 }
329
330 ##################################################################################
331 # BUILD HTML
332 # show all reserves of this borrower, and the position of the reservation ....
333 if ($borrowernumber) {
334
335     # new op dev
336     # now we show the status of the borrower's reservations
337     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
338     my @reservloop;
339     my @WaitingReserveLoop;
340     
341     foreach my $num_res (@borrowerreserv) {
342         my %getreserv;
343         my %getWaitingReserveInfo;
344         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
345         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
346         my ( $transfertwhen, $transfertfrom, $transfertto ) =
347           GetTransfers( $num_res->{'itemnumber'} );
348
349         $getreserv{waiting}       = 0;
350         $getreserv{transfered}    = 0;
351         $getreserv{nottransfered} = 0;
352
353         $getreserv{reservedate}    = format_date( $num_res->{'reservedate'} );
354         $getreserv{title}          = $getiteminfo->{'title'};
355         $getreserv{itemtype}       = $itemtypeinfo->{'description'};
356         $getreserv{author}         = $getiteminfo->{'author'};
357         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
358         $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
359         $getreserv{biblionumber}   = $getiteminfo->{'biblionumber'};
360         $getreserv{waitingat}      = GetBranchName( $num_res->{'branchcode'} );
361         #         check if we have a waiting status for reservations
362         if ( $num_res->{'found'} eq 'W' ) {
363             $getreserv{color}   = 'reserved';
364             $getreserv{waiting} = 1;
365 #     genarate information displaying only waiting reserves
366         $getWaitingReserveInfo{title}        = $getiteminfo->{'title'};
367         $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
368         $getWaitingReserveInfo{itemtype}     = $itemtypeinfo->{'description'};
369         $getWaitingReserveInfo{author}       = $getiteminfo->{'author'};
370         $getWaitingReserveInfo{reservedate}  = format_date( $num_res->{'reservedate'} );
371         $getWaitingReserveInfo{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
372         $getWaitingReserveInfo{waitinghere}  = 1 if $num_res->{'branchcode'} eq $branch;
373         }
374         #         check transfers with the itemnumber foud in th reservation loop
375         if ($transfertwhen) {
376             $getreserv{color}      = 'transfered';
377             $getreserv{transfered} = 1;
378             $getreserv{datesent}   = format_date($transfertwhen);
379             $getreserv{frombranch} = GetBranchName($transfertfrom);
380         } elsif ($getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'}) {
381             $getreserv{nottransfered}   = 1;
382             $getreserv{nottransferedby} = GetBranchName( $getiteminfo->{'holdingbranch'} );
383         }
384
385 #         if we don't have a reserv on item, we put the biblio infos and the waiting position
386         if ( $getiteminfo->{'title'} eq '' ) {
387             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
388
389             $getreserv{color}           = 'inwait';
390             $getreserv{title}           = $getbibinfo->{'title'};
391             $getreserv{nottransfered}   = 0;
392             $getreserv{itemtype}        = $itemtypeinfo->{'description'};
393             $getreserv{author}          = $getbibinfo->{'author'};
394             $getreserv{biblionumber}    = $num_res->{'biblionumber'};
395         }
396         $getreserv{waitingposition} = $num_res->{'priority'};
397         push( @reservloop, \%getreserv );
398
399 #         if we have a reserve waiting, initiate waitingreserveloop
400         if ($getreserv{waiting} == 1) {
401         push (@WaitingReserveLoop, \%getWaitingReserveInfo)
402         }
403       
404     }
405
406     # return result to the template
407     $template->param( 
408         countreserv => scalar @reservloop,
409         reservloop  => \@reservloop ,
410         WaitingReserveLoop  => \@WaitingReserveLoop,
411     );
412     $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
413 }
414
415 # make the issued books table.
416 my $todaysissues = '';
417 my $previssues   = '';
418 my @todaysissues;
419 my @previousissues;
420
421 my $totalprice = 0;
422
423 if ($borrower) {
424 # get each issue of the borrower & separate them in todayissues & previous issues
425     my ($issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
426     # split in 2 arrays for today & previous
427     foreach my $it ( @$issueslist ) {
428         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $it->{'itype'} : $it->{'itemtype'} );
429         # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
430         $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
431
432         ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
433             $it->{'itemnumber'}, $borrower->{'borrowernumber'}
434         );
435         $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
436         my ($can_renew, $can_renew_error) = CanBookBeRenewed( 
437             $borrower->{'borrowernumber'},$it->{'itemnumber'}
438         );
439         $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
440         my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
441         $it->{'can_renew'} = $can_renew;
442         $it->{'can_confirm'} = !$can_renew && !$restype;
443         $it->{'renew_error'} = $restype;
444         $it->{'checkoutdate'} = C4::Dates->new($it->{'issuedate'},'iso')->output('syspref');
445
446         $totalprice += $it->{'replacementprice'};
447         $it->{'itemtype'} = $itemtypeinfo->{'description'};
448         $it->{'itemtype_image'} = $itemtypeinfo->{'imageurl'};
449         $it->{'dd'} = format_date($it->{'date_due'});
450         $it->{'displaydate'} = format_date($it->{'issuedate'});
451         $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
452         ($it->{'author'} eq '') and $it->{'author'} = ' ';
453         $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
454
455         if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
456             push @todaysissues, $it;
457         } else {
458             push @previousissues, $it;
459         }
460     }
461     if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
462         @todaysissues   = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
463     }
464     else {
465         @todaysissues   = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
466     }
467     if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
468         @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
469     }
470     else {
471         @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
472     }
473 }
474
475
476 my @values;
477 my %labels;
478 my $CGIselectborrower;
479 if ($borrowerslist) {
480     foreach (
481         sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
482         } @$borrowerslist
483       )
484     {
485         push @values, $_->{'borrowernumber'};
486         $labels{ $_->{'borrowernumber'} } =
487 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ...  $_->{'address'} ";
488     }
489     $CGIselectborrower = CGI::scrolling_list(
490         -name     => 'borrowernumber',
491         -class    => 'focus',
492         -id       => 'borrowernumber',
493         -values   => \@values,
494         -labels   => \%labels,
495         -onclick  => "window.location = '/cgi-bin/koha/circ/circulation.pl?borrowernumber=' + this.value;",
496         -size     => 7,
497         -tabindex => '',
498         -multiple => 0
499     );
500 }
501
502 #title
503 my $flags = $borrower->{'flags'};
504 foreach my $flag ( sort keys %$flags ) {
505     $template->param( flagged=> 1);
506     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
507     if ( $flags->{$flag}->{'noissues'} ) {
508         $template->param(
509             flagged  => 1,
510             noissues => 'true',
511         );
512         if ( $flag eq 'GNA' ) {
513             $template->param( gna => 'true' );
514         }
515         elsif ( $flag eq 'LOST' ) {
516             $template->param( lost => 'true' );
517         }
518         elsif ( $flag eq 'DBARRED' ) {
519             $template->param( dbarred => 'true' );
520         }
521         elsif ( $flag eq 'CHARGES' ) {
522             $template->param(
523                 charges    => 'true',
524                 chargesmsg => $flags->{'CHARGES'}->{'message'},
525                 chargesamount => $flags->{'CHARGES'}->{'amount'},
526                 charges_is_blocker => 1
527             );
528         }
529         elsif ( $flag eq 'CREDITS' ) {
530             $template->param(
531                 credits    => 'true',
532                 creditsmsg => $flags->{'CREDITS'}->{'message'},
533                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
534             );
535         }
536     }
537     else {
538         if ( $flag eq 'CHARGES' ) {
539             $template->param(
540                 charges    => 'true',
541                 flagged    => 1,
542                 chargesmsg => $flags->{'CHARGES'}->{'message'},
543                 chargesamount => $flags->{'CHARGES'}->{'amount'},
544             );
545         }
546         elsif ( $flag eq 'CREDITS' ) {
547             $template->param(
548                 credits    => 'true',
549                 creditsmsg => $flags->{'CREDITS'}->{'message'},
550                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
551             );
552         }
553         elsif ( $flag eq 'ODUES' ) {
554             $template->param(
555                 odues    => 'true',
556                 flagged  => 1,
557                 oduesmsg => $flags->{'ODUES'}->{'message'}
558             );
559
560             my $items = $flags->{$flag}->{'itemlist'};
561             if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
562                 $template->param( nonreturns => 'true' );
563             }
564         }
565         elsif ( $flag eq 'NOTES' ) {
566             $template->param(
567                 notes    => 'true',
568                 flagged  => 1,
569                 notesmsg => $flags->{'NOTES'}->{'message'}
570             );
571         }
572     }
573 }
574
575 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
576 $amountold =~ s/^.*\$//;    # remove upto the $, if any
577
578 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
579
580 if ( $borrower->{'category_type'} eq 'C') {
581     my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
582     my $cnt = scalar(@$catcodes);
583     $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
584     $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
585 }
586
587 my $CGIorganisations;
588 my $member_of_institution;
589 if ( C4::Context->preference("memberofinstitution") ) {
590     my $organisations = get_institutions();
591     my @orgs;
592     my %org_labels;
593     foreach my $organisation ( keys %$organisations ) {
594         push @orgs, $organisation;
595         $org_labels{$organisation} = $organisations->{$organisation}->{'surname'};
596     }
597     $member_of_institution = 1;
598     $CGIorganisations      = CGI::popup_menu(
599         -id     => 'organisations',
600         -name   => 'organisations',
601         -labels => \%org_labels,
602         -values => \@orgs,
603     );
604 }
605
606 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
607 if($lib_messages_loop){ $template->param(flagged => 1 ); }
608
609 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
610 if($bor_messages_loop){ $template->param(flagged => 1 ); }
611
612 # Computes full borrower address
613 my (undef, $roadttype_hashref) = &GetRoadTypes();
614 my $address = $borrower->{'streetnumber'}.' '.$roadttype_hashref->{$borrower->{'streettype'}}.' '.$borrower->{'address'};
615
616 $template->param(
617     lib_messages_loop => $lib_messages_loop,
618     bor_messages_loop => $bor_messages_loop,
619     all_messages_del  => C4::Context->preference('AllowAllMessageDeletion'),
620     findborrower      => $findborrower,
621     borrower          => $borrower,
622     borrowernumber    => $borrowernumber,
623     branch            => $branch,
624     branchname        => GetBranchName($borrower->{'branchcode'}),
625     printer           => $printer,
626     printername       => $printer,
627     firstname         => $borrower->{'firstname'},
628     surname           => $borrower->{'surname'},
629     dateexpiry        => format_date($newexpiry),
630     expiry            => format_date($borrower->{'dateexpiry'}),
631     categorycode      => $borrower->{'categorycode'},
632     categoryname      => $borrower->{description},
633     address           => $address,
634     address2          => $borrower->{'address2'},
635     email             => $borrower->{'email'},
636     emailpro          => $borrower->{'emailpro'},
637     borrowernotes     => $borrower->{'borrowernotes'},
638     city              => $borrower->{'city'},
639     zipcode           => $borrower->{'zipcode'},
640     country           => $borrower->{'country'},
641     phone             => $borrower->{'phone'} || $borrower->{'mobile'},
642     cardnumber        => $borrower->{'cardnumber'},
643     amountold         => $amountold,
644     barcode           => $barcode,
645     stickyduedate     => $stickyduedate,
646     duedatespec       => $duedatespec,
647     message           => $message,
648     CGIselectborrower => $CGIselectborrower,
649     totalprice        => sprintf('%.2f', $totalprice),
650     totaldue          => sprintf('%.2f', $total),
651     todayissues       => \@todaysissues,
652     previssues        => \@previousissues,
653     inprocess         => $inprocess,
654     memberofinstution => $member_of_institution,
655     CGIorganisations  => $CGIorganisations,
656     is_child          => ($borrower->{'category_type'} eq 'C'),
657     circview => 1,
658     soundon           => C4::Context->preference("SoundOn"),
659 );
660
661 # save stickyduedate to session
662 if ($stickyduedate) {
663     $session->param( 'stickyduedate', $duedatespec );
664 }
665
666 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
667 $template->param( picture => 1 ) if $picture;
668
669 # get authorised values with type of BOR_NOTES
670
671 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
672
673 $template->param(
674     debt_confirmed            => $debt_confirmed,
675     SpecifyDueDate            => $duedatespec_allow,
676     CircAutocompl             => C4::Context->preference("CircAutocompl"),
677         AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
678     dateformat                => C4::Context->preference("dateformat"),
679     DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar(),
680     canned_bor_notes_loop     => $canned_notes,
681 );
682 output_html_with_http_headers $query, $cookie, $template->output;