Merge remote-tracking branch 'kc/new/bug_6755' into kcmaster
[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::Form::MessagingPreferences;
53 use C4::NewsChannels; #get slip news
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 # in template <TMPL_IF name="I"> => instutitional (A for Adult& C for children) 
136 $template->param( $data->{'categorycode'} => 1 ); 
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(debarred gonenoaddress lost borrowernotes)) {
153          $data->{$_} and $template->param(flagged => 1) and last;
154 }
155
156 $data->{'ethnicity'} = fixEthnicity( $data->{'ethnicity'} );
157 $data->{ "sex_".$data->{'sex'}."_p" } = 1;
158
159 my $catcode;
160 if ( $category_type eq 'C') {
161    my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
162    my $cnt = scalar(@$catcodes);
163
164    $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
165    $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
166 }
167
168
169 if ( $data->{'ethnicity'} || $data->{'ethnotes'} ) {
170     $template->param( printethnicityline => 1 );
171 }
172 if ( $category_type eq 'A' || $category_type eq 'I') {
173     $template->param( isguarantee => 1 );
174
175     # FIXME
176     # It looks like the $i is only being returned to handle walking through
177     # the array, which is probably better done as a foreach loop.
178     #
179     my ( $count, $guarantees ) = GetGuarantees( $data->{'borrowernumber'} );
180     my @guaranteedata;
181     for ( my $i = 0 ; $i < $count ; $i++ ) {
182         push(@guaranteedata,
183             {
184                 borrowernumber => $guarantees->[$i]->{'borrowernumber'},
185                 cardnumber     => $guarantees->[$i]->{'cardnumber'},
186                 name           => $guarantees->[$i]->{'firstname'} . " "
187                                 . $guarantees->[$i]->{'surname'}
188             }
189         );
190     }
191     $template->param( guaranteeloop => \@guaranteedata );
192     ( $template->param( adultborrower => 1 ) ) if ( $category_type eq 'A' || $category_type eq 'I' );
193 }
194 else {
195     if ($data->{'guarantorid'}){
196             my ($guarantor) = GetMember( 'borrowernumber' =>$data->{'guarantorid'});
197                 $template->param(guarantor => 1);
198                 foreach (qw(borrowernumber cardnumber firstname surname)) {        
199                           $template->param("guarantor$_" => $guarantor->{$_});
200         }
201     }
202         if ($category_type eq 'C'){
203                 $template->param('C' => 1);
204         }
205 }
206
207 my %bor;
208 $bor{'borrowernumber'} = $borrowernumber;
209
210 # Converts the branchcode to the branch name
211 my $samebranch;
212 if ( C4::Context->preference("IndependantBranches") ) {
213     my $userenv = C4::Context->userenv;
214     unless ( $userenv->{flags} % 2 == 1 ) {
215         $samebranch = ( $data->{'branchcode'} eq $userenv->{branch} );
216     }
217     $samebranch = 1 if ( $userenv->{flags} % 2 == 1 );
218 }else{
219     $samebranch = 1;
220 }
221 my $branchdetail = GetBranchDetail( $data->{'branchcode'});
222 @{$data}{keys %$branchdetail} = values %$branchdetail; # merge in all branch columns
223
224 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
225 my $lib1 = &GetSortDetails( "Bsort1", $data->{'sort1'} );
226 my $lib2 = &GetSortDetails( "Bsort2", $data->{'sort2'} );
227 $template->param( lib1 => $lib1 ) if ($lib1);
228 $template->param( lib2 => $lib2 ) if ($lib2);
229
230 # Show OPAC privacy preference is system preference is set
231 if ( C4::Context->preference('OPACPrivacy') ) {
232     $template->param( OPACPrivacy => 1);
233     $template->param( "privacy".$data->{'privacy'} => 1);
234 }
235
236 # current issues
237 #
238 my @borrowernumbers = GetMemberRelatives($borrowernumber);
239 my $issue       = GetPendingIssues($borrowernumber);
240 my $relissue    = [];
241 if ( @borrowernumbers ) {
242     $relissue    = GetPendingIssues(@borrowernumbers);
243 }
244 my $issuecount     = @{$issue};
245 my $relissuecount  = @{$relissue};
246 my $roaddetails = &GetRoadTypeDetails( $data->{'streettype'} );
247 my $today       = POSIX::strftime("%Y-%m-%d", localtime);       # iso format
248 my @issuedata;
249 my @borrowers_with_issues;
250 my $overdues_exist = 0;
251 my $totalprice = 0;
252
253 my @issuedata = build_issue_data($issue, $issuecount);
254 my @relissuedata = build_issue_data($relissue, $relissuecount);
255
256 sub build_issue_data {
257     my $issue = shift;
258     my $issuecount = shift;
259
260     my $localissue;
261
262     for ( my $i = 0 ; $i < $issuecount ; $i++ ) {
263         # Getting borrower details
264         my $memberdetails = GetMemberDetails($issue->[$i]{'borrowernumber'});
265         $issue->[$i]{'borrowername'} = $memberdetails->{'firstname'} . " " . $memberdetails->{'surname'};
266         $issue->[$i]{'cardnumber'} = $memberdetails->{'cardnumber'};
267         my $datedue = $issue->[$i]{'date_due'};
268         my $issuedate = $issue->[$i]{'issuedate'};
269         $issue->[$i]{'date_due'}  = C4::Dates->new($issue->[$i]{'date_due'}, 'iso')->output('syspref');
270         $issue->[$i]{'issuedate'} = C4::Dates->new($issue->[$i]{'issuedate'},'iso')->output('syspref');
271         my $biblionumber = $issue->[$i]{'biblionumber'};
272         $issue->[$i]{'issuingbranchname'} = GetBranchName($issue->[$i]{'branchcode'});
273         my %row = %{ $issue->[$i] };
274         $totalprice += $issue->[$i]{'replacementprice'};
275         $row{'replacementprice'} = $issue->[$i]{'replacementprice'};
276         # item lost, damaged loops
277         if ($row{'itemlost'}) {
278             my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
279             my $category = GetAuthValCode('items.itemlost',$fw);
280             my $lostdbh = C4::Context->dbh;
281             my $sth = $lostdbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
282             $sth->execute($category, $row{'itemlost'});
283             my $loststat = $sth->fetchrow;
284             if ($loststat) {
285                $row{'itemlost'} = $loststat;
286             }
287         }
288         if ($row{'damaged'}) {
289             my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
290             my $category = GetAuthValCode('items.damaged',$fw);
291             my $damageddbh = C4::Context->dbh;
292             my $sth = $damageddbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
293             $sth->execute($category, $row{'damaged'});
294             my $damagedstat = $sth->fetchrow;
295             if ($damagedstat) {
296                $row{'itemdamaged'} = $damagedstat;
297             }
298         }
299         # end lost, damaged
300         if ( $datedue lt $today ) {
301             $overdues_exist = 1;
302             $row{'red'} = 1;
303         }
304          if ( $issuedate eq $today ) {
305             $row{'today'} = 1; 
306          }
307
308         #find the charge for an item
309         my ( $charge, $itemtype ) =
310           GetIssuingCharges( $issue->[$i]{'itemnumber'}, $borrowernumber );
311
312         my $itemtypeinfo = getitemtypeinfo($itemtype);
313         $row{'itemtype_description'} = $itemtypeinfo->{description};
314         $row{'itemtype_image'}       = $itemtypeinfo->{imageurl};
315
316         $row{'charge'} = sprintf( "%.2f", $charge );
317
318         my ( $renewokay,$renewerror ) = CanBookBeRenewed( $borrowernumber, $issue->[$i]{'itemnumber'}, $override_limit );
319         $row{'norenew'} = !$renewokay;
320         $row{'can_confirm'} = ( !$renewokay && $renewerror ne 'on_reserve' );
321         $row{"norenew_reason_$renewerror"} = 1 if $renewerror;
322         $row{'renew_failed'}  = $renew_failed{ $issue->[$i]{'itemnumber'} };
323         $row{'return_failed'} = $return_failed{$issue->[$i]{'barcode'}};   
324         push( @$localissue, \%row );
325     }
326     return $localissue;
327 }
328
329
330 ### ###############################################################################
331 # BUILD HTML
332 # show all reserves of this borrower, and the position of the reservation ....
333 if ($borrowernumber) {
334
335     # new op dev
336     # now we show the status of the borrower's reservations
337     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
338     my @reservloop;
339     foreach my $num_res (@borrowerreserv) {
340         my %getreserv;
341         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
342         my $itemtypeinfo = getitemtypeinfo( $getiteminfo->{'itemtype'} );
343         my ( $transfertwhen, $transfertfrom, $transfertto ) =
344             GetTransfers( $num_res->{'itemnumber'} );
345
346         foreach (qw(waiting transfered nottransfered)) {
347             $getreserv{$_} = 0;
348         }
349         $getreserv{reservedate}  = C4::Dates->new($num_res->{'reservedate'},'iso')->output('syspref');
350         foreach (qw(biblionumber title author itemcallnumber )) {
351             $getreserv{$_} = $getiteminfo->{$_};
352         }
353         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
354         $getreserv{itemtype}  = $itemtypeinfo->{'description'};
355
356         #               check if we have a waitin status for reservations
357         if ( $num_res->{'found'} eq 'W' ) {
358             $getreserv{color}   = 'reserved';
359             $getreserv{waiting} = 1;
360         }
361
362         #               check transfers with the itemnumber foud in th reservation loop
363         if ($transfertwhen) {
364             $getreserv{color}      = 'transfered';
365             $getreserv{transfered} = 1;
366             $getreserv{datesent}   = C4::Dates->new($transfertwhen, 'iso')->output('syspref') or die "Cannot get new($transfertwhen, 'iso') from C4::Dates";
367             $getreserv{frombranch} = GetBranchName($transfertfrom);
368         }
369
370         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
371             and not $transfertwhen )
372         {
373             $getreserv{nottransfered}   = 1;
374             $getreserv{nottransferedby} =
375                 GetBranchName( $getiteminfo->{'holdingbranch'} );
376         }
377
378 #               if we don't have a reserv on item, we put the biblio infos and the waiting position
379         if ( $getiteminfo->{'title'} eq '' ) {
380             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
381             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );
382             $getreserv{color}           = 'inwait';
383             $getreserv{title}           = $getbibinfo->{'title'};
384             $getreserv{nottransfered}   = 0;
385             $getreserv{itemtype}        = $getbibtype->{'description'};
386             $getreserv{author}          = $getbibinfo->{'author'};
387             $getreserv{biblionumber}  = $num_res->{'biblionumber'};     
388         }
389         $getreserv{waitingposition} = $num_res->{'priority'};
390
391         push( @reservloop, \%getreserv );
392     }
393
394     # return result to the template
395     $template->param( reservloop => \@reservloop,
396         countreserv => scalar @reservloop,
397          );
398 }
399
400 # current alert subscriptions
401 my $alerts = getalert($borrowernumber);
402 foreach (@$alerts) {
403     $_->{ $_->{type} } = 1;
404     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
405 }
406
407 my $candeleteuser;
408 my $userenv = C4::Context->userenv;
409 if($userenv->{flags} % 2 == 1){
410     $candeleteuser = 1;
411 }elsif ( C4::Context->preference("IndependantBranches") ) {
412     $candeleteuser = ( $data->{'branchcode'} eq $userenv->{branch} );
413 }else{
414     if( C4::Auth::getuserflags( $userenv->{flags},$userenv->{number})->{borrowers} ) {
415         $candeleteuser = 1;
416     }else{
417         $candeleteuser = 0;
418     }
419 }
420
421 # check to see if patron's image exists in the database
422 # basically this gives us a template var to condition the display of
423 # patronimage related interface on
424 my ($picture, $dberror) = GetPatronImage($data->{'cardnumber'});
425 $template->param( picture => 1 ) if $picture;
426
427 my $branch=C4::Context->userenv->{'branch'};
428
429 $template->param(%$data);
430
431 if (C4::Context->preference('ExtendedPatronAttributes')) {
432     $template->param(ExtendedPatronAttributes => 1);
433     $template->param(patron_attributes => C4::Members::Attributes::GetBorrowerAttributes($borrowernumber));
434     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
435     if (scalar(@types) == 0) {
436         $template->param(no_patron_attribute_types => 1);
437     }
438 }
439
440 if (C4::Context->preference('EnhancedMessagingPreferences')) {
441     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
442     $template->param(messaging_form_inactive => 1);
443     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
444     $template->param(SMSnumber     => defined $data->{'smsalertnumber'} ? $data->{'smsalertnumber'} : $data->{'mobile'});
445 }
446 my $attributes = GetBorrowerAttributes($borrowernumber);
447
448 $template->param(
449     detailview => 1,
450     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
451     DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
452     CANDELETEUSER    => $candeleteuser,
453     roaddetails     => $roaddetails,
454     borrowernumber  => $borrowernumber,
455     categoryname    => $data->{'description'},
456     reregistration  => $reregistration,
457     branch          => $branch,
458     todaysdate      => C4::Dates->today(),
459     totalprice      => sprintf("%.2f", $totalprice),
460     totaldue        => sprintf("%.2f", $total),
461     totaldue_raw    => $total,
462     issueloop       => @issuedata,
463     relissueloop    => @relissuedata,
464         issuecount      => $issuecount,
465     relissuecount   => $relissuecount,
466     overdues_exist  => $overdues_exist,
467     error           => $error,
468     $error          => 1,
469     StaffMember     => ($category_type eq 'S'),
470     is_child        => ($category_type eq 'C'),
471 #   reserveloop     => \@reservedata,
472     dateformat      => C4::Context->preference("dateformat"),
473     "dateformat_" . (C4::Context->preference("dateformat") || '') => 1,
474     samebranch     => $samebranch,
475     quickslip             => $quickslip,
476     extendedattributes => $attributes,
477 );
478
479 #Get the slip news items
480 my $all_koha_news   = &GetNewsToDisplay("slip");
481 my $koha_news_count = scalar @$all_koha_news;
482
483 $template->param(
484     koha_news       => $all_koha_news,
485     koha_news_count => $koha_news_count
486 );
487
488 output_html_with_http_headers $input, $cookie, $template->output;