Bug 9367: Code optimization: CheckReserves is too often called
[koha.git] / members / moremember.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21
22 =head1 moremember.pl
23
24  script to do a borrower enquiry/bring up borrower details etc
25  Displays all the details about a borrower
26  written 20/12/99 by chris@katipo.co.nz
27  last modified 21/1/2000 by chris@katipo.co.nz
28  modified 31/1/2001 by chris@katipo.co.nz
29    to not allow items on request to be renewed
30
31  needs html removed and to use the C4::Output more, but its tricky
32
33 =cut
34
35 use strict;
36 #use warnings; FIXME - Bug 2505
37 use CGI;
38 use C4::Context;
39 use C4::Auth;
40 use C4::Output;
41 use C4::Members;
42 use C4::Members::Attributes;
43 use C4::Members::AttributeTypes;
44 use C4::Dates;
45 use C4::Reserves;
46 use C4::Circulation;
47 use C4::Koha;
48 use C4::Letters;
49 use C4::Biblio;
50 use C4::Branch; # GetBranchName
51 use C4::Overdues qw/CheckBorrowerDebarred/;
52 use C4::Form::MessagingPreferences;
53 use List::MoreUtils qw/uniq/;
54 use C4::Members::Attributes qw(GetBorrowerAttributes);
55
56 #use Smart::Comments;
57 #use Data::Dumper;
58 use DateTime;
59 use Koha::DateUtils;
60
61 use vars qw($debug);
62
63 BEGIN {
64         $debug = $ENV{DEBUG} || 0;
65 }
66
67 my $dbh = C4::Context->dbh;
68
69 my $input = CGI->new;
70 $debug or $debug = $input->param('debug') || 0;
71 my $print = $input->param('print');
72 my $override_limit = $input->param("override_limit") || 0;
73 my @failedrenews = $input->param('failedrenew');
74 my @failedreturns = $input->param('failedreturn');
75 my $error = $input->param('error');
76 my %renew_failed;
77 for my $renew (@failedrenews) { $renew_failed{$renew} = 1; }
78 my %return_failed;
79 for my $failedret (@failedreturns) { $return_failed{$failedret} = 1; }
80
81 my $template_name;
82 my $quickslip = 0;
83
84 my $flagsrequired;
85 if ($print eq "page") {
86     $template_name = "members/moremember-print.tmpl";
87     # circ staff who process checkouts but can't edit
88     # patrons still need to be able to access print view
89     $flagsrequired = { circulate => "circulate_remaining_permissions" };
90 } elsif ($print eq "slip") {
91     $template_name = "members/moremember-receipt.tmpl";
92     # circ staff who process checkouts but can't edit
93     # patrons still need to be able to print receipts
94     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
95 } elsif ($print eq "qslip") {
96     $template_name = "members/moremember-receipt.tmpl";
97     $quickslip = 1;
98     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
99 } elsif ($print eq "brief") {
100     $template_name = "members/moremember-brief.tmpl";
101     $flagsrequired = { borrowers => 1 };
102 } else {
103     $template_name = "members/moremember.tmpl";
104     $flagsrequired = { borrowers => 1 };
105 }
106
107 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
108     {
109         template_name   => $template_name,
110         query           => $input,
111         type            => "intranet",
112         authnotrequired => 0,
113         flagsrequired   => $flagsrequired,
114         debug           => 1,
115     }
116 );
117 my $borrowernumber = $input->param('borrowernumber');
118
119 #start the page and read in includes
120 my $data           = GetMember( 'borrowernumber' => $borrowernumber );
121 my $reregistration = $input->param('reregistration');
122
123 if ( not defined $data ) {
124     $template->param (unknowuser => 1);
125         output_html_with_http_headers $input, $cookie, $template->output;
126     exit;
127 }
128
129 # re-reregistration function to automatic calcul of date expiry
130 if ( $reregistration eq 'y' ) {
131         $data->{'dateexpiry'} = ExtendMemberSubscriptionTo( $borrowernumber );
132 }
133
134 my $category_type = $data->{'category_type'};
135
136 ### $category_type
137
138 $debug and printf STDERR "dates (enrolled,expiry,birthdate) raw: (%s, %s, %s)\n", map {$data->{$_}} qw(dateenrolled dateexpiry dateofbirth);
139 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
140                 my $userdate = $data->{$_};
141                 unless ($userdate) {
142                         $debug and warn sprintf "Empty \$data{%12s}", $_;
143                         $data->{$_} = '';
144                         next;
145                 }
146                 $userdate = C4::Dates->new($userdate,'iso')->output('syspref');
147                 $data->{$_} = $userdate || '';
148                 $template->param( $_ => $userdate );
149 }
150 $data->{'IS_ADULT'} = ( $data->{'categorycode'} ne 'I' );
151
152 for (qw(gonenoaddress lost borrowernotes)) {
153          $data->{$_} and $template->param(flagged => 1) and last;
154 }
155
156 my $debar = CheckBorrowerDebarred($borrowernumber);
157 if ($debar) {
158     $template->param( 'userdebarred' => 1, 'flagged' => 1 );
159     if ( $debar ne "9999-12-31" ) {
160         $template->param( 'userdebarreddate' => C4::Dates::format_date($debar) );
161         $template->param( 'debarredcomment'  => $data->{debarredcomment} );
162     }
163 }
164
165 $data->{'ethnicity'} = fixEthnicity( $data->{'ethnicity'} );
166 $data->{ "sex_".$data->{'sex'}."_p" } = 1;
167
168 my $catcode;
169 if ( $category_type eq 'C') {
170    my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
171    my $cnt = scalar(@$catcodes);
172
173    $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
174    $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
175 }
176
177
178 if ( $data->{'ethnicity'} || $data->{'ethnotes'} ) {
179     $template->param( printethnicityline => 1 );
180 }
181 if ( $category_type eq 'A' || $category_type eq 'I') {
182     $template->param( isguarantee => 1 );
183
184     # FIXME
185     # It looks like the $i is only being returned to handle walking through
186     # the array, which is probably better done as a foreach loop.
187     #
188     my ( $count, $guarantees ) = GetGuarantees( $data->{'borrowernumber'} );
189     my @guaranteedata;
190     for ( my $i = 0 ; $i < $count ; $i++ ) {
191         push(@guaranteedata,
192             {
193                 borrowernumber => $guarantees->[$i]->{'borrowernumber'},
194                 cardnumber     => $guarantees->[$i]->{'cardnumber'},
195                 name           => $guarantees->[$i]->{'firstname'} . " "
196                                 . $guarantees->[$i]->{'surname'}
197             }
198         );
199     }
200     $template->param( guaranteeloop => \@guaranteedata );
201     ( $template->param( adultborrower => 1 ) ) if ( $category_type eq 'A' || $category_type eq 'I' );
202 }
203 else {
204     if ($data->{'guarantorid'}){
205             my ($guarantor) = GetMember( 'borrowernumber' =>$data->{'guarantorid'});
206                 $template->param(guarantor => 1);
207                 foreach (qw(borrowernumber cardnumber firstname surname)) {        
208                           $template->param("guarantor$_" => $guarantor->{$_});
209         }
210     }
211         if ($category_type eq 'C'){
212                 $template->param('C' => 1);
213         }
214 }
215
216 my %bor;
217 $bor{'borrowernumber'} = $borrowernumber;
218
219 # Converts the branchcode to the branch name
220 my $samebranch;
221 if ( C4::Context->preference("IndependantBranches") ) {
222     my $userenv = C4::Context->userenv;
223     unless ( $userenv->{flags} % 2 == 1 ) {
224         $samebranch = ( $data->{'branchcode'} eq $userenv->{branch} );
225     }
226     $samebranch = 1 if ( $userenv->{flags} % 2 == 1 );
227 }else{
228     $samebranch = 1;
229 }
230 my $branchdetail = GetBranchDetail( $data->{'branchcode'});
231 @{$data}{keys %$branchdetail} = values %$branchdetail; # merge in all branch columns
232
233 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
234 my $lib1 = &GetSortDetails( "Bsort1", $data->{'sort1'} );
235 my $lib2 = &GetSortDetails( "Bsort2", $data->{'sort2'} );
236 $template->param( lib1 => $lib1 ) if ($lib1);
237 $template->param( lib2 => $lib2 ) if ($lib2);
238
239 # Show OPAC privacy preference is system preference is set
240 if ( C4::Context->preference('OPACPrivacy') ) {
241     $template->param( OPACPrivacy => 1);
242     $template->param( "privacy".$data->{'privacy'} => 1);
243 }
244
245 # current issues
246 #
247 my @borrowernumbers = GetMemberRelatives($borrowernumber);
248 my $issue       = GetPendingIssues($borrowernumber);
249 my $relissue    = [];
250 if ( @borrowernumbers ) {
251     $relissue    = GetPendingIssues(@borrowernumbers);
252 }
253 my $roaddetails = &GetRoadTypeDetails( $data->{'streettype'} );
254 my $today       = DateTime->now( time_zone => C4::Context->tz);
255 $today->truncate(to => 'day');
256 my @borrowers_with_issues;
257 my $overdues_exist = 0;
258 my $totalprice = 0;
259
260 my @issuedata = build_issue_data($issue);
261 my @relissuedata = build_issue_data($relissue);
262
263
264 ### ###############################################################################
265 # BUILD HTML
266 # show all reserves of this borrower, and the position of the reservation ....
267 if ($borrowernumber) {
268
269     # new op dev
270     # now we show the status of the borrower's reservations
271     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
272     my @reservloop;
273     foreach my $num_res (@borrowerreserv) {
274         my %getreserv;
275         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
276         my $itemtypeinfo = getitemtypeinfo( $getiteminfo->{'itemtype'} );
277         my ( $transfertwhen, $transfertfrom, $transfertto ) =
278             GetTransfers( $num_res->{'itemnumber'} );
279
280         foreach (qw(waiting transfered nottransfered)) {
281             $getreserv{$_} = 0;
282         }
283         $getreserv{reservedate}  = C4::Dates->new($num_res->{'reservedate'},'iso')->output('syspref');
284         foreach (qw(biblionumber title author itemcallnumber )) {
285             $getreserv{$_} = $getiteminfo->{$_};
286         }
287         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
288         $getreserv{itemtype}  = $itemtypeinfo->{'description'};
289
290         #               check if we have a waitin status for reservations
291         if ( $num_res->{'found'} eq 'W' ) {
292             $getreserv{color}   = 'reserved';
293             $getreserv{waiting} = 1;
294         }
295
296         #               check transfers with the itemnumber foud in th reservation loop
297         if ($transfertwhen) {
298             $getreserv{color}      = 'transfered';
299             $getreserv{transfered} = 1;
300             $getreserv{datesent}   = C4::Dates->new($transfertwhen, 'iso')->output('syspref') or die "Cannot get new($transfertwhen, 'iso') from C4::Dates";
301             $getreserv{frombranch} = GetBranchName($transfertfrom);
302         }
303
304         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
305             and not $transfertwhen )
306         {
307             $getreserv{nottransfered}   = 1;
308             $getreserv{nottransferedby} =
309                 GetBranchName( $getiteminfo->{'holdingbranch'} );
310         }
311
312 #               if we don't have a reserv on item, we put the biblio infos and the waiting position
313         if ( $getiteminfo->{'title'} eq '' ) {
314             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
315             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );
316             $getreserv{color}           = 'inwait';
317             $getreserv{title}           = $getbibinfo->{'title'};
318             $getreserv{nottransfered}   = 0;
319             $getreserv{itemtype}        = $getbibtype->{'description'};
320             $getreserv{author}          = $getbibinfo->{'author'};
321             $getreserv{biblionumber}  = $num_res->{'biblionumber'};     
322         }
323         $getreserv{waitingposition} = $num_res->{'priority'};
324         $getreserv{suspend} = $num_res->{'suspend'};
325         $getreserv{suspend_until} = $num_res->{'suspend_until'};
326
327         push( @reservloop, \%getreserv );
328     }
329
330     # return result to the template
331     $template->param( reservloop => \@reservloop,
332         countreserv => scalar @reservloop,
333          );
334 }
335
336 # current alert subscriptions
337 my $alerts = getalert($borrowernumber);
338 foreach (@$alerts) {
339     $_->{ $_->{type} } = 1;
340     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
341 }
342
343 my $candeleteuser;
344 my $userenv = C4::Context->userenv;
345 if($userenv->{flags} % 2 == 1){
346     $candeleteuser = 1;
347 }elsif ( C4::Context->preference("IndependantBranches") ) {
348     $candeleteuser = ( $data->{'branchcode'} eq $userenv->{branch} );
349 }else{
350     if( C4::Auth::getuserflags( $userenv->{flags},$userenv->{number})->{borrowers} ) {
351         $candeleteuser = 1;
352     }else{
353         $candeleteuser = 0;
354     }
355 }
356
357 # check to see if patron's image exists in the database
358 # basically this gives us a template var to condition the display of
359 # patronimage related interface on
360 my ($picture, $dberror) = GetPatronImage($data->{'cardnumber'});
361 $template->param( picture => 1 ) if $picture;
362
363 my $branch=C4::Context->userenv->{'branch'};
364
365 $template->param(%$data);
366
367 if (C4::Context->preference('ExtendedPatronAttributes')) {
368     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
369     my @classes = uniq( map {$_->{class}} @$attributes );
370     @classes = sort @classes;
371
372     my @attributes_loop;
373     for my $class (@classes) {
374         my @items;
375         for my $attr (@$attributes) {
376             push @items, $attr if $attr->{class} eq $class
377         }
378         my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
379         push @attributes_loop, {
380             class => $class,
381             items => \@items,
382             lib   => $lib,
383         };
384     }
385
386     $template->param(
387         ExtendedPatronAttributes => 1,
388         attributes_loop => \@attributes_loop
389     );
390
391     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
392     if (scalar(@types) == 0) {
393         $template->param(no_patron_attribute_types => 1);
394     }
395 }
396
397 if (C4::Context->preference('EnhancedMessagingPreferences')) {
398     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
399     $template->param(messaging_form_inactive => 1);
400     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
401     $template->param(SMSnumber     => defined $data->{'smsalertnumber'} ? $data->{'smsalertnumber'} : $data->{'mobile'});
402     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
403 }
404
405 # in template <TMPL_IF name="I"> => instutitional (A for Adult, C for children) 
406 $template->param( $data->{'categorycode'} => 1 ); 
407 $template->param(
408     detailview => 1,
409     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
410     CANDELETEUSER    => $candeleteuser,
411     roaddetails     => $roaddetails,
412     borrowernumber  => $borrowernumber,
413     othernames      => $data->{'othernames'},
414     categoryname    => $data->{'description'},
415     reregistration  => $reregistration,
416     branch          => $branch,
417     todaysdate      => C4::Dates->today(),
418     totalprice      => sprintf("%.2f", $totalprice),
419     totaldue        => sprintf("%.2f", $total),
420     totaldue_raw    => $total,
421     issueloop       => @issuedata,
422     relissueloop    => @relissuedata,
423     overdues_exist  => $overdues_exist,
424     error           => $error,
425     StaffMember     => ($category_type eq 'S'),
426     is_child        => ($category_type eq 'C'),
427 #   reserveloop     => \@reservedata,
428     samebranch     => $samebranch,
429     quickslip             => $quickslip,
430     activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
431     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
432     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
433 );
434 $template->param( $error => 1 ) if $error;
435
436 output_html_with_http_headers $input, $cookie, $template->output;
437
438 sub build_issue_data {
439     my $issues = shift;
440
441     my $localissue;
442
443     foreach my $issue ( @{$issues} ) {
444
445         # Getting borrower details
446         my $memberdetails = GetMemberDetails( $issue->{borrowernumber} );
447         $issue->{borrowername} =
448           $memberdetails->{firstname} . ' ' . $memberdetails->{surname};
449         $issue->{cardnumber} = $memberdetails->{cardnumber};
450         my $issuedate;
451         if ($issue->{issuedate} ) {
452            $issuedate = $issue->{issuedate}->clone();
453         }
454
455         $issue->{date_due}  = output_pref( $issue->{date_due} );
456         $issue->{issuedate} = output_pref( $issue->{issuedate} ) if defined $issue->{issuedate};
457         my $biblionumber = $issue->{biblionumber};
458         $issue->{issuingbranchname} = GetBranchName($issue->{branchcode});
459         my %row          = %{$issue};
460         $totalprice += $issue->{replacementprice};
461
462         # item lost, damaged loops
463         if ( $row{'itemlost'} ) {
464             my $fw       = GetFrameworkCode( $issue->{biblionumber} );
465             my $category = GetAuthValCode( 'items.itemlost', $fw );
466             my $lostdbh  = C4::Context->dbh;
467             my $sth      = $lostdbh->prepare(
468 "select lib from authorised_values where category=? and authorised_value =? "
469             );
470             $sth->execute( $category, $row{'itemlost'} );
471             my $loststat = $sth->fetchrow;
472             if ($loststat) {
473                 $row{'itemlost'} = $loststat;
474             }
475         }
476         if ( $row{'damaged'} ) {
477             my $fw         = GetFrameworkCode( $issue->{biblionumber} );
478             my $category   = GetAuthValCode( 'items.damaged', $fw );
479             my $damageddbh = C4::Context->dbh;
480             my $sth        = $damageddbh->prepare(
481 "select lib from authorised_values where category=? and authorised_value =? "
482             );
483             $sth->execute( $category, $row{'damaged'} );
484             my $damagedstat = $sth->fetchrow;
485             if ($damagedstat) {
486                 $row{'itemdamaged'} = $damagedstat;
487             }
488         }
489
490         # end lost, damaged
491         if ( $issue->{overdue} ) {
492             $overdues_exist = 1;
493             $row{red} = 1;
494         }
495         if ($issuedate) {
496             $issuedate->truncate( to => 'day' );
497             if ( DateTime->compare( $issuedate, $today ) == 0 ) {
498                 $row{today} = 1;
499             }
500         }
501
502         #find the charge for an item
503         my ( $charge, $itemtype ) =
504           GetIssuingCharges( $issue->{itemnumber}, $borrowernumber );
505
506         my $itemtypeinfo = getitemtypeinfo($itemtype);
507         $row{'itemtype_description'} = $itemtypeinfo->{description};
508         $row{'itemtype_image'}       = $itemtypeinfo->{imageurl};
509
510         $row{'charge'} = sprintf( "%.2f", $charge );
511
512         my ( $renewokay, $renewerror ) =
513           CanBookBeRenewed( $borrowernumber, $issue->{itemnumber},
514             $override_limit );
515         $row{'norenew'} = !$renewokay;
516         $row{'can_confirm'} = ( !$renewokay && $renewerror ne 'on_reserve' );
517         $row{"norenew_reason_$renewerror"} = 1 if $renewerror;
518         $row{renew_failed}  = $renew_failed{ $issue->{itemnumber} };
519         $row{return_failed} = $return_failed{ $issue->{barcode} };
520         push( @{$localissue}, \%row );
521     }
522     return $localissue;
523 }