Merge remote branch 'kc/master'
[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
53 #use Smart::Comments;
54 #use Data::Dumper;
55
56 use vars qw($debug);
57
58 BEGIN {
59         $debug = $ENV{DEBUG} || 0;
60 }
61
62 my $dbh = C4::Context->dbh;
63
64 my $input = new CGI;
65 $debug or $debug = $input->param('debug') || 0;
66 my $print = $input->param('print');
67 my $override_limit = $input->param("override_limit") || 0;
68 my @failedrenews = $input->param('failedrenew');
69 my @failedreturns = $input->param('failedreturn');
70 my $error = $input->param('error');
71 my %renew_failed;
72 for my $renew (@failedrenews) { $renew_failed{$renew} = 1; }
73 my %return_failed;
74 for my $failedret (@failedreturns) { $return_failed{$failedret} = 1; }
75
76 my $template_name;
77 my $quickslip = 0;
78
79 my $flagsrequired;
80 if ($print eq "page") {
81     $template_name = "members/moremember-print.tmpl";
82     $flagsrequired = { borrowers => 1 };
83 } elsif ($print eq "slip") {
84     $template_name = "members/moremember-receipt.tmpl";
85     # circ staff who process checkouts but can't edit
86     # patrons still need to be able to print receipts
87     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
88 } elsif ($print eq "qslip") {
89     $template_name = "members/moremember-receipt.tmpl";
90     $quickslip = 1;
91     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
92 } else {
93     $template_name = "members/moremember.tmpl";
94     $flagsrequired = { borrowers => 1 };
95 }
96
97 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
98     {
99         template_name   => $template_name,
100         query           => $input,
101         type            => "intranet",
102         authnotrequired => 0,
103         flagsrequired   => $flagsrequired,
104         debug           => 1,
105     }
106 );
107 my $borrowernumber = $input->param('borrowernumber');
108
109 #start the page and read in includes
110 my $data           = GetMember( 'borrowernumber' => $borrowernumber );
111 my $reregistration = $input->param('reregistration');
112
113 if ( not defined $data ) {
114     $template->param (unknowuser => 1);
115         output_html_with_http_headers $input, $cookie, $template->output;
116     exit;
117 }
118
119 # re-reregistration function to automatic calcul of date expiry
120 if ( $reregistration eq 'y' ) {
121         $data->{'dateexpiry'} = ExtendMemberSubscriptionTo( $borrowernumber );
122 }
123
124 my $category_type = $data->{'category_type'};
125
126 ### $category_type
127
128 # in template <TMPL_IF name="I"> => instutitional (A for Adult& C for children) 
129 $template->param( $data->{'categorycode'} => 1 ); 
130
131 $debug and printf STDERR "dates (enrolled,expiry,birthdate) raw: (%s, %s, %s)\n", map {$data->{$_}} qw(dateenrolled dateexpiry dateofbirth);
132 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
133                 my $userdate = $data->{$_};
134                 unless ($userdate) {
135                         $debug and warn sprintf "Empty \$data{%12s}", $_;
136                         $data->{$_} = '';
137                         next;
138                 }
139                 $userdate = C4::Dates->new($userdate,'iso')->output('syspref');
140                 $data->{$_} = $userdate || '';
141                 $template->param( $_ => $userdate );
142 }
143 $data->{'IS_ADULT'} = ( $data->{'categorycode'} ne 'I' );
144
145 for (qw(debarred gonenoaddress lost borrowernotes)) {
146          $data->{$_} and $template->param(flagged => 1) and last;
147 }
148
149 $data->{'ethnicity'} = fixEthnicity( $data->{'ethnicity'} );
150 $data->{ "sex_".$data->{'sex'}."_p" } = 1;
151
152 my $catcode;
153 if ( $category_type eq 'C') {
154         if ($data->{'guarantorid'} ne '0' ) {
155         my $data2 = GetMember( 'borrowernumber' => $data->{'guarantorid'} );
156         foreach (qw(address city B_address B_city phone mobile zipcode country B_country)) {
157             $data->{$_} = $data2->{$_};
158         }
159    }
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' ) {
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' );
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->{'branchname'} = $branchdetail->{branchname};
222
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 # current issues
231 #
232 my $issue = GetPendingIssues($borrowernumber);
233 my $issuecount = scalar(@$issue);
234 my $roaddetails = &GetRoadTypeDetails( $data->{'streettype'} );
235 my $today       = POSIX::strftime("%Y-%m-%d", localtime);       # iso format
236 my @issuedata;
237 my $overdues_exist = 0;
238 my $totalprice = 0;
239 for ( my $i = 0 ; $i < $issuecount ; $i++ ) {
240     my $datedue = $issue->[$i]{'date_due'};
241     my $issuedate = $issue->[$i]{'issuedate'};
242     $issue->[$i]{'date_due'}  = C4::Dates->new($issue->[$i]{'date_due'}, 'iso')->output('syspref');
243     $issue->[$i]{'issuedate'} = C4::Dates->new($issue->[$i]{'issuedate'},'iso')->output('syspref');
244     my $biblionumber = $issue->[$i]{'biblionumber'};
245     my %row = %{ $issue->[$i] };
246     $totalprice += $issue->[$i]{'replacementprice'};
247     $row{'replacementprice'} = $issue->[$i]{'replacementprice'};
248     # item lost, damaged loops
249     if ($row{'itemlost'}) {
250         my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
251         my $category = GetAuthValCode('items.itemlost',$fw);
252         my $lostdbh = C4::Context->dbh;
253         my $sth = $lostdbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
254         $sth->execute($category, $row{'itemlost'});
255         my $loststat = $sth->fetchrow;
256         if ($loststat) {
257            $row{'itemlost'} = $loststat;
258         }
259     }
260     if ($row{'damaged'}) {
261         my $fw = GetFrameworkCode($issue->[$i]{'biblionumber'});
262         my $category = GetAuthValCode('items.damaged',$fw);
263         my $damageddbh = C4::Context->dbh;
264         my $sth = $damageddbh->prepare("select lib from authorised_values where category=? and authorised_value =? ");
265         $sth->execute($category, $row{'damaged'});
266         my $damagedstat = $sth->fetchrow;
267         if ($damagedstat) {
268            $row{'itemdamaged'} = $damagedstat;
269         }
270     }
271     # end lost, damaged
272     if ( $datedue lt $today ) {
273         $overdues_exist = 1;
274         $row{'red'} = 1;
275         }
276          if ( $issuedate eq $today ) {
277         $row{'today'} = 1; 
278          }
279
280     #find the charge for an item
281     my ( $charge, $itemtype ) =
282       GetIssuingCharges( $issue->[$i]{'itemnumber'}, $borrowernumber );
283
284     my $itemtypeinfo = getitemtypeinfo($itemtype);
285     $row{'itemtype_description'} = $itemtypeinfo->{description};
286     $row{'itemtype_image'}       = $itemtypeinfo->{imageurl};
287
288     $row{'charge'} = sprintf( "%.2f", $charge );
289
290         my ( $renewokay,$renewerror ) = CanBookBeRenewed( $borrowernumber, $issue->[$i]{'itemnumber'}, $override_limit );
291         $row{'norenew'} = !$renewokay;
292         $row{'can_confirm'} = ( !$renewokay && $renewerror ne 'on_reserve' );
293         $row{"norenew_reason_$renewerror"} = 1 if $renewerror;
294         $row{'renew_failed'}  = $renew_failed{ $issue->[$i]{'itemnumber'} };
295         $row{'return_failed'} = $return_failed{$issue->[$i]{'barcode'}};   
296     push( @issuedata, \%row );
297 }
298
299 ### ###############################################################################
300 # BUILD HTML
301 # show all reserves of this borrower, and the position of the reservation ....
302 if ($borrowernumber) {
303
304     # new op dev
305     # now we show the status of the borrower's reservations
306     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
307     my @reservloop;
308     foreach my $num_res (@borrowerreserv) {
309         my %getreserv;
310         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
311         my $itemtypeinfo = getitemtypeinfo( $getiteminfo->{'itemtype'} );
312         my ( $transfertwhen, $transfertfrom, $transfertto ) =
313             GetTransfers( $num_res->{'itemnumber'} );
314
315         foreach (qw(waiting transfered nottransfered)) {
316             $getreserv{$_} = 0;
317         }
318         $getreserv{reservedate}  = C4::Dates->new($num_res->{'reservedate'},'iso')->output('syspref');
319         foreach (qw(biblionumber title author itemcallnumber )) {
320             $getreserv{$_} = $getiteminfo->{$_};
321         }
322         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
323         $getreserv{itemtype}  = $itemtypeinfo->{'description'};
324
325         #               check if we have a waitin status for reservations
326         if ( $num_res->{'found'} eq 'W' ) {
327             $getreserv{color}   = 'reserved';
328             $getreserv{waiting} = 1;
329         }
330
331         #               check transfers with the itemnumber foud in th reservation loop
332         if ($transfertwhen) {
333             $getreserv{color}      = 'transfered';
334             $getreserv{transfered} = 1;
335             $getreserv{datesent}   = C4::Dates->new($transfertwhen, 'iso')->output('syspref') or die "Cannot get new($transfertwhen, 'iso') from C4::Dates";
336             $getreserv{frombranch} = GetBranchName($transfertfrom);
337         }
338
339         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
340             and not $transfertwhen )
341         {
342             $getreserv{nottransfered}   = 1;
343             $getreserv{nottransferedby} =
344                 GetBranchName( $getiteminfo->{'holdingbranch'} );
345         }
346
347 #               if we don't have a reserv on item, we put the biblio infos and the waiting position
348         if ( $getiteminfo->{'title'} eq '' ) {
349             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
350             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );
351             $getreserv{color}           = 'inwait';
352             $getreserv{title}           = $getbibinfo->{'title'};
353             $getreserv{nottransfered}   = 0;
354             $getreserv{itemtype}        = $getbibtype->{'description'};
355             $getreserv{author}          = $getbibinfo->{'author'};
356             $getreserv{biblionumber}  = $num_res->{'biblionumber'};     
357         }
358         $getreserv{waitingposition} = $num_res->{'priority'};
359
360         push( @reservloop, \%getreserv );
361     }
362
363     # return result to the template
364     $template->param( reservloop => \@reservloop,
365         countreserv => scalar @reservloop,
366          );
367 }
368
369 # current alert subscriptions
370 my $alerts = getalert($borrowernumber);
371 foreach (@$alerts) {
372     $_->{ $_->{type} } = 1;
373     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
374 }
375
376 my $candeleteuser;
377 my $userenv = C4::Context->userenv;
378 if($userenv->{flags} % 2 == 1){
379     $candeleteuser = 1;
380 }elsif ( C4::Context->preference("IndependantBranches") ) {
381     $candeleteuser = ( $data->{'branchcode'} eq $userenv->{branch} );
382 }else{
383     if( C4::Auth::getuserflags( $userenv->{flags},$userenv->{number})->{borrowers} ) {
384         $candeleteuser = 1;
385     }else{
386         $candeleteuser = 0;
387     }
388 }
389
390 # check to see if patron's image exists in the database
391 # basically this gives us a template var to condition the display of
392 # patronimage related interface on
393 my ($picture, $dberror) = GetPatronImage($data->{'cardnumber'});
394 $template->param( picture => 1 ) if $picture;
395
396 my $branch=C4::Context->userenv->{'branch'};
397
398 $template->param($data);
399
400 if (C4::Context->preference('ExtendedPatronAttributes')) {
401     $template->param(ExtendedPatronAttributes => 1);
402     $template->param(patron_attributes => C4::Members::Attributes::GetBorrowerAttributes($borrowernumber));
403     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
404     if (scalar(@types) == 0) {
405         $template->param(no_patron_attribute_types => 1);
406     }
407 }
408
409 if (C4::Context->preference('EnhancedMessagingPreferences')) {
410     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
411     $template->param(messaging_form_inactive => 1);
412     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
413     $template->param(SMSnumber     => defined $data->{'smsalertnumber'} ? $data->{'smsalertnumber'} : $data->{'mobile'});
414 }
415
416 $template->param(
417     detailview => 1,
418     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
419     DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
420     CANDELETEUSER    => $candeleteuser,
421     roaddetails     => $roaddetails,
422     borrowernumber  => $borrowernumber,
423     categoryname    => $data->{'description'},
424     reregistration  => $reregistration,
425     branch          => $branch,
426     totalprice      => sprintf("%.2f", $totalprice),
427     totaldue        => sprintf("%.2f", $total),
428     totaldue_raw    => $total,
429     issueloop       => \@issuedata,
430         issuecount => $issuecount,
431     overdues_exist  => $overdues_exist,
432     error           => $error,
433     $error          => 1,
434     StaffMember     => ($category_type eq 'S'),
435     is_child        => ($category_type eq 'C'),
436 #   reserveloop     => \@reservedata,
437     dateformat      => C4::Context->preference("dateformat"),
438     "dateformat_" . (C4::Context->preference("dateformat") || '') => 1,
439     samebranch     => $samebranch,
440     quickslip             => $quickslip,
441 );
442
443 output_html_with_http_headers $input, $cookie, $template->output;