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