Bug 14610 [QA Followup] - Implement staff patron tab
[koha.git] / members / moremember.pl
1 #!/usr/bin/perl
2
3 # Copyright 2000-2002 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Copyright 2014 ByWater Solutions
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22
23 =head1 moremember.pl
24
25  script to do a borrower enquiry/bring up borrower details etc
26  Displays all the details about a borrower
27  written 20/12/99 by chris@katipo.co.nz
28  last modified 21/1/2000 by chris@katipo.co.nz
29  modified 31/1/2001 by chris@katipo.co.nz
30    to not allow items on request to be renewed
31
32  needs html removed and to use the C4::Output more, but its tricky
33
34 =cut
35
36 use strict;
37 #use warnings; FIXME - Bug 2505
38 use CGI qw ( -utf8 );
39 use Digest::MD5 qw(md5_base64);
40 use C4::Context;
41 use C4::Auth;
42 use C4::Output;
43 use C4::Members;
44 use C4::Members::Attributes;
45 use C4::Members::AttributeTypes;
46 use C4::Reserves;
47 use C4::Circulation;
48 use C4::Koha;
49 use C4::Letters;
50 use C4::Biblio;
51 use C4::Form::MessagingPreferences;
52 use List::MoreUtils qw/uniq/;
53 use C4::Members::Attributes qw(GetBorrowerAttributes);
54 use Koha::AuthorisedValues;
55 use Koha::Patron::Debarments qw(GetDebarments);
56 use Koha::Patron::Images;
57 use Module::Load;
58 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
59     load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
60 }
61 #use Smart::Comments;
62 #use Data::Dumper;
63 use DateTime;
64 use Koha::DateUtils;
65 use Koha::Database;
66 use Koha::Patron::Categories;
67 use Koha::Token;
68
69 use vars qw($debug);
70
71 BEGIN {
72         $debug = $ENV{DEBUG} || 0;
73 }
74
75 my $dbh = C4::Context->dbh;
76
77 my $input = CGI->new;
78 $debug or $debug = $input->param('debug') || 0;
79 my $print = $input->param('print');
80
81 my $template_name;
82 my $quickslip = 0;
83
84 my $flagsrequired;
85 if (defined $print and $print eq "page") {
86     $template_name = "members/moremember-print.tt";
87     # circ staff who process checkouts but can't edit
88     # patrons still need to be able to access print view
89     $flagsrequired = { circulate => "circulate_remaining_permissions" };
90 } elsif (defined $print and $print eq "slip") {
91     $template_name = "members/moremember-receipt.tt";
92     # circ staff who process checkouts but can't edit
93     # patrons still need to be able to print receipts
94     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
95 } elsif (defined $print and $print eq "qslip") {
96     $template_name = "members/moremember-receipt.tt";
97     $quickslip = 1;
98     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
99 } elsif (defined $print and $print eq "brief") {
100     $template_name = "members/moremember-brief.tt";
101     $flagsrequired = { borrowers => 1 };
102 } else {
103     $template_name = "members/moremember.tt";
104     $flagsrequired = { borrowers => 1 };
105 }
106
107 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
108     {
109         template_name   => $template_name,
110         query           => $input,
111         type            => "intranet",
112         authnotrequired => 0,
113         flagsrequired   => $flagsrequired,
114         debug           => 1,
115     }
116 );
117 my $borrowernumber = $input->param('borrowernumber');
118 my $error = $input->param('error');
119 $template->param( error => $error ) if ( $error );
120
121 my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
122 $template->param( issuecount => $issue, fines => $fines );
123
124 my $data = GetMember( 'borrowernumber' => $borrowernumber );
125
126 if ( not defined $data ) {
127     $template->param (unknowuser => 1);
128         output_html_with_http_headers $input, $cookie, $template->output;
129     exit;
130 }
131
132 my $category_type = $data->{'category_type'};
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     $template->param( $_ => dt_from_string( $userdate ) );
143 }
144 $data->{'IS_ADULT'} = ( $data->{'categorycode'} ne 'I' );
145
146 for (qw(gonenoaddress lost borrowernotes)) {
147          $data->{$_} and $template->param(flagged => 1) and last;
148 }
149
150 if ( Koha::Patrons->find( $borrowernumber )->is_debarred ) {
151     $template->param( 'userdebarred' => 1, 'flagged' => 1 );
152     my $debar = $data->{'debarred'};
153     if ( $debar ne "9999-12-31" ) {
154         $template->param( 'userdebarreddate' => output_pref( { dt => dt_from_string( $debar ), dateonly => 1 } ) );
155         $template->param( 'debarredcomment'  => $data->{debarredcomment} );
156     }
157 }
158
159 $data->{ "sex_".$data->{'sex'}."_p" } = 1 if defined $data->{sex};
160
161 if ( $category_type eq 'C') {
162     my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => 'A' }, {order_by => ['categorycode']});
163     $template->param( 'CATCODE_MULTI' => 1) if $patron_categories->count > 1;
164     $template->param( 'catcode' => $patron_categories->next )  if $patron_categories->count == 1;
165 }
166
167 my $patron = Koha::Patrons->find($data->{borrowernumber});
168 my @relatives;
169 if ( my $guarantor = $patron->guarantor ) {
170     $template->param( guarantor => $guarantor );
171     push @relatives, $guarantor->borrowernumber;
172     push @relatives, $_->borrowernumber for $patron->siblings;
173 } elsif ( $patron->contactname || $patron->contactfirstname ) {
174     $template->param(
175         guarantor => {
176             firstname => $patron->contactfirstname,
177             surname   => $patron->contactname,
178         }
179     );
180 } else {
181     my @guarantees = $patron->guarantees;
182     $template->param( guarantees => \@guarantees );
183     push @relatives, $_->borrowernumber for @guarantees;
184 }
185
186 my $relatives_issues_count =
187   Koha::Database->new()->schema()->resultset('Issue')
188   ->count( { borrowernumber => \@relatives } );
189
190 $template->param( adultborrower => 1 ) if ( $category_type eq 'A' || $category_type eq 'I' );
191
192 my %bor;
193 $bor{'borrowernumber'} = $borrowernumber;
194
195 # Converts the branchcode to the branch name
196 my $samebranch;
197 if ( C4::Context->preference("IndependentBranches") ) {
198     my $userenv = C4::Context->userenv;
199     if ( C4::Context->IsSuperLibrarian() ) {
200         $samebranch = 1;
201     }
202     else {
203         $samebranch = ( $data->{'branchcode'} eq $userenv->{branch} );
204     }
205 }
206 else {
207     $samebranch = 1;
208 }
209 my $library = Koha::Libraries->find( $data->{branchcode})->unblessed;
210 @{$data}{keys %$library} = values %$library; # merge in all branch columns
211
212 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
213
214 # If printing a page, send the account informations to the template
215 if ($print eq "page") {
216     foreach my $accountline (@$accts) {
217         $accountline->{amount} = sprintf '%.2f', $accountline->{amount};
218         $accountline->{amountoutstanding} = sprintf '%.2f', $accountline->{amountoutstanding};
219
220         if ($accountline->{accounttype} ne 'F' && $accountline->{accounttype} ne 'FU'){
221             $accountline->{printtitle} = 1;
222         }
223     }
224     $template->param( accounts => $accts );
225 }
226
227 # Show OPAC privacy preference is system preference is set
228 if ( C4::Context->preference('OPACPrivacy') ) {
229     $template->param( OPACPrivacy => 1);
230     $template->param( "privacy".$data->{'privacy'} => 1);
231 }
232
233 my $today       = DateTime->now( time_zone => C4::Context->tz);
234 $today->truncate(to => 'day');
235 my $overdues_exist = 0;
236 my $totalprice = 0;
237
238 # Calculate and display patron's age
239 my $dateofbirth = $data->{ 'dateofbirth' };
240 my $age = GetAge($dateofbirth);
241 $template->param( age => $age );
242
243 ### ###############################################################################
244 # BUILD HTML
245 # show all reserves of this borrower, and the position of the reservation ....
246 if ($borrowernumber) {
247     $template->param(
248         holds_count => Koha::Database->new()->schema()->resultset('Reserve')
249           ->count( { borrowernumber => $borrowernumber } ) );
250 }
251
252 # current alert subscriptions
253 my $alerts = getalert($borrowernumber);
254 foreach (@$alerts) {
255     $_->{ $_->{type} } = 1;
256     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
257 }
258
259 # Add sync data to the user data
260 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
261     my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
262     if ( $sync ) {
263         $data->{'sync'}       = $sync->sync;
264         $data->{'syncstatus'} = $sync->syncstatus;
265         $data->{'lastsync'}   = $sync->lastsync;
266     }
267 }
268
269 # check to see if patron's image exists in the database
270 # basically this gives us a template var to condition the display of
271 # patronimage related interface on
272 my $patron_image = Koha::Patron::Images->find($data->{borrowernumber});
273 $template->param( picture => 1 ) if $patron_image;
274 # Generate CSRF token for upload and delete image buttons
275 $template->param(
276     csrf_token => Koha::Token->new->generate_csrf({
277         id     => C4::Context->userenv->{id},
278         secret => md5_base64( C4::Context->config('pass') ),
279     }),
280 );
281
282
283 $template->param(%$data);
284
285 if (C4::Context->preference('ExtendedPatronAttributes')) {
286     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
287     my @classes = uniq( map {$_->{class}} @$attributes );
288     @classes = sort @classes;
289
290     my @attributes_loop;
291     for my $class (@classes) {
292         my @items;
293         for my $attr (@$attributes) {
294             push @items, $attr if $attr->{class} eq $class
295         }
296         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
297         my $lib = $av->count ? $av->next->lib : $class;
298
299         push @attributes_loop, {
300             class => $class,
301             items => \@items,
302             lib   => $lib,
303         };
304     }
305
306     $template->param(
307         ExtendedPatronAttributes => 1,
308         attributes_loop => \@attributes_loop
309     );
310
311     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
312     if (scalar(@types) == 0) {
313         $template->param(no_patron_attribute_types => 1);
314     }
315 }
316
317 if (C4::Context->preference('EnhancedMessagingPreferences')) {
318     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
319     $template->param(messaging_form_inactive => 1);
320     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
321     $template->param(SMSnumber     => defined $data->{'smsalertnumber'} ? $data->{'smsalertnumber'} : $data->{'mobile'});
322     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
323 }
324
325 # in template <TMPL_IF name="I"> => instutitional (A for Adult, C for children) 
326 $template->param( $data->{'categorycode'} => 1 );
327 $template->param(
328     patron          => $patron,
329     detailview      => 1,
330     borrowernumber  => $borrowernumber,
331     othernames      => $data->{'othernames'},
332     categoryname    => $data->{'description'},
333     was_renewed     => scalar $input->param('was_renewed') ? 1 : 0,
334     todaysdate      => output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }),
335     totalprice      => sprintf("%.2f", $totalprice),
336     totaldue        => sprintf("%.2f", $total),
337     totaldue_raw    => $total,
338     overdues_exist  => $overdues_exist,
339     StaffMember     => ($category_type eq 'S'),
340     is_child        => ($category_type eq 'C'),
341     samebranch      => $samebranch,
342     quickslip       => $quickslip,
343     housebound_role => $patron->housebound_role,
344     privacy_guarantor_checkouts => $data->{'privacy_guarantor_checkouts'},
345     activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
346     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
347     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
348     RoutingSerials => C4::Context->preference('RoutingSerials'),
349     debarments => GetDebarments({ borrowernumber => $borrowernumber }),
350     PatronsPerPage => C4::Context->preference("PatronsPerPage") || 20,
351     relatives_issues_count => $relatives_issues_count,
352     relatives_borrowernumbers => \@relatives,
353 );
354
355 output_html_with_http_headers $input, $cookie, $template->output;