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