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>.
26 use List::MoreUtils qw/uniq/;
33 use C4::Members::Attributes;
34 use C4::Members::AttributeTypes;
38 use C4::Form::MessagingPreferences;
40 use Koha::AuthorisedValues;
41 use Koha::Patron::Debarments;
46 use Koha::Patron::Categories;
47 use Koha::Patron::HouseboundRole;
48 use Koha::Patron::HouseboundRoles;
51 use Koha::SMS::Providers;
56 $debug = $ENV{DEBUG} || 0;
60 ($debug) or $debug = $input->param('debug') || 0;
63 my $dbh = C4::Context->dbh;
65 my ($template, $loggedinuser, $cookie)
66 = get_template_and_user({template_name => "members/memberentrygen.tt",
70 flagsrequired => {borrowers => 'edit_borrowers'},
71 debug => ($debug) ? 1 : 0,
74 my $borrowernumber = $input->param('borrowernumber');
75 my $patron = Koha::Patrons->find($borrowernumber);
77 if ( $borrowernumber and not $patron ) {
78 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
81 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
82 my @providers = Koha::SMS::Providers->search();
83 $template->param( sms_providers => \@providers );
86 my $actionType = $input->param('actionType') || '';
87 my $modify = $input->param('modify');
88 my $delete = $input->param('delete');
89 my $op = $input->param('op');
90 my $destination = $input->param('destination');
91 my $cardnumber = $input->param('cardnumber');
92 my $check_member = $input->param('check_member');
93 my $nodouble = $input->param('nodouble');
94 my $duplicate = $input->param('duplicate');
95 my $quickadd = $input->param('quickadd');
96 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
97 # modifying an existing patron, it ipso facto
98 # isn't a duplicate. Marking FIXME because this
99 # script needs to be refactored.
100 my $nok = $input->param('nok');
101 my $step = $input->param('step') || 0;
105 my $userenv = C4::Context->userenv;
108 ## Deal with guarantor stuff
109 $template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
111 my $guarantor_id = $input->param('guarantor_id');
112 my $guarantor = undef;
113 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
114 $template->param( guarantor => $guarantor );
116 my @delete_guarantor = $input->multi_param('delete_guarantor');
117 foreach my $id ( @delete_guarantor ) {
118 my $r = Koha::Patron::Relationships->find( $id );
122 ## Deal with debarments
124 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
125 my @debarments_to_remove = $input->multi_param('remove_debarment');
126 foreach my $d ( @debarments_to_remove ) {
129 if ( $input->param('add_debarment') ) {
131 my $expiration = $input->param('debarred_expiration');
134 ? dt_from_string($expiration)->ymd
139 borrowernumber => $borrowernumber,
141 comment => scalar $input->param('debarred_comment'),
142 expiration => $expiration,
147 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
149 # function to designate mandatory fields (visually with css)
150 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
151 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
152 foreach (@field_check) {
153 $template->param( "mandatory$_" => 1 );
155 # function to designate unwanted fields
156 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
157 @field_check=split(/\|/,$check_BorrowerUnwantedField);
158 foreach (@field_check) {
160 $template->param( "no$_" => 1 );
162 $template->param( "add" => 1 ) if ( $op eq 'add' );
163 $template->param( "quickadd" => 1 ) if ( $quickadd );
164 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
165 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
166 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
167 my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
168 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
170 $borrower_data = $patron->unblessed;
171 $borrower_data->{category_type} = $patron->category->category_type;
174 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
175 my $category_type = $input->param('category_type') || '';
176 unless ($category_type or !($categorycode)){
177 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
178 $category_type = $borrowercategory->category_type;
179 my $category_name = $borrowercategory->description;
180 $template->param("categoryname"=>$category_name);
182 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
184 # if a add or modify is requested => check validity of data.
185 %data = %$borrower_data if ($borrower_data);
187 # initialize %newdata
188 my %newdata; # comes from $input->param()
189 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
190 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
191 foreach my $key (@names) {
192 if (defined $input->param($key)) {
193 $newdata{$key} = $input->param($key);
197 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
198 next unless exists $newdata{$_};
199 my $userdate = $newdata{$_} or next;
201 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
202 if ( $formatteddate ) {
203 $newdata{$_} = $formatteddate;
205 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
206 $template->param( "ERROR_$_" => 1 );
207 push(@errors,"ERROR_$_");
210 # check permission to modify login info.
211 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
216 # remove keys from %newdata that is not part of patron's attributes
218 my @keys_to_delete = (
219 qr/^BorrowerMandatoryField$/,
228 qr/^setting_extended_patron_attributes$/,
229 qr/^setting_messaging_prefs$/,
237 qr/^add_debarment$/, qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
238 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
241 qr/^guarantor_firstname$/,
242 qr/^guarantor_surname$/,
243 qr/^delete_guarantor$/,
245 for my $regexp (@keys_to_delete) {
246 for (keys %newdata) {
247 delete($newdata{$_}) if /$regexp/;
252 # Test uniqueness of surname, firstname and dateofbirth
253 if ( ( $op eq 'insert' ) and !$nodouble ) {
255 $conditions->{surname} = $newdata{surname} if $newdata{surname};
256 if ( $category_type ne 'I' ) {
257 $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
258 $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
261 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
262 if ( $patrons->count > 0) {
264 $check_member = $patrons->next->borrowernumber;
268 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
269 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
270 foreach my $gid ( @new_guarantor_id ) {
271 my $patron = Koha::Patrons->find( $gid );
272 my $relationship = shift( @new_guarantor_relationship );
274 my $g = { patron => $patron, relationship => $relationship };
275 push( @new_guarantors, $g );
277 $template->param( new_guarantors => \@new_guarantors );
281 ###############test to take the right zipcode, country and city name ##############
282 # set only if parameter was passed from the form
283 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
284 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
285 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
287 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
289 # builds default userid
290 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
291 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
292 my $fake_patron = Koha::Patron->new;
293 $fake_patron->userid($patron->userid) if $patron; # editing
294 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
295 # Full page edit, firstname and surname input zones are present
296 $fake_patron->firstname($newdata{firstname});
297 $fake_patron->surname($newdata{surname});
298 $fake_patron->generate_userid;
299 $newdata{'userid'} = $fake_patron->userid;
301 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
302 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
303 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
304 # FIXME clean thiscode newdata vs data is very confusing
305 $fake_patron->firstname($data{firstname});
306 $fake_patron->surname($data{surname});
307 $fake_patron->generate_userid;
308 $newdata{'userid'} = $fake_patron->userid;
311 $newdata{'userid'} = $data{'userid'};
315 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
316 my $extended_patron_attributes = ();
317 if ($op eq 'save' || $op eq 'insert'){
319 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
320 unless Koha::Token->new->check_csrf({
321 session_id => scalar $input->cookie('CGISESSID'),
322 token => scalar $input->param('csrf_token'),
325 # If the cardnumber is blank, treat it as null.
326 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
328 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
329 push @errors, $error_code == 1
330 ? 'ERROR_cardnumber_already_exists'
332 ? 'ERROR_cardnumber_length'
337 if ($op eq 'save' && $step == 3) {
338 $dateofbirth = $patron->dateofbirth;
341 $dateofbirth = $newdata{dateofbirth};
344 if ( $dateofbirth ) {
345 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
346 my $age = $patron->get_age;
347 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
348 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
349 if (($high && ($age > $high)) or ($age < $low)) {
350 push @errors, 'ERROR_age_limitations';
351 $template->param( age_low => $low);
352 $template->param( age_high => $high);
356 if (C4::Context->preference("IndependentBranches")) {
357 unless ( C4::Context->IsSuperLibrarian() ){
358 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
359 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
360 push @errors, "ERROR_branch";
364 # Check if the 'userid' is unique. 'userid' might not always be present in
365 # the edited values list when editing certain sub-forms. Get it straight
366 # from the DB if absent.
367 my $userid = $newdata{ userid } // $borrower_data->{ userid };
368 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new;
369 $p->userid( $userid );
370 unless ( $p->has_valid_userid ) {
371 push @errors, "ERROR_login_exist";
374 my $password = $input->param('password');
375 my $password2 = $input->param('password2');
376 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
378 if ( $password and $password ne '****' ) {
379 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
380 unless ( $is_valid ) {
381 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
382 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
383 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
388 my $emailprimary = $input->param('email');
389 my $emailsecondary = $input->param('emailpro');
390 my $emailalt = $input->param('B_email');
393 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
395 if ($emailsecondary) {
396 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
399 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
402 if (C4::Context->preference('ExtendedPatronAttributes')) {
403 $extended_patron_attributes = parse_extended_patron_attributes($input);
404 foreach my $attr (@$extended_patron_attributes) {
405 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
406 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
407 push @errors, "ERROR_extended_unique_id_failed";
409 ERROR_extended_unique_id_failed_code => $attr->{code},
410 ERROR_extended_unique_id_failed_value => $attr->{value},
411 ERROR_extended_unique_id_failed_description => $attr_info->description()
418 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
419 unless ($newdata{'dateexpiry'}){
420 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
421 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
425 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
426 my $sms = $input->param('SMSnumber');
427 if ( defined $sms ) {
428 $newdata{smsalertnumber} = $sms;
431 ### Error checks should happen before this line.
432 $nok = $nok || scalar(@errors);
433 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
434 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
436 if ($op eq 'insert'){
437 # we know it's not a duplicate borrowernumber or there would already be an error
438 delete $newdata{password2};
439 my $patron = eval { Koha::Patron->new(\%newdata)->store };
441 # FIXME Urgent error handling here, we cannot fail without relevant feedback
442 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
443 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
444 push @messages, {error => 'error_on_insert_patron'};
448 add_guarantors( $patron, $input );
449 $borrowernumber = $patron->borrowernumber;
450 $newdata{'borrowernumber'} = $borrowernumber;
453 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
454 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
455 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
457 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
458 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
459 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
461 elsif ($newdata{email} =~ /\w\@\w/) {
462 $emailaddr = $newdata{email}
464 elsif ($newdata{emailpro} =~ /\w\@\w/) {
465 $emailaddr = $newdata{emailpro}
467 elsif ($newdata{B_email} =~ /\w\@\w/) {
468 $emailaddr = $newdata{B_email}
470 # if we manage to find a valid email address, send notice
472 $newdata{emailaddr} = $emailaddr;
475 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
478 $template->param(error_alert => $@);
479 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
480 $template->{VARS}->{'error_alert'} = "no_email";
482 $template->{VARS}->{'info_alert'} = 1;
487 if ($patron && C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
488 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
490 if ($patron && C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
491 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
494 # Create HouseboundRole if necessary.
495 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
496 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
497 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
498 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
499 # Only create a HouseboundRole if patron has a role.
500 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
501 Koha::Patron::HouseboundRole->new({
502 borrowernumber_id => $borrowernumber,
503 housebound_chooser => $hsbnd_chooser,
504 housebound_deliverer => $hsbnd_deliverer,
508 } elsif ($op eq 'save') {
510 if ($NoUpdateLogin) {
511 delete $newdata{'password'};
512 delete $newdata{'userid'};
515 my $patron = Koha::Patrons->find( $borrowernumber );
516 $newdata{debarredcomment} = $newdata{debarred_comment};
517 delete $newdata{debarred_comment};
518 delete $newdata{password2};
521 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
522 # updating any columns in the borrowers table,
523 # which can happen if we're only editing the
524 # patron attributes or messaging preferences sections
527 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
528 push @messages, {error => 'error_on_update_patron'};
533 # Update or create our HouseboundRole if necessary.
534 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
535 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
536 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
537 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
538 if ( $housebound_role ) {
539 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
540 # Update our HouseboundRole.
542 ->housebound_chooser($hsbnd_chooser)
543 ->housebound_deliverer($hsbnd_deliverer)
546 $housebound_role->delete; # No longer needed.
549 # Only create a HouseboundRole if patron has a role.
550 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
551 $housebound_role = Koha::Patron::HouseboundRole->new({
552 borrowernumber_id => $borrowernumber,
553 housebound_chooser => $hsbnd_chooser,
554 housebound_deliverer => $hsbnd_deliverer,
559 # should never raise an exception as password validity is checked above
560 my $password = $newdata{password};
561 if ( $password and $password ne '****' ) {
562 $patron->set_password({ password => $password });
565 add_guarantors( $patron, $input );
566 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
567 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
573 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
574 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
577 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
578 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
579 $destination = 'not_circ';
581 print scalar( $destination eq "circ" )
583 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
585 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
587 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
592 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
593 exit; # same as above
596 if ($nok or !$nodouble){
597 $op="add" if ($op eq "insert");
598 $op="modify" if ($op eq "save");
600 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
602 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
605 if (C4::Context->preference("IndependentBranches")) {
606 my $userenv = C4::Context->userenv;
607 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
608 unless ($userenv->{branch} eq $data{'branchcode'}){
609 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
618 streetnumber address streettype address2 zipcode country city state phone phonepro mobile
619 fax email emailpro branchcode
620 B_streetnumber B_streettype B_address B_address2
621 B_city B_state B_zipcode B_country B_email B_phone
625 $newdata{$_} = $guarantor->$_;
628 $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1, step_7 => 1);
630 if ($op eq "modify") {
631 $template->param( updtype => 'M',modify => 1 );
632 $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1, step_7 => 1) unless $step;
634 $template->param( categorycode => $borrower_data->{'categorycode'} );
637 if ( $op eq "duplicate" ) {
638 $template->param( updtype => 'I' );
639 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 ) unless $step;
640 $data{'cardnumber'} = "";
643 if(!defined($data{'sex'})){
644 $template->param( none => 1);
645 } elsif($data{'sex'} eq 'F'){
646 $template->param( female => 1);
647 } elsif ($data{'sex'} eq 'M'){
648 $template->param( male => 1);
650 $template->param( none => 1);
653 ##Now all the data to modify a member.
656 my $no_categories = 1;
658 foreach my $category_type (qw(C A S P I X)) {
659 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
660 $no_categories = 0 if $patron_categories->count > 0;
663 while ( my $patron_category = $patron_categories->next ) {
665 { 'categorycode' => $patron_category->categorycode,
666 'categoryname' => $patron_category->description,
667 'categorycodeselected' =>
668 ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
672 $typehash{'typename'} = $category_type;
673 my $typedescription = "typename_" . $typehash{'typename'};
674 $typehash{'categoryloop'} = \@categoryloop;
676 { 'typename' => $category_type,
677 $typedescription => 1,
678 'categoryloop' => \@categoryloop
682 typeloop => \@typeloop,
683 no_categories => $no_categories,
686 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
687 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
689 roadtypes => $roadtypes,
693 my $default_borrowertitle = '';
694 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
696 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
698 while (@relationships) {
699 my $relship = shift @relationships || '';
700 my %row = ('relationship' => $relship);
701 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
702 $row{'selected'}=' selected';
706 push(@relshipdata, \%row);
710 'gonenoaddress' => ['gonenoaddress'],
715 foreach ( keys(%flags) ) {
719 'name' => $flags{$key}[0]
722 $row{'yes'} = ' checked';
727 $row{'no'} = ' checked';
729 push @flagdata, \%row;
733 # in modify mod: userbranch value comes from borrowers table
734 # in add mod: userbranch value comes from branches table (ip correspondence)
737 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
738 $userbranch = C4::Context->userenv->{'branch'};
741 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
742 $userbranch = $data{'branchcode'};
744 $template->param( userbranch => $userbranch );
746 if ( Koha::Libraries->search->count < 1 ){
748 $template->param(no_branches => 1);
752 $template->param(no_categories => 1);
754 $template->param(no_add => $no_add);
755 # --------------------------------------------------------------------------------------------------------
757 $template->param( sort1 => $data{'sort1'});
758 $template->param( sort2 => $data{'sort2'});
761 foreach my $error (@errors) {
762 $template->param($error) || $template->param( $error => 1);
764 $template->param(nok => 1);
767 #Formatting data for display
769 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
770 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
772 if ( $op eq 'duplicate' ) {
773 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
774 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
775 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
777 if (C4::Context->preference('uppercasesurnames')) {
778 $data{'surname'} &&= uc( $data{'surname'} );
779 $data{'contactname'} &&= uc( $data{'contactname'} );
782 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
784 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
786 $template->param( $_ => $data{$_});
789 if (C4::Context->preference('ExtendedPatronAttributes')) {
790 patron_attributes_form($template, $borrowernumber, $op);
793 if (C4::Context->preference('EnhancedMessagingPreferences')) {
795 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
797 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
799 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
800 $template->param(SMSnumber => $data{'smsalertnumber'} );
801 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
804 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
805 $debug and warn "memberentry step: $step";
806 $template->param(%data);
807 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
808 $template->param( step => $step ) if $step; # associate with step to know where u are
811 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
812 category_type => $category_type,#to know the category type of the borrower
813 "$category_type" => 1,# associate with step to know where u are
814 destination => $destination,#to know wher u come from and wher u must go in redirect
815 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
819 patron => $patron ? $patron : \%newdata, # Used by address include templates now
820 nodouble => $nodouble,
821 borrowernumber => $borrowernumber, #register number
822 relshiploop => \@relshipdata,
823 btitle=> $default_borrowertitle,
824 flagloop => \@flagdata,
825 category_type =>$category_type,
827 nok => $nok,#flag to know if an error
828 NoUpdateLogin => $NoUpdateLogin,
831 # Generate CSRF token
832 $template->param( csrf_token =>
833 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
836 # HouseboundModule data
838 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
841 if(defined($data{'flags'})){
842 $template->param(flags=>$data{'flags'});
844 if(defined($data{'contacttitle'})){
845 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
849 my ( $min, $max ) = C4::Members::get_cardnumber_length();
850 if ( defined $min ) {
852 minlength_cardnumber => $min,
853 maxlength_cardnumber => $max
857 if ( C4::Context->preference('TranslateNotices') ) {
858 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
859 $template->param( languages => $translated_languages );
862 $template->param( messages => \@messages );
863 output_html_with_http_headers $input, $cookie, $template->output;
865 sub parse_extended_patron_attributes {
867 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
871 foreach my $key (@patron_attr) {
872 my $value = $input->param($key);
873 next unless defined($value) and $value ne '';
874 my $code = $input->param("${key}_code");
875 next if exists $dups{$code}->{$value};
876 $dups{$code}->{$value} = 1;
877 push @attr, { code => $code, value => $value };
882 sub patron_attributes_form {
883 my $template = shift;
884 my $borrowernumber = shift;
887 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
888 if (scalar(@types) == 0) {
889 $template->param(no_patron_attribute_types => 1);
892 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
893 my @classes = uniq( map {$_->{class}} @$attributes );
894 @classes = sort @classes;
896 # map patron's attributes into a more convenient structure
898 foreach my $attr (@$attributes) {
899 push @{ $attr_hash{$attr->{code}} }, $attr;
902 my @attribute_loop = ();
905 foreach my $type_code (map { $_->{code} } @types) {
906 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
908 class => $attr_type->class(),
909 code => $attr_type->code(),
910 description => $attr_type->description(),
911 repeatable => $attr_type->repeatable(),
912 category => $attr_type->authorised_value_category(),
913 category_code => $attr_type->category_code(),
915 if (exists $attr_hash{$attr_type->code()}) {
916 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
917 my $newentry = { %$entry };
918 $newentry->{value} = $attr->{value};
919 $newentry->{use_dropdown} = 0;
920 if ($attr_type->authorised_value_category()) {
921 $newentry->{use_dropdown} = 1;
922 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
925 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
926 $newentry->{form_id} = "patron_attr_$i";
927 push @{$items_by_class{$attr_type->class()}}, $newentry;
931 my $newentry = { %$entry };
932 if ($attr_type->authorised_value_category()) {
933 $newentry->{use_dropdown} = 1;
934 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
936 $newentry->{form_id} = "patron_attr_$i";
937 push @{$items_by_class{$attr_type->class()}}, $newentry;
940 while ( my ($class, @items) = each %items_by_class ) {
941 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
942 my $lib = $av->count ? $av->next->lib : $class;
943 push @attribute_loop, {
950 $template->param(patron_attributes => \@attribute_loop);
955 my ( $patron, $input ) = @_;
957 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
958 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
960 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
961 my $guarantor_id = $new_guarantor_id[$i];
962 my $relationship = $new_guarantor_relationship[$i];
964 next unless $guarantor_id;
966 $patron->add_guarantor(
968 guarantor_id => $guarantor_id,
969 relationship => $relationship,