Merge remote-tracking branch 'origin/new/bug_6875'
[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::Reserves;
51 use C4::Branch; # GetBranchName
52 use C4::Overdues qw/CheckBorrowerDebarred/;
53 use C4::Form::MessagingPreferences;
54 use List::MoreUtils qw/uniq/;
55 use C4::Members::Attributes qw(GetBorrowerAttributes);
56
57 #use Smart::Comments;
58 #use Data::Dumper;
59
60 use vars qw($debug);
61
62 BEGIN {
63         $debug = $ENV{DEBUG} || 0;
64 }
65
66 my $dbh = C4::Context->dbh;
67
68 my $input = new CGI;
69 $debug or $debug = $input->param('debug') || 0;
70 my $print = $input->param('print');
71 my $override_limit = $input->param("override_limit") || 0;
72 my @failedrenews = $input->param('failedrenew');
73 my @failedreturns = $input->param('failedreturn');
74 my $error = $input->param('error');
75 my %renew_failed;
76 for my $renew (@failedrenews) { $renew_failed{$renew} = 1; }
77 my %return_failed;
78 for my $failedret (@failedreturns) { $return_failed{$failedret} = 1; }
79
80 my $template_name;
81 my $quickslip = 0;
82
83 my $flagsrequired;
84 if ($print eq "page") {
85     $template_name = "members/moremember-print.tmpl";
86     $flagsrequired = { borrowers => 1 };
87 } elsif ($print eq "slip") {
88     $template_name = "members/moremember-receipt.tmpl";
89     # circ staff who process checkouts but can't edit
90     # patrons still need to be able to print receipts
91     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
92 } elsif ($print eq "qslip") {
93     $template_name = "members/moremember-receipt.tmpl";
94     $quickslip = 1;
95     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
96 } elsif ($print eq "brief") {
97     $template_name = "members/moremember-brief.tmpl";
98     $flagsrequired = { borrowers => 1 };
99 } else {
100     $template_name = "members/moremember.tmpl";
101     $flagsrequired = { borrowers => 1 };
102 }
103
104 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
105     {
106         template_name   => $template_name,
107         query           => $input,
108         type            => "intranet",
109         authnotrequired => 0,
110         flagsrequired   => $flagsrequired,
111         debug           => 1,
112     }
113 );
114 my $borrowernumber = $input->param('borrowernumber');
115
116 #start the page and read in includes
117 my $data           = GetMember( 'borrowernumber' => $borrowernumber );
118 my $reregistration = $input->param('reregistration');
119
120 if ( not defined $data ) {
121     $template->param (unknowuser => 1);
122         output_html_with_http_headers $input, $cookie, $template->output;
123     exit;
124 }
125
126 # re-reregistration function to automatic calcul of date expiry
127 if ( $reregistration eq 'y' ) {
128         $data->{'dateexpiry'} = ExtendMemberSubscriptionTo( $borrowernumber );
129 }
130
131 my $category_type = $data->{'category_type'};
132
133 ### $category_type
134
135 $debug and printf STDERR "dates (enrolled,expiry,birthdate) raw: (%s, %s, %s)\n", map {$data->{$_}} qw(dateenrolled dateexpiry dateofbirth);
136 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
137                 my $userdate = $data->{$_};
138                 unless ($userdate) {
139                         $debug and warn sprintf "Empty \$data{%12s}", $_;
140                         $data->{$_} = '';
141                         next;
142                 }
143                 $userdate = C4::Dates->new($userdate,'iso')->output('syspref');
144                 $data->{$_} = $userdate || '';
145                 $template->param( $_ => $userdate );
146 }
147 $data->{'IS_ADULT'} = ( $data->{'categorycode'} ne 'I' );
148
149 for (qw(gonenoaddress lost borrowernotes)) {
150          $data->{$_} and $template->param(flagged => 1) and last;
151 }
152
153 my $debar = CheckBorrowerDebarred($borrowernumber);
154 if ($debar) {
155     $template->param( 'userdebarred' => 1, 'flagged' => 1 );
156     if ( $debar ne "9999-12-31" ) {
157         $template->param( 'userdebarreddate' => C4::Dates::format_date($debar) );
158         $template->param( 'debarredcomment'  => $data->{debarredcomment} );
159     }
160 }
161
162 $data->{'ethnicity'} = fixEthnicity( $data->{'ethnicity'} );
163 $data->{ "sex_".$data->{'sex'}."_p" } = 1;
164
165 my $catcode;
166 if ( $category_type eq 'C') {
167    my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
168    my $cnt = scalar(@$catcodes);
169
170    $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
171    $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
172 }
173
174
175 if ( $data->{'ethnicity'} || $data->{'ethnotes'} ) {
176     $template->param( printethnicityline => 1 );
177 }
178 if ( $category_type eq 'A' || $category_type eq 'I') {
179     $template->param( isguarantee => 1 );
180
181     # FIXME
182     # It looks like the $i is only being returned to handle walking through
183     # the array, which is probably better done as a foreach loop.
184     #
185     my ( $count, $guarantees ) = GetGuarantees( $data->{'borrowernumber'} );
186     my @guaranteedata;
187     for ( my $i = 0 ; $i < $count ; $i++ ) {
188         push(@guaranteedata,
189             {
190                 borrowernumber => $guarantees->[$i]->{'borrowernumber'},
191                 cardnumber     => $guarantees->[$i]->{'cardnumber'},
192                 name           => $guarantees->[$i]->{'firstname'} . " "
193                                 . $guarantees->[$i]->{'surname'}
194             }
195         );
196     }
197     $template->param( guaranteeloop => \@guaranteedata );
198     ( $template->param( adultborrower => 1 ) ) if ( $category_type eq 'A' || $category_type eq 'I' );
199 }
200 else {
201     if ($data->{'guarantorid'}){
202             my ($guarantor) = GetMember( 'borrowernumber' =>$data->{'guarantorid'});
203                 $template->param(guarantor => 1);
204                 foreach (qw(borrowernumber cardnumber firstname surname)) {        
205                           $template->param("guarantor$_" => $guarantor->{$_});
206         }
207     }
208         if ($category_type eq 'C'){
209                 $template->param('C' => 1);
210         }
211 }
212
213 my %bor;
214 $bor{'borrowernumber'} = $borrowernumber;
215
216 # Converts the branchcode to the branch name
217 my $samebranch;
218 if ( C4::Context->preference("IndependantBranches") ) {
219     my $userenv = C4::Context->userenv;
220     unless ( $userenv->{flags} % 2 == 1 ) {
221         $samebranch = ( $data->{'branchcode'} eq $userenv->{branch} );
222     }
223     $samebranch = 1 if ( $userenv->{flags} % 2 == 1 );
224 }else{
225     $samebranch = 1;
226 }
227 my $branchdetail = GetBranchDetail( $data->{'branchcode'});
228 @{$data}{keys %$branchdetail} = values %$branchdetail; # merge in all branch columns
229
230 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
231 my $lib1 = &GetSortDetails( "Bsort1", $data->{'sort1'} );
232 my $lib2 = &GetSortDetails( "Bsort2", $data->{'sort2'} );
233 $template->param( lib1 => $lib1 ) if ($lib1);
234 $template->param( lib2 => $lib2 ) if ($lib2);
235
236 # Show OPAC privacy preference is system preference is set
237 if ( C4::Context->preference('OPACPrivacy') ) {
238     $template->param( OPACPrivacy => 1);
239     $template->param( "privacy".$data->{'privacy'} => 1);
240 }
241
242 # current issues
243 #
244 my @borrowernumbers = GetMemberRelatives($borrowernumber);
245 my $issue       = GetPendingIssues($borrowernumber);
246 my $relissue    = [];
247 if ( @borrowernumbers ) {
248     $relissue    = GetPendingIssues(@borrowernumbers);
249 }
250 my $issuecount     = @{$issue};
251 my $relissuecount  = @{$relissue};
252 my $roaddetails = &GetRoadTypeDetails( $data->{'streettype'} );
253 my $today       = POSIX::strftime("%Y-%m-%d", localtime);       # iso format
254 my @issuedata;
255 my @borrowers_with_issues;
256 my $overdues_exist = 0;
257 my $totalprice = 0;
258
259 my @issuedata = build_issue_data($issue, $issuecount);
260 my @relissuedata = build_issue_data($relissue, $relissuecount);
261
262 sub build_issue_data {
263     my $issue = shift;
264     my $issuecount = shift;
265
266     my $localissue;
267
268     for ( my $i = 0 ; $i < $issuecount ; $i++ ) {
269         my $datedue = $issue->[$i]{'date_due'};
270         my $issuedate = $issue->[$i]{'issuedate'};
271         $issue->[$i]{'date_due'}  = C4::Dates->new($issue->[$i]{'date_due'}, 'iso')->output('syspref');
272         $issue->[$i]{'issuedate'} = C4::Dates->new($issue->[$i]{'issuedate'},'iso')->output('syspref');
273         my $biblionumber = $issue->[$i]{'biblionumber'};
274         $issue->[$i]{'issuingbranchname'} = GetBranchName($issue->[$i]{'branchcode'});
275         my %row = %{ $issue->[$i] };
276         $totalprice += $issue->[$i]{'replacementprice'};
277         $row{'replacementprice'} = $issue->[$i]{'replacementprice'};
278         # item lost, damaged loops
279         if ($row{'itemlost'}) {
280             my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
281             my $category = GetAuthValCode('items.itemlost',$fw);
282             my $lostdbh = C4::Context->dbh;
283             my $sth = $lostdbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
284             $sth->execute($category, $row{'itemlost'});
285             my $loststat = $sth->fetchrow;
286             if ($loststat) {
287                $row{'itemlost'} = $loststat;
288             }
289         }
290         if ($row{'damaged'}) {
291             my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
292             my $category = GetAuthValCode('items.damaged',$fw);
293             my $damageddbh = C4::Context->dbh;
294             my $sth = $damageddbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
295             $sth->execute($category, $row{'damaged'});
296             my $damagedstat = $sth->fetchrow;
297             if ($damagedstat) {
298                $row{'itemdamaged'} = $damagedstat;
299             }
300         }
301         # end lost, damaged
302         if ( $datedue lt $today ) {
303             $overdues_exist = 1;
304             $row{'red'} = 1;
305         }
306          if ( $issuedate eq $today ) {
307             $row{'today'} = 1; 
308          }
309
310         #find the charge for an item
311         my ( $charge, $itemtype ) =
312           GetIssuingCharges( $issue->[$i]{'itemnumber'}, $issue->[$i]{'borrowernumber'} );
313
314         my $itemtypeinfo = getitemtypeinfo($itemtype);
315         $row{'itemtype_description'} = $itemtypeinfo->{description};
316         $row{'itemtype_image'}       = $itemtypeinfo->{imageurl};
317
318         $row{'charge'} = sprintf( "%.2f", $charge );
319
320         my ( $renewokay,$renewerror ) = CanBookBeRenewed( $issue->[$i]{'borrowernumber'}, $issue->[$i]{'itemnumber'}, $override_limit );
321         $row{'norenew'} = !$renewokay;
322         $row{'can_confirm'} = ( !$renewokay && $renewerror ne 'on_reserve' );
323         $row{"norenew_reason_$renewerror"} = 1 if $renewerror;
324         $row{'renew_failed'}  = $renew_failed{ $issue->[$i]{'itemnumber'} };
325         $row{'return_failed'} = $return_failed{$issue->[$i]{'barcode'}};   
326         push( @$localissue, \%row );
327     }
328     return $localissue;
329 }
330
331
332 ### ###############################################################################
333 # BUILD HTML
334 # show all reserves of this borrower, and the position of the reservation ....
335 if ($borrowernumber) {
336
337     # new op dev
338     # now we show the status of the borrower's reservations
339     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
340     my @reservloop;
341     foreach my $num_res (@borrowerreserv) {
342         my %getreserv;
343         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
344         my $itemtypeinfo = getitemtypeinfo( $getiteminfo->{'itemtype'} );
345         my ( $transfertwhen, $transfertfrom, $transfertto ) =
346             GetTransfers( $num_res->{'itemnumber'} );
347
348         foreach (qw(waiting transfered nottransfered)) {
349             $getreserv{$_} = 0;
350         }
351         $getreserv{reservedate}  = C4::Dates->new($num_res->{'reservedate'},'iso')->output('syspref');
352         foreach (qw(biblionumber title author itemcallnumber )) {
353             $getreserv{$_} = $getiteminfo->{$_};
354         }
355         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
356         $getreserv{itemtype}  = $itemtypeinfo->{'description'};
357
358         #               check if we have a waitin status for reservations
359         if ( $num_res->{'found'} eq 'W' ) {
360             $getreserv{color}   = 'reserved';
361             $getreserv{waiting} = 1;
362         }
363
364         #               check transfers with the itemnumber foud in th reservation loop
365         if ($transfertwhen) {
366             $getreserv{color}      = 'transfered';
367             $getreserv{transfered} = 1;
368             $getreserv{datesent}   = C4::Dates->new($transfertwhen, 'iso')->output('syspref') or die "Cannot get new($transfertwhen, 'iso') from C4::Dates";
369             $getreserv{frombranch} = GetBranchName($transfertfrom);
370         }
371
372         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
373             and not $transfertwhen )
374         {
375             $getreserv{nottransfered}   = 1;
376             $getreserv{nottransferedby} =
377                 GetBranchName( $getiteminfo->{'holdingbranch'} );
378         }
379
380 #               if we don't have a reserv on item, we put the biblio infos and the waiting position
381         if ( $getiteminfo->{'title'} eq '' ) {
382             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
383             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );
384             $getreserv{color}           = 'inwait';
385             $getreserv{title}           = $getbibinfo->{'title'};
386             $getreserv{nottransfered}   = 0;
387             $getreserv{itemtype}        = $getbibtype->{'description'};
388             $getreserv{author}          = $getbibinfo->{'author'};
389             $getreserv{biblionumber}  = $num_res->{'biblionumber'};     
390         }
391         $getreserv{waitingposition} = $num_res->{'priority'};
392
393         push( @reservloop, \%getreserv );
394     }
395
396     # return result to the template
397     $template->param( reservloop => \@reservloop,
398         countreserv => scalar @reservloop,
399          );
400 }
401
402 # current alert subscriptions
403 my $alerts = getalert($borrowernumber);
404 foreach (@$alerts) {
405     $_->{ $_->{type} } = 1;
406     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
407 }
408
409 my $candeleteuser;
410 my $userenv = C4::Context->userenv;
411 if($userenv->{flags} % 2 == 1){
412     $candeleteuser = 1;
413 }elsif ( C4::Context->preference("IndependantBranches") ) {
414     $candeleteuser = ( $data->{'branchcode'} eq $userenv->{branch} );
415 }else{
416     if( C4::Auth::getuserflags( $userenv->{flags},$userenv->{number})->{borrowers} ) {
417         $candeleteuser = 1;
418     }else{
419         $candeleteuser = 0;
420     }
421 }
422
423 # check to see if patron's image exists in the database
424 # basically this gives us a template var to condition the display of
425 # patronimage related interface on
426 my ($picture, $dberror) = GetPatronImage($data->{'cardnumber'});
427 $template->param( picture => 1 ) if $picture;
428
429 my $branch=C4::Context->userenv->{'branch'};
430
431 $template->param(%$data);
432
433 if (C4::Context->preference('ExtendedPatronAttributes')) {
434     my $attributes = GetBorrowerAttributes($borrowernumber);
435     $template->param(
436         ExtendedPatronAttributes => 1,
437         extendedattributes => $attributes
438     );
439     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
440     if (scalar(@types) == 0) {
441         $template->param(no_patron_attribute_types => 1);
442     }
443 }
444
445 if (C4::Context->preference('EnhancedMessagingPreferences')) {
446     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
447     $template->param(messaging_form_inactive => 1);
448     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
449     $template->param(SMSnumber     => defined $data->{'smsalertnumber'} ? $data->{'smsalertnumber'} : $data->{'mobile'});
450 }
451
452 # in template <TMPL_IF name="I"> => instutitional (A for Adult, C for children) 
453 $template->param( $data->{'categorycode'} => 1 ); 
454 $template->param(
455     detailview => 1,
456     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
457     DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
458     CANDELETEUSER    => $candeleteuser,
459     roaddetails     => $roaddetails,
460     borrowernumber  => $borrowernumber,
461     othernames      => $data->{'othernames'},
462     categoryname    => $data->{'description'},
463     reregistration  => $reregistration,
464     branch          => $branch,
465     todaysdate      => C4::Dates->today(),
466     totalprice      => sprintf("%.2f", $totalprice),
467     totaldue        => sprintf("%.2f", $total),
468     totaldue_raw    => $total,
469     issueloop       => @issuedata,
470     relissueloop    => @relissuedata,
471         issuecount      => $issuecount,
472     relissuecount   => $relissuecount,
473     overdues_exist  => $overdues_exist,
474     error           => $error,
475     $error          => 1,
476     StaffMember     => ($category_type eq 'S'),
477     is_child        => ($category_type eq 'C'),
478 #   reserveloop     => \@reservedata,
479     dateformat      => C4::Context->preference("dateformat"),
480     "dateformat_" . (C4::Context->preference("dateformat") || '') => 1,
481     samebranch     => $samebranch,
482     quickslip             => $quickslip,
483         activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
484 );
485
486 output_html_with_http_headers $input, $cookie, $template->output;