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