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