Bug 10694: (follow-up) fix various issues
[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::Branch; # GetBranchName
51 use C4::Form::MessagingPreferences;
52 use List::MoreUtils qw/uniq/;
53 use C4::Members::Attributes qw(GetBorrowerAttributes);
54 use Koha::Borrower::Debarments qw(GetDebarments);
55 #use Smart::Comments;
56 #use Data::Dumper;
57 use DateTime;
58 use Koha::DateUtils;
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 = CGI->new;
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     # circ staff who process checkouts but can't edit
87     # patrons still need to be able to access print view
88     $flagsrequired = { circulate => "circulate_remaining_permissions" };
89 } elsif ($print eq "slip") {
90     $template_name = "members/moremember-receipt.tmpl";
91     # circ staff who process checkouts but can't edit
92     # patrons still need to be able to print receipts
93     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
94 } elsif ($print eq "qslip") {
95     $template_name = "members/moremember-receipt.tmpl";
96     $quickslip = 1;
97     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
98 } elsif ($print eq "brief") {
99     $template_name = "members/moremember-brief.tmpl";
100     $flagsrequired = { borrowers => 1 };
101 } else {
102     $template_name = "members/moremember.tmpl";
103     $flagsrequired = { borrowers => 1 };
104 }
105
106 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
107     {
108         template_name   => $template_name,
109         query           => $input,
110         type            => "intranet",
111         authnotrequired => 0,
112         flagsrequired   => $flagsrequired,
113         debug           => 1,
114     }
115 );
116 my $borrowernumber = $input->param('borrowernumber');
117
118 #start the page and read in includes
119 my $data           = GetMember( 'borrowernumber' => $borrowernumber );
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 my $category_type = $data->{'category_type'};
128
129 ### $category_type
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(gonenoaddress lost borrowernotes)) {
146          $data->{$_} and $template->param(flagged => 1) and last;
147 }
148
149 my $debar = $data->{'debarred'};
150 if ($debar) {
151     $template->param( 'userdebarred' => 1, 'flagged' => 1 );
152     if ( $debar ne "9999-12-31" ) {
153         $template->param( 'userdebarreddate' => C4::Dates::format_date($debar) );
154         $template->param( 'debarredcomment'  => $data->{debarredcomment} );
155     }
156 }
157
158 $data->{'ethnicity'} = fixEthnicity( $data->{'ethnicity'} );
159 $data->{ "sex_".$data->{'sex'}."_p" } = 1;
160
161 my $catcode;
162 if ( $category_type eq 'C') {
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("IndependentBranches") ) {
215     my $userenv = C4::Context->userenv;
216     if ( C4::Context->IsSuperLibrarian() ) {
217         $samebranch = 1;
218     }
219     else {
220         $samebranch = ( $data->{'branchcode'} eq $userenv->{branch} );
221     }
222 }
223 else {
224     $samebranch = 1;
225 }
226 my $branchdetail = GetBranchDetail( $data->{'branchcode'});
227 @{$data}{keys %$branchdetail} = values %$branchdetail; # merge in all branch columns
228
229 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
230 my $lib1 = &GetSortDetails( "Bsort1", $data->{'sort1'} );
231 my $lib2 = &GetSortDetails( "Bsort2", $data->{'sort2'} );
232 $template->param( lib1 => $lib1 ) if ($lib1);
233 $template->param( lib2 => $lib2 ) if ($lib2);
234
235 # If printing a page, send the account informations to the template
236 if ($print eq "page") {
237     foreach my $accountline (@$accts) {
238         $accountline->{amount} = sprintf '%.2f', $accountline->{amount};
239         $accountline->{amountoutstanding} = sprintf '%.2f', $accountline->{amountoutstanding};
240
241         if ($accountline->{accounttype} ne 'F' && $accountline->{accounttype} ne 'FU'){
242             $accountline->{printtitle} = 1;
243         }
244     }
245     $template->param( accounts => $accts );
246 }
247
248 # Show OPAC privacy preference is system preference is set
249 if ( C4::Context->preference('OPACPrivacy') ) {
250     $template->param( OPACPrivacy => 1);
251     $template->param( "privacy".$data->{'privacy'} => 1);
252 }
253
254 # current issues
255 #
256 my @borrowernumbers = GetMemberRelatives($borrowernumber);
257 my $issue       = GetPendingIssues($borrowernumber);
258 my $relissue    = [];
259 if ( @borrowernumbers ) {
260     $relissue    = GetPendingIssues(@borrowernumbers);
261 }
262 my $roadtype = C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $data->{streettype} );
263 my $today       = DateTime->now( time_zone => C4::Context->tz);
264 $today->truncate(to => 'day');
265 my @borrowers_with_issues;
266 my $overdues_exist = 0;
267 my $totalprice = 0;
268
269 my @issuedata = build_issue_data($issue);
270 my @relissuedata = build_issue_data($relissue);
271
272
273 ### ###############################################################################
274 # BUILD HTML
275 # show all reserves of this borrower, and the position of the reservation ....
276 if ($borrowernumber) {
277
278     # new op dev
279     # now we show the status of the borrower's reservations
280     my @borrowerreserv = GetReservesFromBorrowernumber($borrowernumber );
281     my @reservloop;
282     foreach my $num_res (@borrowerreserv) {
283         my %getreserv;
284         my $getiteminfo  = GetBiblioFromItemNumber( $num_res->{'itemnumber'} );
285         my $itemtypeinfo = getitemtypeinfo( $getiteminfo->{'itemtype'} );
286         my ( $transfertwhen, $transfertfrom, $transfertto ) =
287             GetTransfers( $num_res->{'itemnumber'} );
288
289         foreach (qw(waiting transfered nottransfered)) {
290             $getreserv{$_} = 0;
291         }
292         $getreserv{reservedate}  = $num_res->{'reservedate'};
293         foreach (qw(biblionumber title author itemcallnumber )) {
294             $getreserv{$_} = $getiteminfo->{$_};
295         }
296         $getreserv{barcodereserv}  = $getiteminfo->{'barcode'};
297         $getreserv{itemtype}  = $itemtypeinfo->{'description'};
298
299         #               check if we have a waitin status for reservations
300         if ( $num_res->{'found'} eq 'W' ) {
301             $getreserv{color}   = 'reserved';
302             $getreserv{waiting} = 1;
303         }
304
305         #               check transfers with the itemnumber foud in th reservation loop
306         if ($transfertwhen) {
307             $getreserv{color}      = 'transfered';
308             $getreserv{transfered} = 1;
309             $getreserv{datesent}   = C4::Dates->new($transfertwhen, 'iso')->output('syspref') or die "Cannot get new($transfertwhen, 'iso') from C4::Dates";
310             $getreserv{frombranch} = GetBranchName($transfertfrom);
311         }
312
313         if ( ( $getiteminfo->{'holdingbranch'} ne $num_res->{'branchcode'} )
314             and not $transfertwhen )
315         {
316             $getreserv{nottransfered}   = 1;
317             $getreserv{nottransferedby} =
318                 GetBranchName( $getiteminfo->{'holdingbranch'} );
319         }
320         $getreserv{title}          = $getiteminfo->{'title'};
321         $getreserv{subtitle}       = GetRecordValue('subtitle', GetMarcBiblio($getiteminfo->{biblionumber}), GetFrameworkCode($getiteminfo->{biblionumber}));
322
323 #               if we don't have a reserv on item, we put the biblio infos and the waiting position
324         if ( $getiteminfo->{'title'} eq '' ) {
325             my $getbibinfo = GetBiblioData( $num_res->{'biblionumber'} );
326             my $getbibtype = getitemtypeinfo( $getbibinfo->{'itemtype'} );
327             $getreserv{color}           = 'inwait';
328             $getreserv{title}           = $getbibinfo->{'title'};
329             $getreserv{subtitle}        = GetRecordValue('subtitle', GetMarcBiblio($num_res->{biblionumber}), GetFrameworkCode($num_res->{biblionumber}));
330             $getreserv{nottransfered}   = 0;
331             $getreserv{itemtype}        = $getbibtype->{'description'};
332             $getreserv{author}          = $getbibinfo->{'author'};
333             $getreserv{biblionumber}  = $num_res->{'biblionumber'};     
334         }
335         $getreserv{waitingposition} = $num_res->{'priority'};
336         $getreserv{suspend} = $num_res->{'suspend'};
337         $getreserv{suspend_until} = $num_res->{'suspend_until'};
338         $getreserv{expirationdate} = $num_res->{'expirationdate'};
339         $getreserv{reserve_id} = $num_res->{'reserve_id'};
340
341         push( @reservloop, \%getreserv );
342     }
343
344     # return result to the template
345     $template->param( reservloop => \@reservloop,
346         countreserv => scalar @reservloop,
347          );
348 }
349
350 # current alert subscriptions
351 my $alerts = getalert($borrowernumber);
352 foreach (@$alerts) {
353     $_->{ $_->{type} } = 1;
354     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
355 }
356
357 my $candeleteuser;
358 my $userenv = C4::Context->userenv;
359 if ( C4::Context->IsSuperLibrarian() ) {
360     $candeleteuser = 1;
361 }
362 elsif ( C4::Context->preference("IndependentBranches") ) {
363     $candeleteuser = ( $data->{'branchcode'} eq $userenv->{branch} );
364 }
365 else {
366     if ( C4::Auth::getuserflags( $userenv->{flags}, $userenv->{number} )->{borrowers} ) {
367         $candeleteuser = 1;
368     }
369     else {
370         $candeleteuser = 0;
371     }
372 }
373
374 # check to see if patron's image exists in the database
375 # basically this gives us a template var to condition the display of
376 # patronimage related interface on
377 my ($picture, $dberror) = GetPatronImage($data->{'borrowernumber'});
378 $template->param( picture => 1 ) if $picture;
379
380 my $branch=C4::Context->userenv->{'branch'};
381
382 $template->param(%$data);
383
384 if (C4::Context->preference('ExtendedPatronAttributes')) {
385     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
386     my @classes = uniq( map {$_->{class}} @$attributes );
387     @classes = sort @classes;
388
389     my @attributes_loop;
390     for my $class (@classes) {
391         my @items;
392         for my $attr (@$attributes) {
393             push @items, $attr if $attr->{class} eq $class
394         }
395         my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
396         push @attributes_loop, {
397             class => $class,
398             items => \@items,
399             lib   => $lib,
400         };
401     }
402
403     $template->param(
404         ExtendedPatronAttributes => 1,
405         attributes_loop => \@attributes_loop
406     );
407
408     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
409     if (scalar(@types) == 0) {
410         $template->param(no_patron_attribute_types => 1);
411     }
412 }
413
414 if (C4::Context->preference('EnhancedMessagingPreferences')) {
415     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
416     $template->param(messaging_form_inactive => 1);
417     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
418     $template->param(SMSnumber     => defined $data->{'smsalertnumber'} ? $data->{'smsalertnumber'} : $data->{'mobile'});
419     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
420 }
421
422 # in template <TMPL_IF name="I"> => instutitional (A for Adult, C for children) 
423 $template->param( $data->{'categorycode'} => 1 ); 
424 $template->param(
425     detailview => 1,
426     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
427     CANDELETEUSER    => $candeleteuser,
428     roadtype        => $roadtype,
429     borrowernumber  => $borrowernumber,
430     othernames      => $data->{'othernames'},
431     categoryname    => $data->{'description'},
432     was_renewed     => $input->param('was_renewed') ? 1 : 0,
433     branch          => $branch,
434     todaysdate      => C4::Dates->today(),
435     totalprice      => sprintf("%.2f", $totalprice),
436     totaldue        => sprintf("%.2f", $total),
437     totaldue_raw    => $total,
438     issueloop       => @issuedata,
439     relissueloop    => @relissuedata,
440     overdues_exist  => $overdues_exist,
441     error           => $error,
442     StaffMember     => ($category_type eq 'S'),
443     is_child        => ($category_type eq 'C'),
444 #   reserveloop     => \@reservedata,
445     samebranch     => $samebranch,
446     quickslip             => $quickslip,
447     activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
448     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
449     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
450     RoutingSerials => C4::Context->preference('RoutingSerials'),
451     debarments => GetDebarments({ borrowernumber => $borrowernumber }),
452 );
453 $template->param( $error => 1 ) if $error;
454
455 output_html_with_http_headers $input, $cookie, $template->output;
456
457 sub build_issue_data {
458     my $issues = shift;
459
460     my $localissue;
461
462     foreach my $issue ( @{$issues} ) {
463
464         # Getting borrower details
465         my $memberdetails = GetMemberDetails( $issue->{borrowernumber} );
466         $issue->{borrowername} =
467           $memberdetails->{firstname} . ' ' . $memberdetails->{surname};
468         $issue->{cardnumber} = $memberdetails->{cardnumber};
469         my $issuedate;
470         if ($issue->{issuedate} ) {
471            $issuedate = $issue->{issuedate}->clone();
472         }
473         $issue->{subtitle} = GetRecordValue('subtitle', GetMarcBiblio($issue->{biblionumber}), GetFrameworkCode($issue->{biblionumber}));
474         $issue->{issuingbranchname} = GetBranchName($issue->{branchcode});
475         my %row          = %{$issue};
476         $totalprice += $issue->{replacementprice};
477
478         # item lost, damaged loops
479         if ( $row{'itemlost'} ) {
480             my $fw       = GetFrameworkCode( $issue->{biblionumber} );
481             my $category = GetAuthValCode( 'items.itemlost', $fw );
482             my $lostdbh  = C4::Context->dbh;
483             my $sth      = $lostdbh->prepare(
484 "select lib from authorised_values where category=? and authorised_value =? "
485             );
486             $sth->execute( $category, $row{'itemlost'} );
487             my $loststat = $sth->fetchrow;
488             if ($loststat) {
489                 $row{'itemlost'} = $loststat;
490             }
491         }
492         if ( $row{'damaged'} ) {
493             my $fw         = GetFrameworkCode( $issue->{biblionumber} );
494             my $category   = GetAuthValCode( 'items.damaged', $fw );
495             my $damageddbh = C4::Context->dbh;
496             my $sth        = $damageddbh->prepare(
497 "select lib from authorised_values where category=? and authorised_value =? "
498             );
499             $sth->execute( $category, $row{'damaged'} );
500             my $damagedstat = $sth->fetchrow;
501             if ($damagedstat) {
502                 $row{'itemdamaged'} = $damagedstat;
503             }
504         }
505
506         # end lost, damaged
507         if ( $issue->{overdue} ) {
508             $overdues_exist = 1;
509             $row{red} = 1;
510         }
511         if ($issuedate) {
512             $issuedate->truncate( to => 'day' );
513             if ( DateTime->compare( $issuedate, $today ) == 0 ) {
514                 $row{today} = 1;
515             }
516         }
517
518         #find the charge for an item
519         my ( $charge, $itemtype ) =
520           GetIssuingCharges( $issue->{itemnumber}, $borrowernumber );
521
522         my $itemtypeinfo = getitemtypeinfo($itemtype);
523         $row{'itemtype_description'} = $itemtypeinfo->{description};
524         $row{'itemtype_image'}       = $itemtypeinfo->{imageurl};
525
526         $row{'charge'} = sprintf( "%.2f", $charge );
527
528         my ( $renewokay, $renewerror ) =
529           CanBookBeRenewed( $borrowernumber, $issue->{itemnumber},
530             $override_limit );
531         $row{'norenew'} = !$renewokay;
532         $row{'can_confirm'} = ( !$renewokay && $renewerror ne 'on_reserve' );
533         $row{"norenew_reason_$renewerror"} = 1 if $renewerror;
534         $row{renew_failed}  = $renew_failed{ $issue->{itemnumber} };
535         $row{return_failed} = $return_failed{ $issue->{barcode} };
536         ($row{'renewcount'},$row{'renewsallowed'},$row{'renewsleft'}) = C4::Circulation::GetRenewCount($issue->{'borrowernumber'},$issue->{'itemnumber'}); #Add renewal count to item data display
537
538         $row{'soonestrenewdate'} = output_pref(
539             C4::Circulation::GetSoonestRenewDate(
540                 $issue->{borrowernumber},
541                 $issue->{itemnumber}
542             )
543         );
544
545         push( @{$localissue}, \%row );
546     }
547     return $localissue;
548 }