Bug 25642: Fix description of new feature in update_dbix_class_files.pl
[koha.git] / members / memberentry.pl
blobcfdc06032e841263a8ca01db56a296384ff10e03
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::Koha;
34 use C4::Log;
35 use C4::Letters;
36 use C4::Form::MessagingPreferences;
37 use Koha::AuthUtils;
38 use Koha::AuthorisedValues;
39 use Koha::Patron::Debarments;
40 use Koha::Cities;
41 use Koha::DateUtils;
42 use Koha::Libraries;
43 use Koha::Patrons;
44 use Koha::Patron::Attribute::Types;
45 use Koha::Patron::Categories;
46 use Koha::Patron::HouseboundRole;
47 use Koha::Patron::HouseboundRoles;
48 use Koha::Token;
49 use Email::Valid;
50 use Koha::SMS::Providers;
52 use vars qw($debug);
54 BEGIN {
55 $debug = $ENV{DEBUG} || 0;
58 my $input = new CGI;
59 ($debug) or $debug = $input->param('debug') || 0;
60 my %data;
62 my $dbh = C4::Context->dbh;
64 my ($template, $loggedinuser, $cookie)
65 = get_template_and_user({template_name => "members/memberentrygen.tt",
66 query => $input,
67 type => "intranet",
68 authnotrequired => 0,
69 flagsrequired => {borrowers => 'edit_borrowers'},
70 debug => ($debug) ? 1 : 0,
71 });
73 my $borrowernumber = $input->param('borrowernumber');
74 my $patron = Koha::Patrons->find($borrowernumber);
76 if ( $borrowernumber and not $patron ) {
77 output_and_exit( $input, $cookie, $template, 'unknown_patron' );
80 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
81 my @providers = Koha::SMS::Providers->search();
82 $template->param( sms_providers => \@providers );
85 my $actionType = $input->param('actionType') || '';
86 my $modify = $input->param('modify');
87 my $delete = $input->param('delete');
88 my $op = $input->param('op');
89 my $destination = $input->param('destination');
90 my $cardnumber = $input->param('cardnumber');
91 my $check_member = $input->param('check_member');
92 my $nodouble = $input->param('nodouble');
93 my $duplicate = $input->param('duplicate');
94 my $quickadd = $input->param('quickadd');
95 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
96 # modifying an existing patron, it ipso facto
97 # isn't a duplicate. Marking FIXME because this
98 # script needs to be refactored.
99 my $nok = $input->param('nok');
100 my $step = $input->param('step') || 0;
101 my @errors;
102 my $borrower_data;
103 my $NoUpdateLogin;
104 my $userenv = C4::Context->userenv;
105 my @messages;
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 );
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;
266 my @new_guarantors;
267 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
268 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
269 foreach my $gid ( @new_guarantor_id ) {
270 my $patron = Koha::Patrons->find( $gid );
271 my $relationship = shift( @new_guarantor_relationship );
272 next unless $patron;
273 my $g = { patron => $patron, relationship => $relationship };
274 push( @new_guarantors, $g );
276 $template->param( new_guarantors => \@new_guarantors );
280 ###############test to take the right zipcode, country and city name ##############
281 # set only if parameter was passed from the form
282 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
283 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
284 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
286 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
288 # builds default userid
289 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
290 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
291 my $fake_patron = Koha::Patron->new;
292 $fake_patron->userid($patron->userid) if $patron; # editing
293 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
294 # Full page edit, firstname and surname input zones are present
295 $fake_patron->firstname($newdata{firstname});
296 $fake_patron->surname($newdata{surname});
297 $fake_patron->generate_userid;
298 $newdata{'userid'} = $fake_patron->userid;
300 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
301 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
302 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
303 # FIXME clean thiscode newdata vs data is very confusing
304 $fake_patron->firstname($data{firstname});
305 $fake_patron->surname($data{surname});
306 $fake_patron->generate_userid;
307 $newdata{'userid'} = $fake_patron->userid;
309 else {
310 $newdata{'userid'} = $data{'userid'};
314 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
315 my $extended_patron_attributes;
316 if ($op eq 'save' || $op eq 'insert'){
318 output_and_exit( $input, $cookie, $template, 'wrong_csrf_token' )
319 unless Koha::Token->new->check_csrf({
320 session_id => scalar $input->cookie('CGISESSID'),
321 token => scalar $input->param('csrf_token'),
324 # If the cardnumber is blank, treat it as null.
325 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
327 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
328 push @errors, $error_code == 1
329 ? 'ERROR_cardnumber_already_exists'
330 : $error_code == 2
331 ? 'ERROR_cardnumber_length'
332 : ()
335 my $dateofbirth;
336 if ($op eq 'save' && $step == 3) {
337 $dateofbirth = $patron->dateofbirth;
339 else {
340 $dateofbirth = $newdata{dateofbirth};
343 if ( $dateofbirth ) {
344 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
345 my $age = $patron->get_age;
346 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
347 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
348 if (($high && ($age > $high)) or ($age < $low)) {
349 push @errors, 'ERROR_age_limitations';
350 $template->param( age_low => $low);
351 $template->param( age_high => $high);
355 if (C4::Context->preference("IndependentBranches")) {
356 unless ( C4::Context->IsSuperLibrarian() ){
357 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
358 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
359 push @errors, "ERROR_branch";
363 # Check if the 'userid' is unique. 'userid' might not always be present in
364 # the edited values list when editing certain sub-forms. Get it straight
365 # from the DB if absent.
366 my $userid = $newdata{ userid } // $borrower_data->{ userid };
367 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new;
368 $p->userid( $userid );
369 unless ( $p->has_valid_userid ) {
370 push @errors, "ERROR_login_exist";
373 my $password = $input->param('password');
374 my $password2 = $input->param('password2');
375 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
377 if ( $password and $password ne '****' ) {
378 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
379 unless ( $is_valid ) {
380 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
381 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
382 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
386 # Validate emails
387 my $emailprimary = $input->param('email');
388 my $emailsecondary = $input->param('emailpro');
389 my $emailalt = $input->param('B_email');
391 if ($emailprimary) {
392 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
394 if ($emailsecondary) {
395 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
397 if ($emailalt) {
398 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
401 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
402 $extended_patron_attributes = parse_extended_patron_attributes($input);
403 for my $attr ( @$extended_patron_attributes ) {
404 $attr->{borrowernumber} = $borrowernumber if $borrowernumber;
405 my $attribute = Koha::Patron::Attribute->new($attr);
406 eval {$attribute->check_unique_id};
407 if ( $@ ) {
408 push @errors, "ERROR_extended_unique_id_failed";
409 my $attr_type = Koha::Patron::Attribute::Types->find($attr->{code});
410 $template->param(
411 ERROR_extended_unique_id_failed_code => $attr->{code},
412 ERROR_extended_unique_id_failed_value => $attr->{attribute},
413 ERROR_extended_unique_id_failed_description => $attr_type->description()
419 elsif ( $borrowernumber ) {
420 $extended_patron_attributes = Koha::Patrons->find($borrowernumber)->extended_attributes->unblessed;
423 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
424 unless ($newdata{'dateexpiry'}){
425 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
426 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
430 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
431 my $sms = $input->param('SMSnumber');
432 if ( defined $sms ) {
433 $newdata{smsalertnumber} = $sms;
436 ### Error checks should happen before this line.
437 $nok = $nok || scalar(@errors);
438 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
439 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
440 my $success;
441 if ($op eq 'insert'){
442 # we know it's not a duplicate borrowernumber or there would already be an error
443 delete $newdata{password2};
444 $patron = eval { Koha::Patron->new(\%newdata)->store };
445 if ( $@ ) {
446 # FIXME Urgent error handling here, we cannot fail without relevant feedback
447 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
448 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
449 push @messages, {error => 'error_on_insert_patron'};
450 $op = "add";
451 } else {
452 $success = 1;
453 add_guarantors( $patron, $input );
454 $borrowernumber = $patron->borrowernumber;
455 $newdata{'borrowernumber'} = $borrowernumber;
458 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
459 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
460 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
461 my $emailaddr;
462 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
463 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
464 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
466 elsif ($newdata{email} =~ /\w\@\w/) {
467 $emailaddr = $newdata{email}
469 elsif ($newdata{emailpro} =~ /\w\@\w/) {
470 $emailaddr = $newdata{emailpro}
472 elsif ($newdata{B_email} =~ /\w\@\w/) {
473 $emailaddr = $newdata{B_email}
475 # if we manage to find a valid email address, send notice
476 if ($emailaddr) {
477 $newdata{emailaddr} = $emailaddr;
478 my $err;
479 eval {
480 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
482 if ( $@ ) {
483 $template->param(error_alert => $@);
484 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
485 $template->{VARS}->{'error_alert'} = "no_email";
486 } else {
487 $template->{VARS}->{'info_alert'} = 1;
492 if ( $patron && (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) ) {
493 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
496 # Create HouseboundRole if necessary.
497 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
498 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
499 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
500 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
501 # Only create a HouseboundRole if patron has a role.
502 if ( $patron && ( $hsbnd_chooser || $hsbnd_deliverer ) ) {
503 Koha::Patron::HouseboundRole->new({
504 borrowernumber_id => $borrowernumber,
505 housebound_chooser => $hsbnd_chooser,
506 housebound_deliverer => $hsbnd_deliverer,
507 })->store;
510 } elsif ($op eq 'save') {
512 if ($NoUpdateLogin) {
513 delete $newdata{'password'};
514 delete $newdata{'userid'};
517 $patron = Koha::Patrons->find( $borrowernumber );
518 $newdata{debarredcomment} = $newdata{debarred_comment};
519 delete $newdata{debarred_comment};
520 delete $newdata{password2};
522 eval {
523 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
524 # updating any columns in the borrowers table,
525 # which can happen if we're only editing the
526 # patron attributes or messaging preferences sections
528 if ( $@ ) {
529 warn "Patron modification failed! - $@"; # Maybe we must die instead of just warn
530 push @messages, {error => 'error_on_update_patron'};
531 $op = "modify";
532 } else {
534 $success = 1;
535 # Update or create our HouseboundRole if necessary.
536 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
537 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
538 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
539 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
540 if ( $housebound_role ) {
541 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
542 # Update our HouseboundRole.
543 $housebound_role
544 ->housebound_chooser($hsbnd_chooser)
545 ->housebound_deliverer($hsbnd_deliverer)
546 ->store;
547 } else {
548 $housebound_role->delete; # No longer needed.
550 } else {
551 # Only create a HouseboundRole if patron has a role.
552 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
553 $housebound_role = Koha::Patron::HouseboundRole->new({
554 borrowernumber_id => $borrowernumber,
555 housebound_chooser => $hsbnd_chooser,
556 housebound_deliverer => $hsbnd_deliverer,
557 })->store;
561 # should never raise an exception as password validity is checked above
562 my $password = $newdata{password};
563 if ( $password and $password ne '****' ) {
564 $patron->set_password({ password => $password });
567 add_guarantors( $patron, $input );
568 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
569 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
574 if ( $success ) {
575 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
576 $patron->extended_attributes->filter_by_branch_limitations->delete;
577 $patron->extended_attributes($extended_patron_attributes);
580 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
581 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
582 $destination = 'not_circ';
584 print scalar( $destination eq "circ" )
585 ? $input->redirect(
586 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
587 : $input->redirect(
588 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
590 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
594 if ($delete){
595 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
596 exit; # same as above
599 if ($nok or !$nodouble){
600 $op="add" if ($op eq "insert");
601 $op="modify" if ($op eq "save");
602 %data=%newdata;
603 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
604 unless ($step){
605 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
608 if (C4::Context->preference("IndependentBranches")) {
609 my $userenv = C4::Context->userenv;
610 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
611 unless ($userenv->{branch} eq $data{'branchcode'}){
612 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
613 exit;
618 # Define the fields to be pre-filled in guarantee records
619 my $prefillguarantorfields=C4::Context->preference("PrefillGuaranteeField");
620 my @prefill_fields=split(/\,/,$prefillguarantorfields);
622 if ($op eq 'add'){
623 if ($guarantor_id) {
624 foreach (@prefill_fields) {
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;
633 if ( $step == 4 ) {
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);
649 } else {
650 $template->param( none => 1);
653 ##Now all the data to modify a member.
655 my @typeloop;
656 my $no_categories = 1;
657 my $no_add;
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;
662 my @categoryloop;
663 while ( my $patron_category = $patron_categories->next ) {
664 push @categoryloop,
665 { 'categorycode' => $patron_category->categorycode,
666 'categoryname' => $patron_category->description,
667 'categorycodeselected' =>
668 ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
671 my %typehash;
672 $typehash{'typename'} = $category_type;
673 my $typedescription = "typename_" . $typehash{'typename'};
674 $typehash{'categoryloop'} = \@categoryloop;
675 push @typeloop,
676 { 'typename' => $category_type,
677 $typedescription => 1,
678 'categoryloop' => \@categoryloop
681 $template->param(
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' );
688 $template->param(
689 roadtypes => $roadtypes,
690 cities => $cities,
693 my $default_borrowertitle = '';
694 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
696 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
697 my @relshipdata;
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';
703 } else {
704 $row{'selected'}='';
706 push(@relshipdata, \%row);
709 my %flags = (
710 'gonenoaddress' => ['gonenoaddress'],
711 'lost' => ['lost']
714 my @flagdata;
715 foreach ( keys(%flags) ) {
716 my $key = $_;
717 my %row = (
718 'key' => $key,
719 'name' => $flags{$key}[0]
721 if ( $data{$key} ) {
722 $row{'yes'} = ' checked';
723 $row{'no'} = '';
725 else {
726 $row{'yes'} = '';
727 $row{'no'} = ' checked';
729 push @flagdata, \%row;
732 # get Branch Loop
733 # in modify mod: userbranch value comes from borrowers table
734 # in add mod: userbranch value comes from branches table (ip correspondence)
736 my $userbranch = '';
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 ){
747 $no_add = 1;
748 $template->param(no_branches => 1);
750 if($no_categories){
751 $no_add = 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'});
759 $template->param( autorenew => $data{'autorenew'});
761 if ($nok) {
762 foreach my $error (@errors) {
763 $template->param($error) || $template->param( $error => 1);
765 $template->param(nok => 1);
768 #Formatting data for display
770 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
771 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
773 if ( $op eq 'duplicate' ) {
774 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
775 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
776 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
778 if (C4::Context->preference('uppercasesurnames')) {
779 $data{'surname'} &&= uc( $data{'surname'} );
780 $data{'contactname'} &&= uc( $data{'contactname'} );
783 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
784 if ( $data{$_} ) {
785 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
787 $template->param( $_ => $data{$_});
790 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
791 patron_attributes_form( $template, $extended_patron_attributes, $op );
794 if (C4::Context->preference('EnhancedMessagingPreferences')) {
795 if ($op eq 'add') {
796 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
797 } else {
798 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
800 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
801 $template->param(SMSnumber => $data{'smsalertnumber'} );
802 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
805 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
806 $debug and warn "memberentry step: $step";
807 $template->param(%data);
808 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
809 $template->param( step => $step ) if $step; # associate with step to know where u are
811 $template->param(
812 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
813 category_type => $category_type,#to know the category type of the borrower
814 "$category_type" => 1,# associate with step to know where u are
815 destination => $destination,#to know wher u come from and wher u must go in redirect
816 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
817 "op$op" => 1);
819 $template->param(
820 patron => $patron ? $patron : \%newdata, # Used by address include templates now
821 nodouble => $nodouble,
822 borrowernumber => $borrowernumber, #register number
823 relshiploop => \@relshipdata,
824 btitle=> $default_borrowertitle,
825 flagloop => \@flagdata,
826 category_type =>$category_type,
827 modify => $modify,
828 nok => $nok,#flag to know if an error
829 NoUpdateLogin => $NoUpdateLogin,
832 # Generate CSRF token
833 $template->param( csrf_token =>
834 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
837 # HouseboundModule data
838 $template->param(
839 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
842 if(defined($data{'flags'})){
843 $template->param(flags=>$data{'flags'});
845 if(defined($data{'contacttitle'})){
846 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
850 my ( $min, $max ) = C4::Members::get_cardnumber_length();
851 if ( defined $min ) {
852 $template->param(
853 minlength_cardnumber => $min,
854 maxlength_cardnumber => $max
858 if ( C4::Context->preference('TranslateNotices') ) {
859 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
860 $template->param( languages => $translated_languages );
863 $template->param( messages => \@messages );
864 output_html_with_http_headers $input, $cookie, $template->output;
866 sub parse_extended_patron_attributes {
867 my ($input) = @_;
868 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
870 my @attr = ();
871 my %dups = ();
872 foreach my $key (@patron_attr) {
873 my $value = $input->param($key);
874 next unless defined($value) and $value ne '';
875 my $code = $input->param("${key}_code");
876 next if exists $dups{$code}->{$value};
877 $dups{$code}->{$value} = 1;
878 push @attr, { code => $code, attribute => $value };
880 return \@attr;
883 sub patron_attributes_form {
884 my $template = shift;
885 my $attributes = shift;
886 my $op = shift;
888 my $library_id = C4::Context->userenv ? C4::Context->userenv->{'branch'} : undef;
889 my $attribute_types = Koha::Patron::Attribute::Types->search_with_library_limits({}, {}, $library_id);
890 if ( $attribute_types->count == 0 ) {
891 $template->param(no_patron_attribute_types => 1);
892 return;
895 # map patron's attributes into a more convenient structure
896 my %attr_hash = ();
897 foreach my $attr (@$attributes) {
898 push @{ $attr_hash{$attr->{code}} }, $attr;
901 my @attribute_loop = ();
902 my $i = 0;
903 my %items_by_class;
904 while ( my ( $attr_type ) = $attribute_types->next ) {
905 my $entry = {
906 class => $attr_type->class(),
907 code => $attr_type->code(),
908 description => $attr_type->description(),
909 repeatable => $attr_type->repeatable(),
910 category => $attr_type->authorised_value_category(),
911 category_code => $attr_type->category_code(),
913 if (exists $attr_hash{$attr_type->code()}) {
914 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
915 my $newentry = { %$entry };
916 $newentry->{value} = $attr->{attribute};
917 $newentry->{use_dropdown} = 0;
918 if ($attr_type->authorised_value_category()) {
919 $newentry->{use_dropdown} = 1;
920 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{attribute});
922 $i++;
923 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
924 $newentry->{form_id} = "patron_attr_$i";
925 push @{$items_by_class{$attr_type->{class}}}, $newentry;
927 } else {
928 $i++;
929 my $newentry = { %$entry };
930 if ($attr_type->authorised_value_category()) {
931 $newentry->{use_dropdown} = 1;
932 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
934 $newentry->{form_id} = "patron_attr_$i";
935 push @{$items_by_class{$attr_type->class()}}, $newentry;
938 while ( my ($class, @items) = each %items_by_class ) {
939 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
940 my $lib = $av->count ? $av->next->lib : $class;
941 push @attribute_loop, {
942 class => $class,
943 items => @items,
944 lib => $lib,
948 $template->param(patron_attributes => \@attribute_loop);
952 sub add_guarantors {
953 my ( $patron, $input ) = @_;
955 my @new_guarantor_id = $input->multi_param('new_guarantor_id');
956 my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
958 for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
959 my $guarantor_id = $new_guarantor_id[$i];
960 my $relationship = $new_guarantor_relationship[$i];
962 next unless $guarantor_id;
964 $patron->add_guarantor(
966 guarantor_id => $guarantor_id,
967 relationship => $relationship,
973 # Local Variables:
974 # tab-width: 8
975 # End: