Bug 20991: Do not lost patron's category when editing a patron
[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 Modern::Perl;
37 use CGI qw ( -utf8 );
38 use HTML::Entities;
39 use C4::Context;
40 use C4::Auth;
41 use C4::Output;
42 use C4::Members;
43 use C4::Members::Attributes;
44 use C4::Members::AttributeTypes;
45 use C4::Reserves;
46 use C4::Circulation;
47 use C4::Koha;
48 use C4::Letters;
49 use C4::Biblio;
50 use C4::Form::MessagingPreferences;
51 use List::MoreUtils qw/uniq/;
52 use C4::Members::Attributes qw(GetBorrowerAttributes);
53 use Koha::Account::Lines;
54 use Koha::AuthorisedValues;
55 use Koha::CsvProfiles;
56 use Koha::Patron::Debarments qw(GetDebarments);
57 use Koha::Patron::Messages;
58 use Module::Load;
59 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
60     load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
61 }
62 #use Smart::Comments;
63 #use Data::Dumper;
64 use DateTime;
65 use Koha::DateUtils;
66 use Koha::Database;
67 use Koha::Patrons;
68 use Koha::Patron::Categories;
69 use Koha::Token;
70
71 use vars qw($debug);
72
73 BEGIN {
74         $debug = $ENV{DEBUG} || 0;
75 }
76
77 my $dbh = C4::Context->dbh;
78
79 my $input = CGI->new;
80 $debug or $debug = $input->param('debug') || 0;
81 my $print = $input->param('print');
82
83 my $template_name;
84 my $quickslip = 0;
85
86 my $flagsrequired;
87 if (defined $print and $print eq "page") {
88     $template_name = "members/moremember-print.tt";
89     # circ staff who process checkouts but can't edit
90     # patrons still need to be able to access print view
91     $flagsrequired = { circulate => "circulate_remaining_permissions" };
92 } elsif (defined $print and $print eq "slip") {
93     $template_name = "members/moremember-receipt.tt";
94     # circ staff who process checkouts but can't edit
95     # patrons still need to be able to print receipts
96     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
97 } elsif (defined $print and $print eq "qslip") {
98     $template_name = "members/moremember-receipt.tt";
99     $quickslip = 1;
100     $flagsrequired =  { circulate => "circulate_remaining_permissions" };
101 } elsif (defined $print and $print eq "brief") {
102     $template_name = "members/moremember-brief.tt";
103     $flagsrequired = { borrowers => 'edit_borrowers' };
104 } else {
105     $template_name = "members/moremember.tt";
106     $flagsrequired = { borrowers => 'edit_borrowers' };
107 }
108
109 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
110     {
111         template_name   => $template_name,
112         query           => $input,
113         type            => "intranet",
114         authnotrequired => 0,
115         flagsrequired   => $flagsrequired,
116         debug           => 1,
117     }
118 );
119 my $borrowernumber = $input->param('borrowernumber');
120 $borrowernumber = HTML::Entities::encode($borrowernumber);
121 my $error = $input->param('error');
122 $template->param( error => $error ) if ( $error );
123
124 my $patron         = Koha::Patrons->find( $borrowernumber );
125 my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
126 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
127
128 my $issues        = $patron->checkouts;
129 my $balance       = $patron->account->balance;
130 $template->param(
131     issuecount => $issues->count,
132     fines      => $balance,
133 );
134
135 my $category_type = $patron->category->category_type;
136 my $data = $patron->unblessed;
137
138 $debug and printf STDERR "dates (enrolled,expiry,birthdate) raw: (%s, %s, %s)\n", map {$data->{$_}} qw(dateenrolled dateexpiry dateofbirth);
139 foreach (qw(dateenrolled dateexpiry dateofbirth)) { # FIXME This should be removed
140     my $userdate = $data->{$_};
141     unless ($userdate) {
142         $debug and warn sprintf "Empty \$data{%12s}", $_;
143         $data->{$_} = '';
144         next;
145     }
146     $data->{$_} = dt_from_string( $userdate );
147 }
148
149 for (qw(gonenoaddress lost borrowernotes)) {
150          $data->{$_} and $template->param(flagged => 1) and last;
151 }
152
153 if ( $patron->is_debarred ) {
154     $template->param(
155         userdebarred => 1, # FIXME Template should use patron->is_debarred
156         flagged => 1,
157         debarments => scalar GetDebarments({ borrowernumber => $borrowernumber }),
158     );
159     my $debar = $data->{'debarred'};
160     if ( $debar ne "9999-12-31" ) {
161         $template->param( 'userdebarreddate' => output_pref( { dt => dt_from_string( $debar ), dateonly => 1 } ) );
162         $template->param( 'debarredcomment'  => $data->{debarredcomment} );
163     }
164 }
165
166 $data->{ "sex_".$data->{'sex'}."_p" } = 1 if defined $data->{sex};
167
168 if ( $patron->is_child ) {
169     my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => 'A' }, {order_by => ['categorycode']});
170     $template->param( 'CATCODE_MULTI' => 1) if $patron_categories->count > 1;
171     $template->param( 'catcode' => $patron_categories->next->categorycode )  if $patron_categories->count == 1;
172 }
173
174 my @relatives;
175 if ( my $guarantor = $patron->guarantor ) {
176     $template->param( guarantor => $guarantor );
177     push @relatives, $guarantor->borrowernumber;
178     push @relatives, $_->borrowernumber for $patron->siblings;
179 } elsif ( $patron->contactname || $patron->contactfirstname ) {
180     $template->param(
181         guarantor => {
182             firstname => $patron->contactfirstname,
183             surname   => $patron->contactname,
184         }
185     );
186 } else {
187     my @guarantees = $patron->guarantees;
188     $template->param( guarantees => \@guarantees );
189     push @relatives, $_->borrowernumber for @guarantees;
190 }
191
192 my $relatives_issues_count =
193   Koha::Database->new()->schema()->resultset('Issue')
194   ->count( { borrowernumber => \@relatives } );
195
196 my %bor;
197 $bor{'borrowernumber'} = $borrowernumber;
198
199 # Converts the branchcode to the branch name
200 my $samebranch;
201 if ( C4::Context->preference("IndependentBranches") ) {
202     if ( C4::Context->IsSuperLibrarian() ) {
203         $samebranch = 1;
204     }
205     else {
206         my $userenv = C4::Context->userenv;
207         $samebranch = ( $data->{'branchcode'} eq $userenv->{branch} );
208     }
209 }
210 else {
211     $samebranch = 1;
212 }
213 my $library = Koha::Libraries->find( $data->{branchcode})->unblessed;
214 @{$data}{keys %$library} = values %$library; # merge in all branch columns # FIXME This is really ugly, we should pass the library instead
215
216 # If printing a page, send the account informations to the template
217 if (defined $print and $print eq "page") {
218     my $accts = Koha::Account::Lines->search(
219         { borrowernumber => $patron->borrowernumber, amountoutstanding => { '>' => 0 } },
220         { order_by       => { -desc => 'accountlines_id' } }
221     );
222     $template->param( accounts => $accts );
223 }
224
225 # Show OPAC privacy preference is system preference is set
226 if ( C4::Context->preference('OPACPrivacy') ) { # FIXME Should be moved the the template
227     $template->param( OPACPrivacy => 1);
228     $template->param( "privacy".$data->{'privacy'} => 1);
229 }
230
231 my $today       = DateTime->now( time_zone => C4::Context->tz);
232 $today->truncate(to => 'day');
233 my $overdues_exist = 0;
234 my $totalprice = 0;
235
236 # Calculate and display patron's age
237 if ( $data->{dateofbirth} ) {
238     $template->param( age => Koha::Patron->new({ dateofbirth => $data->{dateofbirth} })->get_age );
239 }
240
241 ### ###############################################################################
242 # BUILD HTML
243 # show all reserves of this borrower, and the position of the reservation ....
244 if ($borrowernumber) {
245     $template->param(
246         holds_count => Koha::Database->new()->schema()->resultset('Reserve')
247           ->count( { borrowernumber => $borrowernumber } ) );
248 }
249
250 # Add sync data to the user data
251 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
252     my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
253     if ( $sync ) {
254         $data->{'sync'}       = $sync->sync;
255         $data->{'syncstatus'} = $sync->syncstatus;
256         $data->{'lastsync'}   = $sync->lastsync;
257     }
258 }
259
260 # Generate CSRF token for upload and delete image buttons
261 $template->param(
262     csrf_token => Koha::Token->new->generate_csrf({ session_id => $input->cookie('CGISESSID'),}),
263 );
264
265
266 $template->param(%$data); # FIXME This should be removed and used $patron instead, but too many things are processed above
267
268 if (C4::Context->preference('ExtendedPatronAttributes')) {
269     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
270     my @classes = uniq( map {$_->{class}} @$attributes );
271     @classes = sort @classes;
272
273     my @attributes_loop;
274     for my $class (@classes) {
275         my @items;
276         for my $attr (@$attributes) {
277             push @items, $attr if $attr->{class} eq $class
278         }
279         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
280         my $lib = $av->count ? $av->next->lib : $class;
281
282         push @attributes_loop, {
283             class => $class,
284             items => \@items,
285             lib   => $lib,
286         };
287     }
288
289     $template->param(
290         ExtendedPatronAttributes => 1,
291         attributes_loop => \@attributes_loop
292     );
293
294     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
295     if (scalar(@types) == 0) {
296         $template->param(no_patron_attribute_types => 1);
297     }
298 }
299
300 if (C4::Context->preference('EnhancedMessagingPreferences')) {
301     C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
302     $template->param(messaging_form_inactive => 1);
303     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
304     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
305 }
306
307 if ( C4::Context->preference("ExportCircHistory") ) {
308     $template->param(csv_profiles => [ Koha::CsvProfiles->search({ type => 'marc' }) ]);
309 }
310
311 my $patron_messages = Koha::Patron::Messages->search(
312     {
313         'me.borrowernumber' => $borrowernumber,
314     },
315     {
316         join => 'manager',
317         '+select' => ['manager.surname', 'manager.firstname' ],
318         '+as' => ['manager_surname', 'manager_firstname'],
319     }
320 );
321
322 if( $patron_messages->count > 0 ){
323     $template->param( patron_messages => $patron_messages );
324 }
325
326 # Display the language description instead of the code
327 # Note that this is certainly wrong
328 my ( $subtag, $region ) = split '-', $patron->lang;
329 my $translated_language = C4::Languages::language_get_description( $subtag, $subtag, 'language' );
330
331 my $total = $patron->account->balance;
332 $template->param(
333     patron          => $patron,
334     translated_language => $translated_language,
335     detailview      => 1,
336     was_renewed     => scalar $input->param('was_renewed') ? 1 : 0,
337     todaysdate      => output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 }),
338     totalprice      => sprintf("%.2f", $totalprice),
339     totaldue        => sprintf("%.2f", $total),
340     totaldue_raw    => $total,
341     overdues_exist  => $overdues_exist,
342     StaffMember     => $category_type eq 'S',
343     $category_type  => 1, # [% IF ( I ) %] = institutional/organisation
344     samebranch      => $samebranch,
345     quickslip       => $quickslip,
346     housebound_role => scalar $patron->housebound_role,
347     PatronsPerPage => C4::Context->preference("PatronsPerPage") || 20,
348     relatives_issues_count => $relatives_issues_count,
349     relatives_borrowernumbers => \@relatives,
350 );
351
352 output_html_with_http_headers $input, $cookie, $template->output;