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