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