Merge commit 'origin/master' into sopac
[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 with
20 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
21 # Suite 330, Boston, MA  02111-1307 USA
22
23 use strict;
24 # use warnings;  # FIXME
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 #$findborrower =~ s|'| |g;
98 my $borrowernumber = $query->param('borrowernumber');
99
100 $branch  = C4::Context->userenv->{'branch'};  
101 $printer = C4::Context->userenv->{'branchprinter'};
102
103
104 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
105 if (C4::Context->preference("AutoLocation") ne 1) { # FIXME: string comparison to number
106     $template->param(ManualLocation => 1);
107 }
108
109 if (C4::Context->preference("DisplayClearScreenButton")) {
110     $template->param(DisplayClearScreenButton => 1);
111 }
112
113 my $barcode        = $query->param('barcode') || '';
114 $barcode =~  s/^\s*|\s*$//g; # remove leading/trailing whitespace
115
116 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
117 my $stickyduedate  = $query->param('stickyduedate') || $session->param('stickyduedate');
118 my $duedatespec    = $query->param('duedatespec')   || $session->param('stickyduedate');
119 my $issueconfirmed = $query->param('issueconfirmed');
120 my $cancelreserve  = $query->param('cancelreserve');
121 my $organisation   = $query->param('organisations');
122 my $print          = $query->param('print');
123 my $newexpiry      = $query->param('dateexpiry');
124 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
125
126 # Check if stickyduedate is turned off
127 if ( $barcode ) {
128     # was stickyduedate loaded from session?
129     if ( $stickyduedate && ! $query->param("stickyduedate") ) {
130         $session->clear( 'stickyduedate' );
131         $stickyduedate  = $query->param('stickyduedate');
132         $duedatespec    = $query->param('duedatespec');
133     }
134 }
135
136 #set up cookie.....
137 # my $branchcookie;
138 # my $printercookie;
139 # if ($query->param('setcookies')) {
140 #     $branchcookie = $query->cookie(-name=>'branch', -value=>"$branch", -expires=>'+1y');
141 #     $printercookie = $query->cookie(-name=>'printer', -value=>"$printer", -expires=>'+1y');
142 # }
143 #
144
145 my ($datedue,$invalidduedate,$globalduedate);
146
147 if(C4::Context->preference('globalDueDate') && (C4::Context->preference('globalDueDate') =~ C4::Dates->regexp('syspref'))){
148         $globalduedate = C4::Dates->new(C4::Context->preference('globalDueDate'));
149 }
150 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
151 if($duedatespec_allow){
152     if ($duedatespec) {
153         if ($duedatespec =~ C4::Dates->regexp('syspref')) {
154                 my $tempdate = C4::Dates->new($duedatespec);
155                 if ($tempdate and $tempdate->output('iso') gt C4::Dates->new()->output('iso')) {
156                         # i.e., it has to be later than today/now
157                         $datedue = $tempdate;
158                 } else {
159                         $invalidduedate = 1;
160                         $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
161                 }
162         } else {
163                 $invalidduedate = 1;
164                 $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
165         }
166     } else {
167         # pass global due date to tmpl if specifyduedate is true 
168         # and we have no barcode (loading circ page but not checking out)
169         if($globalduedate &&  ! $barcode ){
170             $duedatespec = $globalduedate->output();
171             $stickyduedate = 1;
172         }
173     }
174 } else {
175     $datedue = $globalduedate if ($globalduedate);
176 }
177
178 my $todaysdate = C4::Dates->new->output('iso');
179
180 # check and see if we should print
181 if ( $barcode eq '' && $print eq 'maybe' ) {
182     $print = 'yes';
183 }
184
185 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
186 if ( $barcode eq '' && $query->param('charges') eq 'yes' ) {
187     $template->param(
188         PAYCHARGES     => 'yes',
189         borrowernumber => $borrowernumber
190     );
191 }
192
193 if ( $print eq 'yes' && $borrowernumber ne '' ) {
194     printslip( $borrowernumber );
195     $query->param( 'borrowernumber', '' );
196     $borrowernumber = '';
197 }
198
199 #
200 # STEP 2 : FIND BORROWER
201 # if there is a list of find borrowers....
202 #
203 my $borrowerslist;
204 my $message;
205 if ($findborrower) {
206     my ($count, $borrowers) = SearchMember($findborrower, 'cardnumber', 'web');
207     my @borrowers = @$borrowers;
208     if (C4::Context->preference("AddPatronLists")) {
209         $template->param(
210             "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
211         );
212         if (C4::Context->preference("AddPatronLists")=~/code/){
213             my $categories = GetBorrowercategoryList;
214             $categories->[0]->{'first'} = 1;
215             $template->param(categories=>$categories);
216         }
217     }
218     if ( $#borrowers == -1 ) {
219         $query->param( 'findborrower', '' );
220         $message = "'$findborrower'";
221     }
222     elsif ( $#borrowers == 0 ) {
223         $query->param( 'borrowernumber', $borrowers[0]->{'borrowernumber'} );
224         $query->param( 'barcode',           '' );
225         $borrowernumber = $borrowers[0]->{'borrowernumber'};
226     }
227     else {
228         $borrowerslist = \@borrowers;
229     }
230 }
231
232 # get the borrower information.....
233 my $borrower;
234 if ($borrowernumber) {
235     $borrower = GetMemberDetails( $borrowernumber, 0 );
236     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
237
238     # Warningdate is the date that the warning starts appearing
239     my (  $today_year,   $today_month,   $today_day) = Today();
240     my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
241     my (  $enrol_year,   $enrol_month,   $enrol_day) = split /-/, $borrower->{'dateenrolled'};
242     # Renew day is calculated by adding the enrolment period to today
243     my (  $renew_year,   $renew_month,   $renew_day) =
244       Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
245         0 , $borrower->{'enrolmentperiod'}) if ($enrol_year*$enrol_month*$enrol_day>0);
246     # if the expiry date is before today ie they have expired
247     if ( $warning_year*$warning_month*$warning_day==0 
248         || Date_to_Days($today_year,     $today_month, $today_day  ) 
249          > Date_to_Days($warning_year, $warning_month, $warning_day) )
250     {
251         #borrowercard expired, no issues
252         $template->param(
253             flagged  => "1",
254             noissues => "1",
255             expired     => format_date($borrower->{dateexpiry}),
256             renewaldate => format_date("$renew_year-$renew_month-$renew_day")
257         );
258     }
259     # check for NotifyBorrowerDeparture
260     elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
261             Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
262             Date_to_Days( $today_year, $today_month, $today_day ) ) 
263     {
264         # borrower card soon to expire warn librarian
265         $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
266         flagged       => "1",);
267         if (C4::Context->preference('ReturnBeforeExpiry')){
268             $template->param("returnbeforeexpiry" => 1);
269         }
270     }
271     $template->param(
272         overduecount => $od,
273         issuecount   => $issue,
274         finetotal    => $fines
275     );
276 }
277
278 #
279 # STEP 3 : ISSUING
280 #
281 #
282 if ($barcode) {
283   # always check for blockers on issuing
284   my ( $error, $question ) =
285     CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
286   my $blocker = $invalidduedate ? 1 : 0;
287
288   delete $question->{'DEBT'} if ($debt_confirmed);
289   foreach my $impossible ( keys %$error ) {
290             $template->param(
291                 $impossible => $$error{$impossible},
292                 IMPOSSIBLE  => 1
293             );
294             $blocker = 1;
295         }
296     if( !$blocker ){
297         my $confirm_required = 0;
298         unless($issueconfirmed){
299             #  Get the item title for more information
300             my $getmessageiteminfo  = GetBiblioFromItemNumber(undef,$barcode);
301                     $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
302
303                     # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
304             foreach my $needsconfirmation ( keys %$question ) {
305                 $template->param(
306                     $needsconfirmation => $$question{$needsconfirmation},
307                     getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
308                     NEEDSCONFIRMATION  => 1
309                 );
310                 $confirm_required = 1;
311             }
312                 }
313         unless($confirm_required) {
314             AddIssue( $borrower, $barcode, $datedue, $cancelreserve );
315                         $inprocess = 1;
316             if($globalduedate && ! $stickyduedate && $duedatespec_allow ){
317                 $duedatespec = $globalduedate->output();
318                 $stickyduedate = 1;
319             }
320                 }
321     }
322     
323     # FIXME If the issue is confirmed, we launch another time GetMemberIssuesAndFines, now display the issue count after issue 
324     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
325     $template->param( issuecount   => $issue );
326 }
327
328 # reload the borrower info for the sake of reseting the flags.....
329 if ($borrowernumber) {
330     $borrower = GetMemberDetails( $borrowernumber, 0 );
331 }
332
333 ##################################################################################
334 # BUILD HTML
335 # show all reserves of this borrower, and the position of the reservation ....
336 my $borrowercategory;
337 my $category_type;
338 if ($borrowernumber) {
339
340     # new op dev
341     # now we show the status of the borrower's reservations
342     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
343     my @reservloop;
344     my @WaitingReserveLoop;
345     
346     foreach my $num_res (@borrowerreserv) {
347         my %getreserv;
348         my %getWaitingReserveInfo;
349         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
350         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $getiteminfo->{'itype'} : $getiteminfo->{'itemtype'} );
351         my ( $transfertwhen, $transfertfrom, $transfertto ) =
352           GetTransfers( $num_res->{'itemnumber'} );
353
354         $getreserv{waiting}       = 0;
355         $getreserv{transfered}    = 0;
356         $getreserv{nottransfered} = 0;
357
358         $getreserv{reservedate}    = format_date( $num_res->{'reservedate'} );
359         $getreserv{title}          = $getiteminfo->{'title'};
360         $getreserv{itemtype}       = $itemtypeinfo->{'description'};
361         $getreserv{author}         = $getiteminfo->{'author'};
362         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
363         $getreserv{itemcallnumber} = $getiteminfo->{'itemcallnumber'};
364         $getreserv{biblionumber}   = $getiteminfo->{'biblionumber'};
365         $getreserv{waitingat}      = GetBranchName( $num_res->{'branchcode'} );
366         #         check if we have a waiting status for reservations
367         if ( $num_res->{'found'} eq 'W' ) {
368             $getreserv{color}   = 'reserved';
369             $getreserv{waiting} = 1;
370 #     genarate information displaying only waiting reserves
371         $getWaitingReserveInfo{title}        = $getiteminfo->{'title'};
372         $getWaitingReserveInfo{biblionumber} = $getiteminfo->{'biblionumber'};
373         $getWaitingReserveInfo{itemtype}     = $itemtypeinfo->{'description'};
374         $getWaitingReserveInfo{author}       = $getiteminfo->{'author'};
375         $getWaitingReserveInfo{reservedate}  = format_date( $num_res->{'reservedate'} );
376         $getWaitingReserveInfo{waitingat}    = GetBranchName( $num_res->{'branchcode'} );
377         $getWaitingReserveInfo{waitinghere}  = 1 if $num_res->{'branchcode'} eq $branch;
378         }
379         #         check transfers with the itemnumber foud in th reservation loop
380         if ($transfertwhen) {
381             $getreserv{color}      = 'transfered';
382             $getreserv{transfered} = 1;
383             $getreserv{datesent}   = format_date($transfertwhen);
384             $getreserv{frombranch} = GetBranchName($transfertfrom);
385         } elsif ($getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'}) {
386             $getreserv{nottransfered}   = 1;
387             $getreserv{nottransferedby} = GetBranchName( $getiteminfo->{'holdingbranch'} );
388         }
389
390 #         if we don't have a reserv on item, we put the biblio infos and the waiting position
391         if ( $getiteminfo->{'title'} eq '' ) {
392             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
393             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );  # fixme - we should have item-level reserves here ?
394             $getreserv{color}           = 'inwait';
395             $getreserv{title}           = $getbibinfo->{'title'};
396             $getreserv{nottransfered}   = 0;
397             $getreserv{itemtype}        = $getbibtype->{'description'};
398             $getreserv{author}          = $getbibinfo->{'author'};
399             $getreserv{biblionumber}    = $num_res->{'biblionumber'};
400         }
401         $getreserv{waitingposition} = $num_res->{'priority'};
402         push( @reservloop, \%getreserv );
403
404 #         if we have a reserve waiting, initiate waitingreserveloop
405         if ($getreserv{waiting} eq 1) {
406         push (@WaitingReserveLoop, \%getWaitingReserveInfo)
407         }
408       
409     }
410
411     # return result to the template
412     $template->param( 
413         countreserv => scalar @reservloop,
414         reservloop  => \@reservloop ,
415         WaitingReserveLoop  => \@WaitingReserveLoop,
416     );
417     $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
418 }
419
420 # make the issued books table.
421 my $todaysissues = '';
422 my $previssues   = '';
423 my @todaysissues;
424 my @previousissues;
425 ## ADDED BY JF: new itemtype issuingrules counter stuff
426 my $issued_itemtypes_count;
427 my @issued_itemtypes_count_loop;
428 my $totalprice = 0;
429
430 if ($borrower) {
431 # get each issue of the borrower & separate them in todayissues & previous issues
432     my ($issueslist) = GetPendingIssues($borrower->{'borrowernumber'});
433     # split in 2 arrays for today & previous
434     foreach my $it ( @$issueslist ) {
435         my $itemtypeinfo = getitemtypeinfo( (C4::Context->preference('item-level_itypes')) ? $it->{'itype'} : $it->{'itemtype'} );
436         # set itemtype per item-level_itype syspref - FIXME this is an ugly hack
437         $it->{'itemtype'} = ( C4::Context->preference( 'item-level_itypes' ) ) ? $it->{'itype'} : $it->{'itemtype'};
438
439         ($it->{'charge'}, $it->{'itemtype_charge'}) = GetIssuingCharges(
440             $it->{'itemnumber'}, $borrower->{'borrowernumber'}
441         );
442         $it->{'charge'} = sprintf("%.2f", $it->{'charge'});
443         my ($can_renew, $can_renew_error) = CanBookBeRenewed( 
444             $borrower->{'borrowernumber'},$it->{'itemnumber'}
445         );
446         $it->{"renew_error_${can_renew_error}"} = 1 if defined $can_renew_error;
447         my ( $restype, $reserves ) = CheckReserves( $it->{'itemnumber'} );
448                 $it->{'can_renew'} = $can_renew;
449                 $it->{'can_confirm'} = !$can_renew && !$restype;
450                 $it->{'renew_error'} = $restype;
451             $it->{'checkoutdate'} = C4::Dates->new($it->{'issuedate'},'iso')->output('syspref');
452
453             $totalprice += $it->{'replacementprice'};
454                 $it->{'itemtype'} = $itemtypeinfo->{'description'};
455                 $it->{'itemtype_image'} = $itemtypeinfo->{'imageurl'};
456         $it->{'dd'} = format_date($it->{'date_due'});
457         $it->{'issuedate'} = format_date($it->{'issuedate'});
458         $it->{'od'} = ( $it->{'date_due'} lt $todaysdate ) ? 1 : 0 ;
459         ($it->{'author'} eq '') and $it->{'author'} = ' ';
460         $it->{'renew_failed'} = $renew_failed{$it->{'itemnumber'}};
461         # ADDED BY JF: NEW ITEMTYPE COUNT DISPLAY
462         $issued_itemtypes_count->{ $it->{'itemtype'} }++;
463
464         if ( $todaysdate eq $it->{'issuedate'} or $todaysdate eq $it->{'lastreneweddate'} ) {
465             push @todaysissues, $it;
466         } else {
467             push @previousissues, $it;
468         }
469     }
470     if ( C4::Context->preference( "todaysIssuesDefaultSortOrder" ) eq 'asc' ) {
471         @todaysissues   = sort { $a->{'timestamp'} cmp $b->{'timestamp'} } @todaysissues;
472     }
473     else {
474         @todaysissues   = sort { $b->{'timestamp'} cmp $a->{'timestamp'} } @todaysissues;
475     }
476     if ( C4::Context->preference( "previousIssuesDefaultSortOrder" ) eq 'asc' ){
477         @previousissues = sort { $a->{'date_due'} cmp $b->{'date_due'} } @previousissues;
478     }
479     else {
480         @previousissues = sort { $b->{'date_due'} cmp $a->{'date_due'} } @previousissues;
481     }
482 }
483
484 #### ADDED BY JF FOR COUNTS BY ITEMTYPE RULES
485 # FIXME: This should utilize all the issuingrules options rather than just the defaults
486 # and it should be moved to a module
487 my $dbh = C4::Context->dbh;
488
489 # how many of each is allowed?
490 my $issueqty_sth = $dbh->prepare( "
491 SELECT itemtypes.description AS description,issuingrules.itemtype,maxissueqty
492 FROM issuingrules
493   LEFT JOIN itemtypes ON (itemtypes.itemtype=issuingrules.itemtype)
494   WHERE categorycode=?
495 " );
496 $issueqty_sth->execute("*");    # This is a literal asterisk, not a wildcard.
497
498 while ( my $data = $issueqty_sth->fetchrow_hashref() ) {
499
500     # subtract how many of each this borrower has
501     $data->{'count'} = $issued_itemtypes_count->{ $data->{'description'} };  
502     $data->{'left'}  =
503       ( $data->{'maxissueqty'} -
504           $issued_itemtypes_count->{ $data->{'description'} } );
505
506     # can't have a negative number of remaining
507     if ( $data->{'left'} < 0 ) { $data->{'left'} = "0" }
508     $data->{'flag'} = 1 unless ( $data->{'maxissueqty'} > $data->{'count'} );
509     unless ( ( $data->{'maxissueqty'} < 1 )
510         || ( $data->{'itemtype'} eq "*" )
511         || ( $data->{'itemtype'} eq "CIRC" ) )
512     {
513         push @issued_itemtypes_count_loop, $data;
514     }
515 }
516
517 #### / JF
518
519 my @values;
520 my %labels;
521 my $CGIselectborrower;
522 if ($borrowerslist) {
523     foreach (
524         sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
525         } @$borrowerslist
526       )
527     {
528         push @values, $_->{'borrowernumber'};
529         $labels{ $_->{'borrowernumber'} } =
530 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'}) ...  $_->{'address'} ";
531     }
532     $CGIselectborrower = CGI::scrolling_list(
533         -name     => 'borrowernumber',
534         -class    => 'focus',
535         -id       => 'borrowernumber',
536         -values   => \@values,
537         -labels   => \%labels,
538         -onclick  => "window.location = '/cgi-bin/koha/circ/circulation.pl?borrowernumber=' + this.value;",
539         -size     => 7,
540         -tabindex => '',
541         -multiple => 0
542     );
543 }
544
545 #title
546 my $flags = $borrower->{'flags'};
547 foreach my $flag ( sort keys %$flags ) {
548     $template->param( flagged=> 1);
549     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
550     if ( $flags->{$flag}->{'noissues'} ) {
551         $template->param(
552             flagged  => 1,
553             noissues => 'true',
554         );
555         if ( $flag eq 'GNA' ) {
556             $template->param( gna => 'true' );
557         }
558         elsif ( $flag eq 'LOST' ) {
559             $template->param( lost => 'true' );
560         }
561         elsif ( $flag eq 'DBARRED' ) {
562             $template->param( dbarred => 'true' );
563         }
564         elsif ( $flag eq 'CHARGES' ) {
565             $template->param(
566                 charges    => 'true',
567                 chargesmsg => $flags->{'CHARGES'}->{'message'},
568                 chargesamount => $flags->{'CHARGES'}->{'amount'},
569                 charges_is_blocker => 1
570             );
571         }
572         elsif ( $flag eq 'CREDITS' ) {
573             $template->param(
574                 credits    => 'true',
575                 creditsmsg => $flags->{'CREDITS'}->{'message'}
576             );
577         }
578     }
579     else {
580         if ( $flag eq 'CHARGES' ) {
581             $template->param(
582                 charges    => 'true',
583                 flagged    => 1,
584                 chargesmsg => $flags->{'CHARGES'}->{'message'},
585                 chargesamount => $flags->{'CHARGES'}->{'amount'},
586             );
587         }
588         elsif ( $flag eq 'CREDITS' ) {
589             $template->param(
590                 credits    => 'true',
591                 creditsmsg => $flags->{'CREDITS'}->{'message'}
592             );
593         }
594         elsif ( $flag eq 'ODUES' ) {
595             $template->param(
596                 odues    => 'true',
597                 flagged  => 1,
598                 oduesmsg => $flags->{'ODUES'}->{'message'}
599             );
600
601             my $items = $flags->{$flag}->{'itemlist'};
602 # useless ???
603 #             {
604 #                 my @itemswaiting;
605 #                 foreach my $item (@$items) {
606 #                     my ($iteminformation) =
607 #                         getiteminformation( $item->{'itemnumber'}, 0 );
608 #                     push @itemswaiting, $iteminformation;
609 #                 }
610 #             }
611             if ( ! $query->param('module') or $query->param('module') ne 'returns' ) {
612                 $template->param( nonreturns => 'true' );
613             }
614         }
615         elsif ( $flag eq 'NOTES' ) {
616             $template->param(
617                 notes    => 'true',
618                 flagged  => 1,
619                 notesmsg => $flags->{'NOTES'}->{'message'}
620             );
621         }
622     }
623 }
624
625 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
626 $amountold =~ s/^.*\$//;    # remove upto the $, if any
627
628 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
629
630 if ( $borrower->{'category_type'} eq 'C') {
631     my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
632     my $cnt = scalar(@$catcodes);
633     $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
634     $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
635 }
636
637 my $CGIorganisations;
638 my $member_of_institution;
639 if ( C4::Context->preference("memberofinstitution") ) {
640     my $organisations = get_institutions();
641     my @orgs;
642     my %org_labels;
643     foreach my $organisation ( keys %$organisations ) {
644         push @orgs, $organisation;
645         $org_labels{$organisation} = $organisations->{$organisation}->{'surname'};
646     }
647     $member_of_institution = 1;
648     $CGIorganisations      = CGI::popup_menu(
649         -id     => 'organisations',
650         -name   => 'organisations',
651         -labels => \%org_labels,
652         -values => \@orgs,
653     );
654 }
655
656 $template->param(
657     issued_itemtypes_count_loop => \@issued_itemtypes_count_loop,
658     findborrower                => $findborrower,
659     borrower                    => $borrower,
660     borrowernumber              => $borrowernumber,
661     branch                      => $branch,
662     branchname                  => GetBranchName($borrower->{'branchcode'}),
663     printer                     => $printer,
664     printername                 => $printer,
665     firstname                   => $borrower->{'firstname'},
666     surname                     => $borrower->{'surname'},
667     dateexpiry        => format_date($newexpiry),
668     expiry            => format_date($borrower->{'dateexpiry'}),
669     categorycode      => $borrower->{'categorycode'},
670     categoryname      => $borrower->{description},
671     address           => $borrower->{'address'},
672     address2          => $borrower->{'address2'},
673     email             => $borrower->{'email'},
674     emailpro          => $borrower->{'emailpro'},
675     borrowernotes     => $borrower->{'borrowernotes'},
676     city              => $borrower->{'city'},
677     zipcode               => $borrower->{'zipcode'},
678     country               => $borrower->{'country'},
679     phone             => $borrower->{'phone'} || $borrower->{'mobile'},
680     cardnumber        => $borrower->{'cardnumber'},
681     amountold         => $amountold,
682     barcode           => $barcode,
683     stickyduedate     => $stickyduedate,
684     duedatespec       => $duedatespec,
685     message           => $message,
686     CGIselectborrower => $CGIselectborrower,
687         totalprice => sprintf("%.2f", $totalprice),
688     totaldue        => sprintf("%.2f", $total),
689     todayissues       => \@todaysissues,
690     previssues        => \@previousissues,
691     inprocess         => $inprocess,
692     memberofinstution => $member_of_institution,
693     CGIorganisations  => $CGIorganisations,
694         is_child          => ($borrower->{'category_type'} eq 'C'),
695     circview => 1,
696 );
697
698 # save stickyduedate to session
699 if ($stickyduedate) {
700     $session->param( 'stickyduedate', $duedatespec );
701 }
702
703 #if ($branchcookie) {
704 #$cookie=[$cookie, $branchcookie, $printercookie];
705 #}
706
707 my ($picture, $dberror) = GetPatronImage($borrower->{'cardnumber'});
708 $template->param( picture => 1 ) if $picture;
709
710
711 $template->param(
712     debt_confirmed            => $debt_confirmed,
713     SpecifyDueDate            => $duedatespec_allow,
714     CircAutocompl             => C4::Context->preference("CircAutocompl"),
715         AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
716     dateformat                => C4::Context->preference("dateformat"),
717     DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar(),
718 );
719 output_html_with_http_headers $query, $cookie, $template->output;