Merge branch 'new/enh/bug_4877'
[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         my $datedue = $issue->[$i]{'date_due'};
264         my $issuedate = $issue->[$i]{'issuedate'};
265         $issue->[$i]{'date_due'}  = C4::Dates->new($issue->[$i]{'date_due'}, 'iso')->output('syspref');
266         $issue->[$i]{'issuedate'} = C4::Dates->new($issue->[$i]{'issuedate'},'iso')->output('syspref');
267         my $biblionumber = $issue->[$i]{'biblionumber'};
268         $issue->[$i]{'issuingbranchname'} = GetBranchName($issue->[$i]{'branchcode'});
269         my %row = %{ $issue->[$i] };
270         $totalprice += $issue->[$i]{'replacementprice'};
271         $row{'replacementprice'} = $issue->[$i]{'replacementprice'};
272         # item lost, damaged loops
273         if ($row{'itemlost'}) {
274             my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
275             my $category = GetAuthValCode('items.itemlost',$fw);
276             my $lostdbh = C4::Context->dbh;
277             my $sth = $lostdbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
278             $sth->execute($category, $row{'itemlost'});
279             my $loststat = $sth->fetchrow;
280             if ($loststat) {
281                $row{'itemlost'} = $loststat;
282             }
283         }
284         if ($row{'damaged'}) {
285             my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
286             my $category = GetAuthValCode('items.damaged',$fw);
287             my $damageddbh = C4::Context->dbh;
288             my $sth = $damageddbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
289             $sth->execute($category, $row{'damaged'});
290             my $damagedstat = $sth->fetchrow;
291             if ($damagedstat) {
292                $row{'itemdamaged'} = $damagedstat;
293             }
294         }
295         # end lost, damaged
296         if ( $datedue lt $today ) {
297             $overdues_exist = 1;
298             $row{'red'} = 1;
299         }
300          if ( $issuedate eq $today ) {
301             $row{'today'} = 1; 
302          }
303
304         #find the charge for an item
305         my ( $charge, $itemtype ) =
306           GetIssuingCharges( $issue->[$i]{'itemnumber'}, $issue->[$i]{'borrowernumber'} );
307
308         my $itemtypeinfo = getitemtypeinfo($itemtype);
309         $row{'itemtype_description'} = $itemtypeinfo->{description};
310         $row{'itemtype_image'}       = $itemtypeinfo->{imageurl};
311
312         $row{'charge'} = sprintf( "%.2f", $charge );
313
314         my ( $renewokay,$renewerror ) = CanBookBeRenewed( $issue->[$i]{'borrowernumber'}, $issue->[$i]{'itemnumber'}, $override_limit );
315         $row{'norenew'} = !$renewokay;
316         $row{'can_confirm'} = ( !$renewokay && $renewerror ne 'on_reserve' );
317         $row{"norenew_reason_$renewerror"} = 1 if $renewerror;
318         $row{'renew_failed'}  = $renew_failed{ $issue->[$i]{'itemnumber'} };
319         $row{'return_failed'} = $return_failed{$issue->[$i]{'barcode'}};   
320         push( @$localissue, \%row );
321     }
322     return $localissue;
323 }
324
325
326 ### ###############################################################################
327 # BUILD HTML
328 # show all reserves of this borrower, and the position of the reservation ....
329 if ($borrowernumber) {
330
331     # new op dev
332     # now we show the status of the borrower's reservations
333     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
334     my @reservloop;
335     foreach my $num_res (@borrowerreserv) {
336         my %getreserv;
337         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
338         my $itemtypeinfo = getitemtypeinfo( $getiteminfo->{'itemtype'} );
339         my ( $transfertwhen, $transfertfrom, $transfertto ) =
340             GetTransfers( $num_res->{'itemnumber'} );
341
342         foreach (qw(waiting transfered nottransfered)) {
343             $getreserv{$_} = 0;
344         }
345         $getreserv{reservedate}  = C4::Dates->new($num_res->{'reservedate'},'iso')->output('syspref');
346         foreach (qw(biblionumber title author itemcallnumber )) {
347             $getreserv{$_} = $getiteminfo->{$_};
348         }
349         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
350         $getreserv{itemtype}  = $itemtypeinfo->{'description'};
351
352         #               check if we have a waitin status for reservations
353         if ( $num_res->{'found'} eq 'W' ) {
354             $getreserv{color}   = 'reserved';
355             $getreserv{waiting} = 1;
356         }
357
358         #               check transfers with the itemnumber foud in th reservation loop
359         if ($transfertwhen) {
360             $getreserv{color}      = 'transfered';
361             $getreserv{transfered} = 1;
362             $getreserv{datesent}   = C4::Dates->new($transfertwhen, 'iso')->output('syspref') or die "Cannot get new($transfertwhen, 'iso') from C4::Dates";
363             $getreserv{frombranch} = GetBranchName($transfertfrom);
364         }
365
366         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
367             and not $transfertwhen )
368         {
369             $getreserv{nottransfered}   = 1;
370             $getreserv{nottransferedby} =
371                 GetBranchName( $getiteminfo->{'holdingbranch'} );
372         }
373
374 #               if we don't have a reserv on item, we put the biblio infos and the waiting position
375         if ( $getiteminfo->{'title'} eq '' ) {
376             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
377             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );
378             $getreserv{color}           = 'inwait';
379             $getreserv{title}           = $getbibinfo->{'title'};
380             $getreserv{nottransfered}   = 0;
381             $getreserv{itemtype}        = $getbibtype->{'description'};
382             $getreserv{author}          = $getbibinfo->{'author'};
383             $getreserv{biblionumber}  = $num_res->{'biblionumber'};     
384         }
385         $getreserv{waitingposition} = $num_res->{'priority'};
386
387         push( @reservloop, \%getreserv );
388     }
389
390     # return result to the template
391     $template->param( reservloop => \@reservloop,
392         countreserv => scalar @reservloop,
393          );
394 }
395
396 # current alert subscriptions
397 my $alerts = getalert($borrowernumber);
398 foreach (@$alerts) {
399     $_->{ $_->{type} } = 1;
400     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
401 }
402
403 my $candeleteuser;
404 my $userenv = C4::Context->userenv;
405 if($userenv->{flags} % 2 == 1){
406     $candeleteuser = 1;
407 }elsif ( C4::Context->preference("IndependantBranches") ) {
408     $candeleteuser = ( $data->{'branchcode'} eq $userenv->{branch} );
409 }else{
410     if( C4::Auth::getuserflags( $userenv->{flags},$userenv->{number})->{borrowers} ) {
411         $candeleteuser = 1;
412     }else{
413         $candeleteuser = 0;
414     }
415 }
416
417 # check to see if patron's image exists in the database
418 # basically this gives us a template var to condition the display of
419 # patronimage related interface on
420 my ($picture, $dberror) = GetPatronImage($data->{'cardnumber'});
421 $template->param( picture => 1 ) if $picture;
422
423 my $branch=C4::Context->userenv->{'branch'};
424
425 $template->param(%$data);
426
427 if (C4::Context->preference('ExtendedPatronAttributes')) {
428     my $attributes = GetBorrowerAttributes($borrowernumber);
429     $template->param(
430         ExtendedPatronAttributes => 1,
431         extendedattributes => $attributes
432     );
433     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
434     if (scalar(@types) == 0) {
435         $template->param(no_patron_attribute_types => 1);
436     }
437 }
438
439 if (C4::Context->preference('EnhancedMessagingPreferences')) {
440     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
441     $template->param(messaging_form_inactive => 1);
442     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
443     $template->param(SMSnumber     => defined $data->{'smsalertnumber'} ? $data->{'smsalertnumber'} : $data->{'mobile'});
444 }
445
446 $template->param(
447     detailview => 1,
448     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
449     DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
450     CANDELETEUSER    => $candeleteuser,
451     roaddetails     => $roaddetails,
452     borrowernumber  => $borrowernumber,
453     categoryname    => $data->{'description'},
454     reregistration  => $reregistration,
455     branch          => $branch,
456     todaysdate      => C4::Dates->today(),
457     totalprice      => sprintf("%.2f", $totalprice),
458     totaldue        => sprintf("%.2f", $total),
459     totaldue_raw    => $total,
460     issueloop       => @issuedata,
461     relissueloop    => @relissuedata,
462         issuecount      => $issuecount,
463     relissuecount   => $relissuecount,
464     overdues_exist  => $overdues_exist,
465     error           => $error,
466     $error          => 1,
467     StaffMember     => ($category_type eq 'S'),
468     is_child        => ($category_type eq 'C'),
469 #   reserveloop     => \@reservedata,
470     dateformat      => C4::Context->preference("dateformat"),
471     "dateformat_" . (C4::Context->preference("dateformat") || '') => 1,
472     samebranch     => $samebranch,
473     quickslip             => $quickslip,
474 );
475
476 #Get the slip news items
477 my $all_koha_news   = &GetNewsToDisplay("slip");
478 my $koha_news_count = scalar @$all_koha_news;
479
480 $template->param(
481     koha_news       => $all_koha_news,
482     koha_news_count => $koha_news_count
483 );
484
485 output_html_with_http_headers $input, $cookie, $template->output;