Bug 20702: Bind results of GetHostItemsInfo to the EasyAnalyticalRecords pref
[koha.git] / members / memberentry.pl
blob5dc318cae02b0fed488e29ca38f1f01b7db0859f
1 #!/usr/bin/perl
3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 # Copyright 2010 BibLibre
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21 # pragma
22 use Modern::Perl;
24 # external modules
25 use CGI qw ( -utf8 );
26 use List::MoreUtils qw/uniq/;
28 # internal modules
29 use C4::Auth;
30 use C4::Context;
31 use C4::Output;
32 use C4::Members;
33 use C4::Members::Attributes;
34 use C4::Members::AttributeTypes;
35 use C4::Koha;
36 use C4::Log;
37 use C4::Letters;
38 use C4::Form::MessagingPreferences;
39 use Koha::AuthUtils;
40 use Koha::AuthorisedValues;
41 use Koha::Patron::Debarments;
42 use Koha::Cities;
43 use Koha::DateUtils;
44 use Koha::Libraries;
45 use Koha::Patrons;
46 use Koha::Patron::Categories;
47 use Koha::Patron::HouseboundRole;
48 use Koha::Patron::HouseboundRoles;
49 use Koha::Token;
50 use Email::Valid;
51 use Module::Load;
52 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
53 load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
55 use Koha::SMS::Providers;
57 use vars qw($debug);
59 BEGIN {
60 $debug = $ENV{DEBUG} || 0;
63 my $input = new CGI;
64 ($debug) or $debug = $input->param('debug') || 0;
65 my %data;
67 my $dbh = C4::Context->dbh;
69 my ($template, $loggedinuser, $cookie)
70 = get_template_and_user({template_name => "members/memberentrygen.tt",
71 query => $input,
72 type => "intranet",
73 authnotrequired => 0,
74 flagsrequired => {borrowers => 'edit_borrowers'},
75 debug => ($debug) ? 1 : 0,
76 });
78 my $borrowernumber = $input->param('borrowernumber');
79 my $patron = Koha::Patrons->find($borrowernumber);
81 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
82 my @providers = Koha::SMS::Providers->search();
83 $template->param( sms_providers => \@providers );
86 my $guarantorid = $input->param('guarantorid');
87 my $actionType = $input->param('actionType') || '';
88 my $modify = $input->param('modify');
89 my $delete = $input->param('delete');
90 my $op = $input->param('op');
91 my $destination = $input->param('destination');
92 my $cardnumber = $input->param('cardnumber');
93 my $check_member = $input->param('check_member');
94 my $nodouble = $input->param('nodouble');
95 my $duplicate = $input->param('duplicate');
96 my $quickadd = $input->param('quickadd');
97 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
98 # modifying an existing patron, it ipso facto
99 # isn't a duplicate. Marking FIXME because this
100 # script needs to be refactored.
101 my $nok = $input->param('nok');
102 my $guarantorinfo = $input->param('guarantorinfo');
103 my $step = $input->param('step') || 0;
104 my @errors;
105 my $borrower_data;
106 my $NoUpdateLogin;
107 my $userenv = C4::Context->userenv;
109 ## Deal with debarments
110 $template->param(
111 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
112 my @debarments_to_remove = $input->multi_param('remove_debarment');
113 foreach my $d ( @debarments_to_remove ) {
114 DelDebarment( $d );
116 if ( $input->param('add_debarment') ) {
118 my $expiration = $input->param('debarred_expiration');
119 $expiration =
120 $expiration
121 ? dt_from_string($expiration)->ymd
122 : undef;
124 AddDebarment(
126 borrowernumber => $borrowernumber,
127 type => 'MANUAL',
128 comment => scalar $input->param('debarred_comment'),
129 expiration => $expiration,
134 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
136 # function to designate mandatory fields (visually with css)
137 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
138 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
139 foreach (@field_check) {
140 $template->param( "mandatory$_" => 1);
142 # function to designate unwanted fields
143 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
144 @field_check=split(/\|/,$check_BorrowerUnwantedField);
145 foreach (@field_check) {
146 next unless m/\w/o;
147 $template->param( "no$_" => 1);
149 $template->param( "add" => 1 ) if ( $op eq 'add' );
150 $template->param( "quickadd" => 1 ) if ( $quickadd );
151 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
152 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
153 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
154 my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
155 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
157 $borrower_data = $patron->unblessed;
158 $borrower_data->{category_type} = $patron->category->category_type;
159 } else {
160 $patron = Koha::Patron->new;
162 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
163 my $category_type = $input->param('category_type') || '';
164 unless ($category_type or !($categorycode)){
165 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
166 $category_type = $borrowercategory->category_type;
167 my $category_name = $borrowercategory->description;
168 $template->param("categoryname"=>$category_name);
170 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
172 # if a add or modify is requested => check validity of data.
173 %data = %$borrower_data if ($borrower_data);
175 # initialize %newdata
176 my %newdata; # comes from $input->param()
177 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
178 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
179 foreach my $key (@names) {
180 if (defined $input->param($key)) {
181 $newdata{$key} = $input->param($key);
182 $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
186 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
187 next unless exists $newdata{$_};
188 my $userdate = $newdata{$_} or next;
190 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
191 if ( $formatteddate ) {
192 $newdata{$_} = $formatteddate;
193 } else {
194 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
195 $template->param( "ERROR_$_" => 1 );
196 push(@errors,"ERROR_$_");
199 # check permission to modify login info.
200 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
201 $NoUpdateLogin = 1;
205 # remove keys from %newdata that ModMember() doesn't like
207 my @keys_to_delete = (
208 qr/^BorrowerMandatoryField$/,
209 qr/^category_type$/,
210 qr/^check_member$/,
211 qr/^destination$/,
212 qr/^nodouble$/,
213 qr/^op$/,
214 qr/^save$/,
215 qr/^updtype$/,
216 qr/^SMSnumber$/,
217 qr/^setting_extended_patron_attributes$/,
218 qr/^setting_messaging_prefs$/,
219 qr/^digest$/,
220 qr/^modify$/,
221 qr/^step$/,
222 qr/^\d+$/,
223 qr/^\d+-DAYS/,
224 qr/^patron_attr_/,
226 for my $regexp (@keys_to_delete) {
227 for (keys %newdata) {
228 delete($newdata{$_}) if /$regexp/;
233 # Test uniqueness of surname, firstname and dateofbirth
234 if ( ( $op eq 'insert' ) and !$nodouble ) {
235 my $conditions;
236 $conditions->{surname} = $newdata{surname} if $newdata{surname};
237 if ( $category_type ne 'I' ) {
238 $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
239 $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
241 $nodouble = 1;
242 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
243 if ( $patrons->count > 0) {
244 $nodouble = 0;
245 $check_member = $patrons->next->borrowernumber;
249 #recover all data from guarantor address phone ,fax...
250 if ( $guarantorid ) {
251 if (my $guarantor = Koha::Patrons->find( $guarantorid )) {
252 my $guarantordata = $guarantor->unblessed;
253 $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
254 $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
255 $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
256 $newdata{'contactname'} = $guarantordata->{'surname'};
257 $newdata{'contacttitle'} = $guarantordata->{'title'};
258 if ( $op eq 'add' ) {
259 foreach (qw(streetnumber address streettype address2
260 zipcode country city state phone phonepro mobile fax email emailpro branchcode
261 B_streetnumber B_streettype B_address B_address2
262 B_city B_state B_zipcode B_country B_email B_phone)) {
263 $newdata{$_} = $guarantordata->{$_};
269 ###############test to take the right zipcode, country and city name ##############
270 # set only if parameter was passed from the form
271 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
272 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
273 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
275 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
277 # builds default userid
278 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
279 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
280 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
281 # Full page edit, firstname and surname input zones are present
282 $patron->firstname($newdata{firstname});
283 $patron->surname($newdata{surname});
284 $newdata{'userid'} = $patron->generate_userid;
286 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
287 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
288 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
289 # FIXME clean thiscode newdata vs data is very confusing
290 $patron->firstname($data{firstname});
291 $patron->surname($data{surname});
292 $newdata{'userid'} = $patron->generate_userid;
294 else {
295 $newdata{'userid'} = $data{'userid'};
299 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
300 my $extended_patron_attributes = ();
301 if ($op eq 'save' || $op eq 'insert'){
303 die "Wrong CSRF token"
304 unless Koha::Token->new->check_csrf({
305 session_id => scalar $input->cookie('CGISESSID'),
306 token => scalar $input->param('csrf_token'),
309 # If the cardnumber is blank, treat it as null.
310 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
312 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
313 push @errors, $error_code == 1
314 ? 'ERROR_cardnumber_already_exists'
315 : $error_code == 2
316 ? 'ERROR_cardnumber_length'
317 : ()
320 my $dateofbirth;
321 if ($op eq 'save' && $step == 3) {
322 $dateofbirth = $patron->dateofbirth;
324 else {
325 $dateofbirth = $newdata{dateofbirth};
328 if ( $dateofbirth ) {
329 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
330 my $age = $patron->get_age;
331 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
332 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
333 if (($high && ($age > $high)) or ($age < $low)) {
334 push @errors, 'ERROR_age_limitations';
335 $template->param( age_low => $low);
336 $template->param( age_high => $high);
340 if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
341 $newdata{'surname'} = uc($newdata{'surname'});
344 if (C4::Context->preference("IndependentBranches")) {
345 unless ( C4::Context->IsSuperLibrarian() ){
346 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
347 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
348 push @errors, "ERROR_branch";
352 # Check if the 'userid' is unique. 'userid' might not always be present in
353 # the edited values list when editing certain sub-forms. Get it straight
354 # from the DB if absent.
355 my $userid = $newdata{ userid } // $borrower_data->{ userid };
356 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new;
357 $p->userid( $userid );
358 unless ( $p->has_valid_userid ) {
359 push @errors, "ERROR_login_exist";
362 my $password = $input->param('password');
363 my $password2 = $input->param('password2');
364 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
366 if ( $password and $password ne '****' ) {
367 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
368 unless ( $is_valid ) {
369 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
370 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
371 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
375 # Validate emails
376 my $emailprimary = $input->param('email');
377 my $emailsecondary = $input->param('emailpro');
378 my $emailalt = $input->param('B_email');
380 if ($emailprimary) {
381 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
383 if ($emailsecondary) {
384 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
386 if ($emailalt) {
387 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
390 if (C4::Context->preference('ExtendedPatronAttributes')) {
391 $extended_patron_attributes = parse_extended_patron_attributes($input);
392 foreach my $attr (@$extended_patron_attributes) {
393 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
394 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
395 push @errors, "ERROR_extended_unique_id_failed";
396 $template->param(
397 ERROR_extended_unique_id_failed_code => $attr->{code},
398 ERROR_extended_unique_id_failed_value => $attr->{value},
399 ERROR_extended_unique_id_failed_description => $attr_info->description()
406 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
407 unless ($newdata{'dateexpiry'}){
408 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
409 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
413 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
414 my $sms = $input->param('SMSnumber');
415 if ( defined $sms ) {
416 $newdata{smsalertnumber} = $sms;
419 ### Error checks should happen before this line.
420 $nok = $nok || scalar(@errors);
421 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
422 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
423 if ($op eq 'insert'){
424 # we know it's not a duplicate borrowernumber or there would already be an error
425 $borrowernumber = &AddMember(%newdata);
426 $newdata{'borrowernumber'} = $borrowernumber;
428 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
429 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
430 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
431 my $emailaddr;
432 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
433 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
434 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
436 elsif ($newdata{email} =~ /\w\@\w/) {
437 $emailaddr = $newdata{email}
439 elsif ($newdata{emailpro} =~ /\w\@\w/) {
440 $emailaddr = $newdata{emailpro}
442 elsif ($newdata{B_email} =~ /\w\@\w/) {
443 $emailaddr = $newdata{B_email}
445 # if we manage to find a valid email address, send notice
446 if ($emailaddr) {
447 $newdata{emailaddr} = $emailaddr;
448 my $err;
449 eval {
450 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
452 if ( $@ ) {
453 $template->param(error_alert => $@);
454 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
455 $template->{VARS}->{'error_alert'} = "no_email";
456 } else {
457 $template->{VARS}->{'info_alert'} = 1;
462 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
463 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
465 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
466 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
468 # Try to do the live sync with the Norwegian national patron database, if it is enabled
469 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
470 NLSync({ 'borrowernumber' => $borrowernumber });
473 # Create HouseboundRole if necessary.
474 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
475 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
476 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
477 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
478 # Only create a HouseboundRole if patron has a role.
479 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
480 Koha::Patron::HouseboundRole->new({
481 borrowernumber_id => $borrowernumber,
482 housebound_chooser => $hsbnd_chooser,
483 housebound_deliverer => $hsbnd_deliverer,
484 })->store;
487 } elsif ($op eq 'save') {
489 # Update or create our HouseboundRole if necessary.
490 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
491 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
492 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
493 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
494 if ( $housebound_role ) {
495 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
496 # Update our HouseboundRole.
497 $housebound_role
498 ->housebound_chooser($hsbnd_chooser)
499 ->housebound_deliverer($hsbnd_deliverer)
500 ->store;
501 } else {
502 $housebound_role->delete; # No longer needed.
504 } else {
505 # Only create a HouseboundRole if patron has a role.
506 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
507 $housebound_role = Koha::Patron::HouseboundRole->new({
508 borrowernumber_id => $borrowernumber,
509 housebound_chooser => $hsbnd_chooser,
510 housebound_deliverer => $hsbnd_deliverer,
511 })->store;
515 if ($NoUpdateLogin) {
516 delete $newdata{'password'};
517 delete $newdata{'userid'};
519 &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
520 # updating any columns in the borrowers table,
521 # which can happen if we're only editing the
522 # patron attributes or messaging preferences sections
523 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
524 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
526 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
527 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
531 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
532 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
533 $destination = 'not_circ';
535 print scalar( $destination eq "circ" )
536 ? $input->redirect(
537 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
538 : $input->redirect(
539 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
541 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
544 if ($delete){
545 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
546 exit; # same as above
549 if ($nok or !$nodouble){
550 $op="add" if ($op eq "insert");
551 $op="modify" if ($op eq "save");
552 %data=%newdata;
553 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
554 unless ($step){
555 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
558 if (C4::Context->preference("IndependentBranches")) {
559 my $userenv = C4::Context->userenv;
560 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
561 unless ($userenv->{branch} eq $data{'branchcode'}){
562 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
563 exit;
567 if ($op eq 'add'){
568 $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
570 if ($op eq "modify") {
571 $template->param( updtype => 'M',modify => 1 );
572 $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
573 if ( $step == 4 ) {
574 $template->param( categorycode => $borrower_data->{'categorycode'} );
576 # Add sync data to the user data
577 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
578 my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
579 if ( $sync ) {
580 $template->param(
581 sync => $sync->sync,
586 if ( $op eq "duplicate" ) {
587 $template->param( updtype => 'I' );
588 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
589 $data{'cardnumber'} = "";
592 if(!defined($data{'sex'})){
593 $template->param( none => 1);
594 } elsif($data{'sex'} eq 'F'){
595 $template->param( female => 1);
596 } elsif ($data{'sex'} eq 'M'){
597 $template->param( male => 1);
598 } else {
599 $template->param( none => 1);
602 ##Now all the data to modify a member.
604 my @typeloop;
605 my $no_categories = 1;
606 my $no_add;
607 foreach my $category_type (qw(C A S P I X)) {
608 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
609 $no_categories = 0 if $patron_categories->count > 0;
611 my @categoryloop;
612 while ( my $patron_category = $patron_categories->next ) {
613 push @categoryloop,
614 { 'categorycode' => $patron_category->categorycode,
615 'categoryname' => $patron_category->description,
616 'categorycodeselected' =>
617 ( ( defined( $borrower_data->{'categorycode'} ) && $patron_category->categorycode eq $borrower_data->{'categorycode'} ) || ( defined($categorycode) && $patron_category->categorycode eq $categorycode ) ),
620 my %typehash;
621 $typehash{'typename'} = $category_type;
622 my $typedescription = "typename_" . $typehash{'typename'};
623 $typehash{'categoryloop'} = \@categoryloop;
624 push @typeloop,
625 { 'typename' => $category_type,
626 $typedescription => 1,
627 'categoryloop' => \@categoryloop
631 $template->param('typeloop' => \@typeloop,
632 no_categories => $no_categories);
633 if($no_categories){ $no_add = 1; }
636 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
637 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
638 $template->param(
639 roadtypes => $roadtypes,
640 cities => $cities,
643 my $default_borrowertitle = '';
644 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
646 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
647 my @relshipdata;
648 while (@relationships) {
649 my $relship = shift @relationships || '';
650 my %row = ('relationship' => $relship);
651 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
652 $row{'selected'}=' selected';
653 } else {
654 $row{'selected'}='';
656 push(@relshipdata, \%row);
659 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
660 'lost' => ['lost']);
663 my @flagdata;
664 foreach (keys(%flags)) {
665 my $key = $_;
666 my %row = ('key' => $key,
667 'name' => $flags{$key}[0]);
668 if ($data{$key}) {
669 $row{'yes'}=' checked';
670 $row{'no'}='';
672 else {
673 $row{'yes'}='';
674 $row{'no'}=' checked';
676 push @flagdata,\%row;
679 # get Branch Loop
680 # in modify mod: userbranch value comes from borrowers table
681 # in add mod: userbranch value comes from branches table (ip correspondence)
683 my $userbranch = '';
684 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
685 $userbranch = C4::Context->userenv->{'branch'};
688 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
689 $userbranch = $data{'branchcode'};
691 $template->param( userbranch => $userbranch );
693 if ( Koha::Libraries->search->count < 1 ){
694 $no_add = 1;
695 $template->param(no_branches => 1);
697 if($no_categories){
698 $no_add = 1;
699 $template->param(no_categories => 1);
701 $template->param(no_add => $no_add);
702 # --------------------------------------------------------------------------------------------------------
704 $template->param( sort1 => $data{'sort1'});
705 $template->param( sort2 => $data{'sort2'});
707 if ($nok) {
708 foreach my $error (@errors) {
709 $template->param($error) || $template->param( $error => 1);
711 $template->param(nok => 1);
714 #Formatting data for display
716 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
717 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
719 if ( $op eq 'duplicate' ) {
720 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
721 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
722 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
724 if (C4::Context->preference('uppercasesurnames')) {
725 $data{'surname'} &&= uc( $data{'surname'} );
726 $data{'contactname'} &&= uc( $data{'contactname'} );
729 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
730 if ( $data{$_} ) {
731 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
733 $template->param( $_ => $data{$_});
736 if (C4::Context->preference('ExtendedPatronAttributes')) {
737 $template->param(ExtendedPatronAttributes => 1);
738 patron_attributes_form($template, $borrowernumber);
741 if (C4::Context->preference('EnhancedMessagingPreferences')) {
742 if ($op eq 'add') {
743 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
744 } else {
745 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
747 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
748 $template->param(SMSnumber => $data{'smsalertnumber'} );
749 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
752 $template->param( "showguarantor" => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
753 $debug and warn "memberentry step: $step";
754 $template->param(%data);
755 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
756 $template->param( step => $step ) if $step; # associate with step to know where u are
758 $template->param(
759 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
760 category_type => $category_type,#to know the category type of the borrower
761 "$category_type" => 1,# associate with step to know where u are
762 destination => $destination,#to know wher u come from and wher u must go in redirect
763 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
764 "op$op" => 1);
766 $guarantorid = $borrower_data->{'guarantorid'} || $guarantorid;
767 my $guarantor = $guarantorid ? Koha::Patrons->find( $guarantorid ) : undef;
768 $template->param(
769 patron => $patron, # Used by address include templates now
770 nodouble => $nodouble,
771 borrowernumber => $borrowernumber, #register number
772 guarantor => $guarantor,
773 guarantorid => $guarantorid,
774 relshiploop => \@relshipdata,
775 btitle=> $default_borrowertitle,
776 guarantorinfo => $guarantorinfo,
777 flagloop => \@flagdata,
778 category_type =>$category_type,
779 modify => $modify,
780 nok => $nok,#flag to know if an error
781 NoUpdateLogin => $NoUpdateLogin,
784 # Generate CSRF token
785 $template->param( csrf_token =>
786 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
789 # HouseboundModule data
790 $template->param(
791 housebound_role => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
794 if(defined($data{'flags'})){
795 $template->param(flags=>$data{'flags'});
797 if(defined($data{'contacttitle'})){
798 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
802 my ( $min, $max ) = C4::Members::get_cardnumber_length();
803 if ( defined $min ) {
804 $template->param(
805 minlength_cardnumber => $min,
806 maxlength_cardnumber => $max
810 if ( C4::Context->preference('TranslateNotices') ) {
811 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
812 $template->param( languages => $translated_languages );
815 output_html_with_http_headers $input, $cookie, $template->output;
817 sub parse_extended_patron_attributes {
818 my ($input) = @_;
819 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
821 my @attr = ();
822 my %dups = ();
823 foreach my $key (@patron_attr) {
824 my $value = $input->param($key);
825 next unless defined($value) and $value ne '';
826 my $code = $input->param("${key}_code");
827 next if exists $dups{$code}->{$value};
828 $dups{$code}->{$value} = 1;
829 push @attr, { code => $code, value => $value };
831 return \@attr;
834 sub patron_attributes_form {
835 my $template = shift;
836 my $borrowernumber = shift;
838 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
839 if (scalar(@types) == 0) {
840 $template->param(no_patron_attribute_types => 1);
841 return;
843 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
844 my @classes = uniq( map {$_->{class}} @$attributes );
845 @classes = sort @classes;
847 # map patron's attributes into a more convenient structure
848 my %attr_hash = ();
849 foreach my $attr (@$attributes) {
850 push @{ $attr_hash{$attr->{code}} }, $attr;
853 my @attribute_loop = ();
854 my $i = 0;
855 my %items_by_class;
856 foreach my $type_code (map { $_->{code} } @types) {
857 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
858 my $entry = {
859 class => $attr_type->class(),
860 code => $attr_type->code(),
861 description => $attr_type->description(),
862 repeatable => $attr_type->repeatable(),
863 category => $attr_type->authorised_value_category(),
864 category_code => $attr_type->category_code(),
866 if (exists $attr_hash{$attr_type->code()}) {
867 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
868 my $newentry = { %$entry };
869 $newentry->{value} = $attr->{value};
870 $newentry->{use_dropdown} = 0;
871 if ($attr_type->authorised_value_category()) {
872 $newentry->{use_dropdown} = 1;
873 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
875 $i++;
876 $newentry->{form_id} = "patron_attr_$i";
877 push @{$items_by_class{$attr_type->class()}}, $newentry;
879 } else {
880 $i++;
881 my $newentry = { %$entry };
882 if ($attr_type->authorised_value_category()) {
883 $newentry->{use_dropdown} = 1;
884 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
886 $newentry->{form_id} = "patron_attr_$i";
887 push @{$items_by_class{$attr_type->class()}}, $newentry;
890 while ( my ($class, @items) = each %items_by_class ) {
891 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
892 my $lib = $av->count ? $av->next->lib : $class;
893 push @attribute_loop, {
894 class => $class,
895 items => @items,
896 lib => $lib,
900 $template->param(patron_attributes => \@attribute_loop);
904 # Local Variables:
905 # tab-width: 8
906 # End: