Bug 20434: Add default authority type
[koha.git] / members / memberentry.pl
blobfa5cbe427e22f5c6afe6b5f1439be438f431bea0
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 Koha::SMS::Providers;
53 use vars qw($debug);
55 BEGIN {
56 $debug = $ENV{DEBUG} || 0;
59 my $input = new CGI;
60 ($debug) or $debug = $input->param('debug') || 0;
61 my %data;
63 my $dbh = C4::Context->dbh;
65 my ($template, $loggedinuser, $cookie)
66 = get_template_and_user({template_name => "members/memberentrygen.tt",
67 query => $input,
68 type => "intranet",
69 authnotrequired => 0,
70 flagsrequired => {borrowers => 'edit_borrowers'},
71 debug => ($debug) ? 1 : 0,
72 });
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;
102 my @errors;
103 my $borrower_data;
104 my $NoUpdateLogin;
105 my $userenv = C4::Context->userenv;
107 ## Deal with guarantor stuff
108 $template->param( relationships => scalar $patron->guarantor_relationships ) if $patron;
110 my $guarantor_id = $input->param('guarantor_id');
111 my $guarantor = undef;
112 $guarantor = Koha::Patrons->find( $guarantor_id ) if $guarantor_id;
113 $template->param( guarantor => $guarantor );
115 my @delete_guarantor = $input->multi_param('delete_guarantor');
116 foreach my $id ( @delete_guarantor ) {
117 my $r = Koha::Patron::Relationships->find( $id );
118 $r->delete() if $r;
121 ## Deal with debarments
122 $template->param(
123 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
124 my @debarments_to_remove = $input->multi_param('remove_debarment');
125 foreach my $d ( @debarments_to_remove ) {
126 DelDebarment( $d );
128 if ( $input->param('add_debarment') ) {
130 my $expiration = $input->param('debarred_expiration');
131 $expiration =
132 $expiration
133 ? dt_from_string($expiration)->ymd
134 : undef;
136 AddDebarment(
138 borrowernumber => $borrowernumber,
139 type => 'MANUAL',
140 comment => scalar $input->param('debarred_comment'),
141 expiration => $expiration,
146 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
148 # function to designate mandatory fields (visually with css)
149 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
150 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
151 foreach (@field_check) {
152 $template->param( "mandatory$_" => 1 );
154 # function to designate unwanted fields
155 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
156 @field_check=split(/\|/,$check_BorrowerUnwantedField);
157 foreach (@field_check) {
158 next unless m/\w/o;
159 $template->param( "no$_" => 1 );
161 $template->param( "add" => 1 ) if ( $op eq 'add' );
162 $template->param( "quickadd" => 1 ) if ( $quickadd );
163 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
164 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
165 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
166 my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
167 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
169 $borrower_data = $patron->unblessed;
170 $borrower_data->{category_type} = $patron->category->category_type;
173 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
174 my $category_type = $input->param('category_type') || '';
175 unless ($category_type or !($categorycode)){
176 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
177 $category_type = $borrowercategory->category_type;
178 my $category_name = $borrowercategory->description;
179 $template->param("categoryname"=>$category_name);
181 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
183 # if a add or modify is requested => check validity of data.
184 %data = %$borrower_data if ($borrower_data);
186 # initialize %newdata
187 my %newdata; # comes from $input->param()
188 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
189 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
190 foreach my $key (@names) {
191 if (defined $input->param($key)) {
192 $newdata{$key} = $input->param($key);
196 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
197 next unless exists $newdata{$_};
198 my $userdate = $newdata{$_} or next;
200 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
201 if ( $formatteddate ) {
202 $newdata{$_} = $formatteddate;
203 } else {
204 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
205 $template->param( "ERROR_$_" => 1 );
206 push(@errors,"ERROR_$_");
209 # check permission to modify login info.
210 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
211 $NoUpdateLogin = 1;
215 # remove keys from %newdata that is not part of patron's attributes
217 my @keys_to_delete = (
218 qr/^BorrowerMandatoryField$/,
219 qr/^category_type$/,
220 qr/^check_member$/,
221 qr/^destination$/,
222 qr/^nodouble$/,
223 qr/^op$/,
224 qr/^save$/,
225 qr/^updtype$/,
226 qr/^SMSnumber$/,
227 qr/^setting_extended_patron_attributes$/,
228 qr/^setting_messaging_prefs$/,
229 qr/^digest$/,
230 qr/^modify$/,
231 qr/^step$/,
232 qr/^\d+$/,
233 qr/^\d+-DAYS/,
234 qr/^patron_attr_/,
235 qr/^csrf_token$/,
236 qr/^add_debarment$/, qr/^debarred_expiration$/, qr/^remove_debarment$/, # We already dealt with debarments previously
237 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
238 qr/^select_city$/,
239 qr/^new_guarantor_/,
240 qr/^guarantor_firstname$/,
241 qr/^guarantor_surname$/,
242 qr/^delete_guarantor$/,
244 for my $regexp (@keys_to_delete) {
245 for (keys %newdata) {
246 delete($newdata{$_}) if /$regexp/;
251 # Test uniqueness of surname, firstname and dateofbirth
252 if ( ( $op eq 'insert' ) and !$nodouble ) {
253 my $conditions;
254 $conditions->{surname} = $newdata{surname} if $newdata{surname};
255 if ( $category_type ne 'I' ) {
256 $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
257 $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
259 $nodouble = 1;
260 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
261 if ( $patrons->count > 0) {
262 $nodouble = 0;
263 $check_member = $patrons->next->borrowernumber;
267 ###############test to take the right zipcode, country and city name ##############
268 # set only if parameter was passed from the form
269 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
270 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
271 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
273 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
275 # builds default userid
276 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
277 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
278 my $fake_patron = Koha::Patron->new;
279 $fake_patron->userid($patron->userid) if $patron; # editing
280 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
281 # Full page edit, firstname and surname input zones are present
282 $fake_patron->firstname($newdata{firstname});
283 $fake_patron->surname($newdata{surname});
284 $fake_patron->generate_userid;
285 $newdata{'userid'} = $fake_patron->userid;
287 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
288 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
289 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
290 # FIXME clean thiscode newdata vs data is very confusing
291 $fake_patron->firstname($data{firstname});
292 $fake_patron->surname($data{surname});
293 $fake_patron->generate_userid;
294 $newdata{'userid'} = $fake_patron->userid;
296 else {
297 $newdata{'userid'} = $data{'userid'};
301 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
302 my $extended_patron_attributes = ();
303 if ($op eq 'save' || $op eq 'insert'){
305 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
306 unless Koha::Token->new->check_csrf({
307 session_id => scalar $input->cookie('CGISESSID'),
308 token => scalar $input->param('csrf_token'),
311 # If the cardnumber is blank, treat it as null.
312 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
314 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
315 push @errors, $error_code == 1
316 ? 'ERROR_cardnumber_already_exists'
317 : $error_code == 2
318 ? 'ERROR_cardnumber_length'
319 : ()
322 my $dateofbirth;
323 if ($op eq 'save' && $step == 3) {
324 $dateofbirth = $patron->dateofbirth;
326 else {
327 $dateofbirth = $newdata{dateofbirth};
330 if ( $dateofbirth ) {
331 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
332 my $age = $patron->get_age;
333 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
334 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
335 if (($high && ($age > $high)) or ($age < $low)) {
336 push @errors, 'ERROR_age_limitations';
337 $template->param( age_low => $low);
338 $template->param( age_high => $high);
342 if (C4::Context->preference("IndependentBranches")) {
343 unless ( C4::Context->IsSuperLibrarian() ){
344 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
345 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
346 push @errors, "ERROR_branch";
350 # Check if the 'userid' is unique. 'userid' might not always be present in
351 # the edited values list when editing certain sub-forms. Get it straight
352 # from the DB if absent.
353 my $userid = $newdata{ userid } // $borrower_data->{ userid };
354 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new;
355 $p->userid( $userid );
356 unless ( $p->has_valid_userid ) {
357 push @errors, "ERROR_login_exist";
360 my $password = $input->param('password');
361 my $password2 = $input->param('password2');
362 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
364 if ( $password and $password ne '****' ) {
365 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
366 unless ( $is_valid ) {
367 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
368 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
369 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
373 # Validate emails
374 my $emailprimary = $input->param('email');
375 my $emailsecondary = $input->param('emailpro');
376 my $emailalt = $input->param('B_email');
378 if ($emailprimary) {
379 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
381 if ($emailsecondary) {
382 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
384 if ($emailalt) {
385 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
388 if (C4::Context->preference('ExtendedPatronAttributes')) {
389 $extended_patron_attributes = parse_extended_patron_attributes($input);
390 foreach my $attr (@$extended_patron_attributes) {
391 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
392 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
393 push @errors, "ERROR_extended_unique_id_failed";
394 $template->param(
395 ERROR_extended_unique_id_failed_code => $attr->{code},
396 ERROR_extended_unique_id_failed_value => $attr->{value},
397 ERROR_extended_unique_id_failed_description => $attr_info->description()
404 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
405 unless ($newdata{'dateexpiry'}){
406 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
407 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
411 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
412 my $sms = $input->param('SMSnumber');
413 if ( defined $sms ) {
414 $newdata{smsalertnumber} = $sms;
417 ### Error checks should happen before this line.
418 $nok = $nok || scalar(@errors);
419 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
420 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
421 if ($op eq 'insert'){
422 # we know it's not a duplicate borrowernumber or there would already be an error
423 delete $newdata{password2};
424 my $patron = eval { Koha::Patron->new(\%newdata)->store };
425 if ( $@ ) {
426 # FIXME Urgent error handling here, we cannot fail without relevant feedback
427 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
428 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
429 } else {
430 add_guarantors( $patron, $input );
431 $borrowernumber = $patron->borrowernumber;
432 $newdata{'borrowernumber'} = $borrowernumber;
435 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
436 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
437 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
438 my $emailaddr;
439 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
440 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
441 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
443 elsif ($newdata{email} =~ /\w\@\w/) {
444 $emailaddr = $newdata{email}
446 elsif ($newdata{emailpro} =~ /\w\@\w/) {
447 $emailaddr = $newdata{emailpro}
449 elsif ($newdata{B_email} =~ /\w\@\w/) {
450 $emailaddr = $newdata{B_email}
452 # if we manage to find a valid email address, send notice
453 if ($emailaddr) {
454 $newdata{emailaddr} = $emailaddr;
455 my $err;
456 eval {
457 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
459 if ( $@ ) {
460 $template->param(error_alert => $@);
461 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
462 $template->{VARS}->{'error_alert'} = "no_email";
463 } else {
464 $template->{VARS}->{'info_alert'} = 1;
469 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
470 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
472 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
473 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
476 # Create HouseboundRole if necessary.
477 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
478 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
479 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
480 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
481 # Only create a HouseboundRole if patron has a role.
482 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
483 Koha::Patron::HouseboundRole->new({
484 borrowernumber_id => $borrowernumber,
485 housebound_chooser => $hsbnd_chooser,
486 housebound_deliverer => $hsbnd_deliverer,
487 })->store;
490 } elsif ($op eq 'save') {
492 # Update or create our HouseboundRole if necessary.
493 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
494 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
495 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
496 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
497 if ( $housebound_role ) {
498 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
499 # Update our HouseboundRole.
500 $housebound_role
501 ->housebound_chooser($hsbnd_chooser)
502 ->housebound_deliverer($hsbnd_deliverer)
503 ->store;
504 } else {
505 $housebound_role->delete; # No longer needed.
507 } else {
508 # Only create a HouseboundRole if patron has a role.
509 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
510 $housebound_role = Koha::Patron::HouseboundRole->new({
511 borrowernumber_id => $borrowernumber,
512 housebound_chooser => $hsbnd_chooser,
513 housebound_deliverer => $hsbnd_deliverer,
514 })->store;
518 if ($NoUpdateLogin) {
519 delete $newdata{'password'};
520 delete $newdata{'userid'};
523 my $patron = Koha::Patrons->find( $borrowernumber );
524 $newdata{debarredcomment} = $newdata{debarred_comment};
525 delete $newdata{debarred_comment};
526 delete $newdata{password2};
527 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
528 # updating any columns in the borrowers table,
529 # which can happen if we're only editing the
530 # patron attributes or messaging preferences sections
532 # should never raise an exception as password validity is checked above
533 my $password = $newdata{password};
534 if ( $password and $password ne '****' ) {
535 $patron->set_password({ password => $password });
538 add_guarantors( $patron, $input );
539 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
540 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
542 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
543 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
547 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
548 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
549 $destination = 'not_circ';
551 print scalar( $destination eq "circ" )
552 ? $input->redirect(
553 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
554 : $input->redirect(
555 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
557 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
560 if ($delete){
561 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
562 exit; # same as above
565 if ($nok or !$nodouble){
566 $op="add" if ($op eq "insert");
567 $op="modify" if ($op eq "save");
568 %data=%newdata;
569 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
570 unless ($step){
571 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
574 if (C4::Context->preference("IndependentBranches")) {
575 my $userenv = C4::Context->userenv;
576 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
577 unless ($userenv->{branch} eq $data{'branchcode'}){
578 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
579 exit;
583 if ($op eq 'add'){
584 $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);
586 if ($op eq "modify") {
587 $template->param( updtype => 'M',modify => 1 );
588 $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;
589 if ( $step == 4 ) {
590 $template->param( categorycode => $borrower_data->{'categorycode'} );
593 if ( $op eq "duplicate" ) {
594 $template->param( updtype => 'I' );
595 $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;
596 $data{'cardnumber'} = "";
599 if(!defined($data{'sex'})){
600 $template->param( none => 1);
601 } elsif($data{'sex'} eq 'F'){
602 $template->param( female => 1);
603 } elsif ($data{'sex'} eq 'M'){
604 $template->param( male => 1);
605 } else {
606 $template->param( none => 1);
609 ##Now all the data to modify a member.
611 my @typeloop;
612 my $no_categories = 1;
613 my $no_add;
614 foreach my $category_type (qw(C A S P I X)) {
615 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
616 $no_categories = 0 if $patron_categories->count > 0;
618 my @categoryloop;
619 while ( my $patron_category = $patron_categories->next ) {
620 push @categoryloop,
621 { 'categorycode' => $patron_category->categorycode,
622 'categoryname' => $patron_category->description,
623 'categorycodeselected' =>
624 ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
627 my %typehash;
628 $typehash{'typename'} = $category_type;
629 my $typedescription = "typename_" . $typehash{'typename'};
630 $typehash{'categoryloop'} = \@categoryloop;
631 push @typeloop,
632 { 'typename' => $category_type,
633 $typedescription => 1,
634 'categoryloop' => \@categoryloop
637 $template->param(
638 typeloop => \@typeloop,
639 no_categories => $no_categories,
642 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
643 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
644 $template->param(
645 roadtypes => $roadtypes,
646 cities => $cities,
649 my $default_borrowertitle = '';
650 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
652 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
653 my @relshipdata;
654 while (@relationships) {
655 my $relship = shift @relationships || '';
656 my %row = ('relationship' => $relship);
657 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
658 $row{'selected'}=' selected';
659 } else {
660 $row{'selected'}='';
662 push(@relshipdata, \%row);
665 my %flags = (
666 'gonenoaddress' => ['gonenoaddress'],
667 'lost' => ['lost']
670 my @flagdata;
671 foreach ( keys(%flags) ) {
672 my $key = $_;
673 my %row = (
674 'key' => $key,
675 'name' => $flags{$key}[0]
677 if ( $data{$key} ) {
678 $row{'yes'} = ' checked';
679 $row{'no'} = '';
681 else {
682 $row{'yes'} = '';
683 $row{'no'} = ' checked';
685 push @flagdata, \%row;
688 # get Branch Loop
689 # in modify mod: userbranch value comes from borrowers table
690 # in add mod: userbranch value comes from branches table (ip correspondence)
692 my $userbranch = '';
693 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
694 $userbranch = C4::Context->userenv->{'branch'};
697 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
698 $userbranch = $data{'branchcode'};
700 $template->param( userbranch => $userbranch );
702 if ( Koha::Libraries->search->count < 1 ){
703 $no_add = 1;
704 $template->param(no_branches => 1);
706 if($no_categories){
707 $no_add = 1;
708 $template->param(no_categories => 1);
710 $template->param(no_add => $no_add);
711 # --------------------------------------------------------------------------------------------------------
713 $template->param( sort1 => $data{'sort1'});
714 $template->param( sort2 => $data{'sort2'});
716 if ($nok) {
717 foreach my $error (@errors) {
718 $template->param($error) || $template->param( $error => 1);
720 $template->param(nok => 1);
723 #Formatting data for display
725 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
726 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
728 if ( $op eq 'duplicate' ) {
729 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
730 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
731 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
733 if (C4::Context->preference('uppercasesurnames')) {
734 $data{'surname'} &&= uc( $data{'surname'} );
735 $data{'contactname'} &&= uc( $data{'contactname'} );
738 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
739 if ( $data{$_} ) {
740 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
742 $template->param( $_ => $data{$_});
745 if (C4::Context->preference('ExtendedPatronAttributes')) {
746 patron_attributes_form($template, $borrowernumber, $op);
749 if (C4::Context->preference('EnhancedMessagingPreferences')) {
750 if ($op eq 'add') {
751 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
752 } else {
753 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
755 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
756 $template->param(SMSnumber => $data{'smsalertnumber'} );
757 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
760 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
761 $debug and warn "memberentry step: $step";
762 $template->param(%data);
763 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
764 $template->param( step => $step ) if $step; # associate with step to know where u are
766 $template->param(
767 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
768 category_type => $category_type,#to know the category type of the borrower
769 "$category_type" => 1,# associate with step to know where u are
770 destination => $destination,#to know wher u come from and wher u must go in redirect
771 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
772 "op$op" => 1);
774 $template->param(
775 patron => $patron ? $patron : \%newdata, # Used by address include templates now
776 nodouble => $nodouble,
777 borrowernumber => $borrowernumber, #register number
778 relshiploop => \@relshipdata,
779 btitle=> $default_borrowertitle,
780 flagloop => \@flagdata,
781 category_type =>$category_type,
782 modify => $modify,
783 nok => $nok,#flag to know if an error
784 NoUpdateLogin => $NoUpdateLogin,
787 # Generate CSRF token
788 $template->param( csrf_token =>
789 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
792 # HouseboundModule data
793 $template->param(
794 housebound_role => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
797 if(defined($data{'flags'})){
798 $template->param(flags=>$data{'flags'});
800 if(defined($data{'contacttitle'})){
801 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
805 my ( $min, $max ) = C4::Members::get_cardnumber_length();
806 if ( defined $min ) {
807 $template->param(
808 minlength_cardnumber => $min,
809 maxlength_cardnumber => $max
813 if ( C4::Context->preference('TranslateNotices') ) {
814 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
815 $template->param( languages => $translated_languages );
818 output_html_with_http_headers $input, $cookie, $template->output;
820 sub parse_extended_patron_attributes {
821 my ($input) = @_;
822 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
824 my @attr = ();
825 my %dups = ();
826 foreach my $key (@patron_attr) {
827 my $value = $input->param($key);
828 next unless defined($value) and $value ne '';
829 my $code = $input->param("${key}_code");
830 next if exists $dups{$code}->{$value};
831 $dups{$code}->{$value} = 1;
832 push @attr, { code => $code, value => $value };
834 return \@attr;
837 sub patron_attributes_form {
838 my $template = shift;
839 my $borrowernumber = shift;
840 my $op = shift;
842 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
843 if (scalar(@types) == 0) {
844 $template->param(no_patron_attribute_types => 1);
845 return;
847 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
848 my @classes = uniq( map {$_->{class}} @$attributes );
849 @classes = sort @classes;
851 # map patron's attributes into a more convenient structure
852 my %attr_hash = ();
853 foreach my $attr (@$attributes) {
854 push @{ $attr_hash{$attr->{code}} }, $attr;
857 my @attribute_loop = ();
858 my $i = 0;
859 my %items_by_class;
860 foreach my $type_code (map { $_->{code} } @types) {
861 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
862 my $entry = {
863 class => $attr_type->class(),
864 code => $attr_type->code(),
865 description => $attr_type->description(),
866 repeatable => $attr_type->repeatable(),
867 category => $attr_type->authorised_value_category(),
868 category_code => $attr_type->category_code(),
870 if (exists $attr_hash{$attr_type->code()}) {
871 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
872 my $newentry = { %$entry };
873 $newentry->{value} = $attr->{value};
874 $newentry->{use_dropdown} = 0;
875 if ($attr_type->authorised_value_category()) {
876 $newentry->{use_dropdown} = 1;
877 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
879 $i++;
880 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
881 $newentry->{form_id} = "patron_attr_$i";
882 push @{$items_by_class{$attr_type->class()}}, $newentry;
884 } else {
885 $i++;
886 my $newentry = { %$entry };
887 if ($attr_type->authorised_value_category()) {
888 $newentry->{use_dropdown} = 1;
889 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
891 $newentry->{form_id} = "patron_attr_$i";
892 push @{$items_by_class{$attr_type->class()}}, $newentry;
895 while ( my ($class, @items) = each %items_by_class ) {
896 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
897 my $lib = $av->count ? $av->next->lib : $class;
898 push @attribute_loop, {
899 class => $class,
900 items => @items,
901 lib => $lib,
905 $template->param(patron_attributes => \@attribute_loop);
909 sub add_guarantors {
910 my ( $patron, $input ) = @_;
912 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
913 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
915 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
916 my $guarantor_id = $new_guarantor_id[$i];
917 my $relationship = $new_guarantor_relationship[$i];
919 next unless $guarantor_id;
921 $patron->add_guarantor(
923 guarantor_id => $guarantor_id,
924 relationship => $relationship,
930 # Local Variables:
931 # tab-width: 8
932 # End: