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