Bug 21467: Prevent tests to fail
[koha.git] / members / memberentry.pl
blob14a11361a204cae670a5cf9ac7874a490ea35f45
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 $guarantorid = $input->param('guarantorid');
87 my $actionType = $input->param('actionType') || '';
88 my $modify = $input->param('modify');
89 my $delete = $input->param('delete');
90 my $op = $input->param('op');
91 my $destination = $input->param('destination');
92 my $cardnumber = $input->param('cardnumber');
93 my $check_member = $input->param('check_member');
94 my $nodouble = $input->param('nodouble');
95 my $duplicate = $input->param('duplicate');
96 my $quickadd = $input->param('quickadd');
97 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate'); # FIXME hack to represent fact that if we're
98 # modifying an existing patron, it ipso facto
99 # isn't a duplicate. Marking FIXME because this
100 # script needs to be refactored.
101 my $nok = $input->param('nok');
102 my $guarantorinfo = $input->param('guarantorinfo');
103 my $step = $input->param('step') || 0;
104 my @errors;
105 my $borrower_data;
106 my $NoUpdateLogin;
107 my $userenv = C4::Context->userenv;
109 ## Deal with debarments
110 $template->param(
111 debarments => scalar GetDebarments( { borrowernumber => $borrowernumber } ) );
112 my @debarments_to_remove = $input->multi_param('remove_debarment');
113 foreach my $d ( @debarments_to_remove ) {
114 DelDebarment( $d );
116 if ( $input->param('add_debarment') ) {
118 my $expiration = $input->param('debarred_expiration');
119 $expiration =
120 $expiration
121 ? dt_from_string($expiration)->ymd
122 : undef;
124 AddDebarment(
126 borrowernumber => $borrowernumber,
127 type => 'MANUAL',
128 comment => scalar $input->param('debarred_comment'),
129 expiration => $expiration,
134 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
136 # function to designate mandatory fields (visually with css)
137 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
138 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
139 foreach (@field_check) {
140 $template->param( "mandatory$_" => 1);
142 # function to designate unwanted fields
143 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
144 @field_check=split(/\|/,$check_BorrowerUnwantedField);
145 foreach (@field_check) {
146 next unless m/\w/o;
147 $template->param( "no$_" => 1);
149 $template->param( "add" => 1 ) if ( $op eq 'add' );
150 $template->param( "quickadd" => 1 ) if ( $quickadd );
151 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
152 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
153 if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' ) {
154 my $logged_in_user = Koha::Patrons->find( $loggedinuser ) or die "Not logged in";
155 output_and_exit_if_error( $input, $cookie, $template, { module => 'members', logged_in_user => $logged_in_user, current_patron => $patron } );
157 $borrower_data = $patron->unblessed;
158 $borrower_data->{category_type} = $patron->category->category_type;
161 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
162 my $category_type = $input->param('category_type') || '';
163 unless ($category_type or !($categorycode)){
164 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
165 $category_type = $borrowercategory->category_type;
166 my $category_name = $borrowercategory->description;
167 $template->param("categoryname"=>$category_name);
169 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
171 # if a add or modify is requested => check validity of data.
172 %data = %$borrower_data if ($borrower_data);
174 # initialize %newdata
175 my %newdata; # comes from $input->param()
176 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
177 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
178 foreach my $key (@names) {
179 if (defined $input->param($key)) {
180 $newdata{$key} = $input->param($key);
181 $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
185 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
186 next unless exists $newdata{$_};
187 my $userdate = $newdata{$_} or next;
189 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
190 if ( $formatteddate ) {
191 $newdata{$_} = $formatteddate;
192 } else {
193 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
194 $template->param( "ERROR_$_" => 1 );
195 push(@errors,"ERROR_$_");
198 # check permission to modify login info.
199 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
200 $NoUpdateLogin = 1;
204 # remove keys from %newdata that is not part of patron's attributes
206 my @keys_to_delete = (
207 qr/^BorrowerMandatoryField$/,
208 qr/^category_type$/,
209 qr/^check_member$/,
210 qr/^destination$/,
211 qr/^nodouble$/,
212 qr/^op$/,
213 qr/^save$/,
214 qr/^updtype$/,
215 qr/^SMSnumber$/,
216 qr/^setting_extended_patron_attributes$/,
217 qr/^setting_messaging_prefs$/,
218 qr/^digest$/,
219 qr/^modify$/,
220 qr/^step$/,
221 qr/^\d+$/,
222 qr/^\d+-DAYS/,
223 qr/^patron_attr_/,
224 qr/^csrf_token$/,
225 qr/^add_debarment$/, qr/^debarred_expiration$/, # We already dealt with debarments previously
226 qr/^housebound_chooser$/, qr/^housebound_deliverer$/,
227 qr/^select_city$/,
229 for my $regexp (@keys_to_delete) {
230 for (keys %newdata) {
231 delete($newdata{$_}) if /$regexp/;
236 # Test uniqueness of surname, firstname and dateofbirth
237 if ( ( $op eq 'insert' ) and !$nodouble ) {
238 my $conditions;
239 $conditions->{surname} = $newdata{surname} if $newdata{surname};
240 if ( $category_type ne 'I' ) {
241 $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
242 $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
244 $nodouble = 1;
245 my $patrons = Koha::Patrons->search($conditions); # FIXME Should be search_limited?
246 if ( $patrons->count > 0) {
247 $nodouble = 0;
248 $check_member = $patrons->next->borrowernumber;
252 #recover all data from guarantor address phone ,fax...
253 if ( $guarantorid ) {
254 if (my $guarantor = Koha::Patrons->find( $guarantorid )) {
255 my $guarantordata = $guarantor->unblessed;
256 $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
257 $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
258 $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
259 $newdata{'contactname'} = $guarantordata->{'surname'};
260 $newdata{'contacttitle'} = $guarantordata->{'title'};
261 if ( $op eq 'add' ) {
262 foreach (qw(streetnumber address streettype address2
263 zipcode country city state phone phonepro mobile fax email emailpro branchcode
264 B_streetnumber B_streettype B_address B_address2
265 B_city B_state B_zipcode B_country B_email B_phone)) {
266 $newdata{$_} = $guarantordata->{$_};
272 ###############test to take the right zipcode, country and city name ##############
273 # set only if parameter was passed from the form
274 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
275 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
276 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
278 $newdata{'lang'} = $input->param('lang') if defined($input->param('lang'));
280 # builds default userid
281 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
282 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
283 my $fake_patron = Koha::Patron->new;
284 $fake_patron->userid($patron->userid) if $patron; # editing
285 if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
286 # Full page edit, firstname and surname input zones are present
287 $fake_patron->firstname($newdata{firstname});
288 $fake_patron->surname($newdata{surname});
289 $fake_patron->generate_userid;
290 $newdata{'userid'} = $fake_patron->userid;
292 elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
293 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
294 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
295 # FIXME clean thiscode newdata vs data is very confusing
296 $fake_patron->firstname($data{firstname});
297 $fake_patron->surname($data{surname});
298 $fake_patron->generate_userid;
299 $newdata{'userid'} = $fake_patron->userid;
301 else {
302 $newdata{'userid'} = $data{'userid'};
306 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
307 my $extended_patron_attributes = ();
308 if ($op eq 'save' || $op eq 'insert'){
310 die "Wrong CSRF token"
311 unless Koha::Token->new->check_csrf({
312 session_id => scalar $input->cookie('CGISESSID'),
313 token => scalar $input->param('csrf_token'),
316 # If the cardnumber is blank, treat it as null.
317 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
319 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
320 push @errors, $error_code == 1
321 ? 'ERROR_cardnumber_already_exists'
322 : $error_code == 2
323 ? 'ERROR_cardnumber_length'
324 : ()
327 my $dateofbirth;
328 if ($op eq 'save' && $step == 3) {
329 $dateofbirth = $patron->dateofbirth;
331 else {
332 $dateofbirth = $newdata{dateofbirth};
335 if ( $dateofbirth ) {
336 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
337 my $age = $patron->get_age;
338 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
339 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
340 if (($high && ($age > $high)) or ($age < $low)) {
341 push @errors, 'ERROR_age_limitations';
342 $template->param( age_low => $low);
343 $template->param( age_high => $high);
347 if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
348 $newdata{'surname'} = uc($newdata{'surname'});
351 if (C4::Context->preference("IndependentBranches")) {
352 unless ( C4::Context->IsSuperLibrarian() ){
353 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
354 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
355 push @errors, "ERROR_branch";
359 # Check if the 'userid' is unique. 'userid' might not always be present in
360 # the edited values list when editing certain sub-forms. Get it straight
361 # from the DB if absent.
362 my $userid = $newdata{ userid } // $borrower_data->{ userid };
363 my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new;
364 $p->userid( $userid );
365 unless ( $p->has_valid_userid ) {
366 push @errors, "ERROR_login_exist";
369 my $password = $input->param('password');
370 my $password2 = $input->param('password2');
371 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
373 if ( $password and $password ne '****' ) {
374 my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
375 unless ( $is_valid ) {
376 push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
377 push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
378 push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
382 # Validate emails
383 my $emailprimary = $input->param('email');
384 my $emailsecondary = $input->param('emailpro');
385 my $emailalt = $input->param('B_email');
387 if ($emailprimary) {
388 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
390 if ($emailsecondary) {
391 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
393 if ($emailalt) {
394 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
397 if (C4::Context->preference('ExtendedPatronAttributes')) {
398 $extended_patron_attributes = parse_extended_patron_attributes($input);
399 foreach my $attr (@$extended_patron_attributes) {
400 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
401 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
402 push @errors, "ERROR_extended_unique_id_failed";
403 $template->param(
404 ERROR_extended_unique_id_failed_code => $attr->{code},
405 ERROR_extended_unique_id_failed_value => $attr->{value},
406 ERROR_extended_unique_id_failed_description => $attr_info->description()
413 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
414 unless ($newdata{'dateexpiry'}){
415 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
416 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
420 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
421 my $sms = $input->param('SMSnumber');
422 if ( defined $sms ) {
423 $newdata{smsalertnumber} = $sms;
426 ### Error checks should happen before this line.
427 $nok = $nok || scalar(@errors);
428 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
429 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
430 if ($op eq 'insert'){
431 # we know it's not a duplicate borrowernumber or there would already be an error
432 delete $newdata{password2};
433 my $patron = eval { Koha::Patron->new(\%newdata)->store };
434 if ( $@ ) {
435 # FIXME Urgent error handling here, we cannot fail without relevant feedback
436 # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
437 warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
438 } else {
439 $borrowernumber = $patron->borrowernumber;
442 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
443 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
444 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
445 my $emailaddr;
446 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
447 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
448 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
450 elsif ($newdata{email} =~ /\w\@\w/) {
451 $emailaddr = $newdata{email}
453 elsif ($newdata{emailpro} =~ /\w\@\w/) {
454 $emailaddr = $newdata{emailpro}
456 elsif ($newdata{B_email} =~ /\w\@\w/) {
457 $emailaddr = $newdata{B_email}
459 # if we manage to find a valid email address, send notice
460 if ($emailaddr) {
461 $newdata{emailaddr} = $emailaddr;
462 my $err;
463 eval {
464 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
466 if ( $@ ) {
467 $template->param(error_alert => $@);
468 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
469 $template->{VARS}->{'error_alert'} = "no_email";
470 } else {
471 $template->{VARS}->{'info_alert'} = 1;
476 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
477 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
479 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
480 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
483 # Create HouseboundRole if necessary.
484 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
485 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
486 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
487 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
488 # Only create a HouseboundRole if patron has a role.
489 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
490 Koha::Patron::HouseboundRole->new({
491 borrowernumber_id => $borrowernumber,
492 housebound_chooser => $hsbnd_chooser,
493 housebound_deliverer => $hsbnd_deliverer,
494 })->store;
497 } elsif ($op eq 'save') {
499 # Update or create our HouseboundRole if necessary.
500 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
501 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
502 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
503 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
504 if ( $housebound_role ) {
505 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
506 # Update our HouseboundRole.
507 $housebound_role
508 ->housebound_chooser($hsbnd_chooser)
509 ->housebound_deliverer($hsbnd_deliverer)
510 ->store;
511 } else {
512 $housebound_role->delete; # No longer needed.
514 } else {
515 # Only create a HouseboundRole if patron has a role.
516 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
517 $housebound_role = Koha::Patron::HouseboundRole->new({
518 borrowernumber_id => $borrowernumber,
519 housebound_chooser => $hsbnd_chooser,
520 housebound_deliverer => $hsbnd_deliverer,
521 })->store;
525 if ($NoUpdateLogin) {
526 delete $newdata{'password'};
527 delete $newdata{'userid'};
530 my $patron = Koha::Patrons->find( $borrowernumber );
531 $newdata{debarredcomment} = $newdata{debarred_comment};
532 delete $newdata{debarred_comment};
533 delete $newdata{password2};
534 $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
535 # updating any columns in the borrowers table,
536 # which can happen if we're only editing the
537 # patron attributes or messaging preferences sections
539 $patron->update_password($newdata{userid}, $newdata{password});
541 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
542 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
544 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
545 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
549 if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
550 # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
551 $destination = 'not_circ';
553 print scalar( $destination eq "circ" )
554 ? $input->redirect(
555 "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
556 : $input->redirect(
557 "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
559 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
562 if ($delete){
563 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
564 exit; # same as above
567 if ($nok or !$nodouble){
568 $op="add" if ($op eq "insert");
569 $op="modify" if ($op eq "save");
570 %data=%newdata;
571 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
572 unless ($step){
573 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
576 if (C4::Context->preference("IndependentBranches")) {
577 my $userenv = C4::Context->userenv;
578 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
579 unless ($userenv->{branch} eq $data{'branchcode'}){
580 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
581 exit;
585 if ($op eq 'add'){
586 $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);
588 if ($op eq "modify") {
589 $template->param( updtype => 'M',modify => 1 );
590 $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;
591 if ( $step == 4 ) {
592 $template->param( categorycode => $borrower_data->{'categorycode'} );
595 if ( $op eq "duplicate" ) {
596 $template->param( updtype => 'I' );
597 $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;
598 $data{'cardnumber'} = "";
601 if(!defined($data{'sex'})){
602 $template->param( none => 1);
603 } elsif($data{'sex'} eq 'F'){
604 $template->param( female => 1);
605 } elsif ($data{'sex'} eq 'M'){
606 $template->param( male => 1);
607 } else {
608 $template->param( none => 1);
611 ##Now all the data to modify a member.
613 my @typeloop;
614 my $no_categories = 1;
615 my $no_add;
616 foreach my $category_type (qw(C A S P I X)) {
617 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
618 $no_categories = 0 if $patron_categories->count > 0;
620 my @categoryloop;
621 while ( my $patron_category = $patron_categories->next ) {
622 push @categoryloop,
623 { 'categorycode' => $patron_category->categorycode,
624 'categoryname' => $patron_category->description,
625 'categorycodeselected' =>
626 ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
629 my %typehash;
630 $typehash{'typename'} = $category_type;
631 my $typedescription = "typename_" . $typehash{'typename'};
632 $typehash{'categoryloop'} = \@categoryloop;
633 push @typeloop,
634 { 'typename' => $category_type,
635 $typedescription => 1,
636 'categoryloop' => \@categoryloop
640 $template->param('typeloop' => \@typeloop,
641 no_categories => $no_categories);
642 if($no_categories){ $no_add = 1; }
645 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
646 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
647 $template->param(
648 roadtypes => $roadtypes,
649 cities => $cities,
652 my $default_borrowertitle = '';
653 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
655 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
656 my @relshipdata;
657 while (@relationships) {
658 my $relship = shift @relationships || '';
659 my %row = ('relationship' => $relship);
660 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
661 $row{'selected'}=' selected';
662 } else {
663 $row{'selected'}='';
665 push(@relshipdata, \%row);
668 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
669 'lost' => ['lost']);
672 my @flagdata;
673 foreach (keys(%flags)) {
674 my $key = $_;
675 my %row = ('key' => $key,
676 '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 $template->param(ExtendedPatronAttributes => 1);
747 patron_attributes_form($template, $borrowernumber);
750 if (C4::Context->preference('EnhancedMessagingPreferences')) {
751 if ($op eq 'add') {
752 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
753 } else {
754 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
756 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
757 $template->param(SMSnumber => $data{'smsalertnumber'} );
758 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
761 $template->param( "showguarantor" => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
762 $debug and warn "memberentry step: $step";
763 $template->param(%data);
764 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
765 $template->param( step => $step ) if $step; # associate with step to know where u are
767 $template->param(
768 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
769 category_type => $category_type,#to know the category type of the borrower
770 "$category_type" => 1,# associate with step to know where u are
771 destination => $destination,#to know wher u come from and wher u must go in redirect
772 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
773 "op$op" => 1);
775 $guarantorid = $borrower_data->{'guarantorid'} || $guarantorid;
776 my $guarantor = $guarantorid ? Koha::Patrons->find( $guarantorid ) : undef;
777 $template->param(
778 patron => $patron, # Used by address include templates now
779 nodouble => $nodouble,
780 borrowernumber => $borrowernumber, #register number
781 guarantor => $guarantor,
782 guarantorid => $guarantorid,
783 relshiploop => \@relshipdata,
784 btitle=> $default_borrowertitle,
785 guarantorinfo => $guarantorinfo,
786 flagloop => \@flagdata,
787 category_type =>$category_type,
788 modify => $modify,
789 nok => $nok,#flag to know if an error
790 NoUpdateLogin => $NoUpdateLogin,
793 # Generate CSRF token
794 $template->param( csrf_token =>
795 Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
798 # HouseboundModule data
799 $template->param(
800 housebound_role => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
803 if(defined($data{'flags'})){
804 $template->param(flags=>$data{'flags'});
806 if(defined($data{'contacttitle'})){
807 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
811 my ( $min, $max ) = C4::Members::get_cardnumber_length();
812 if ( defined $min ) {
813 $template->param(
814 minlength_cardnumber => $min,
815 maxlength_cardnumber => $max
819 if ( C4::Context->preference('TranslateNotices') ) {
820 my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
821 $template->param( languages => $translated_languages );
824 output_html_with_http_headers $input, $cookie, $template->output;
826 sub parse_extended_patron_attributes {
827 my ($input) = @_;
828 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
830 my @attr = ();
831 my %dups = ();
832 foreach my $key (@patron_attr) {
833 my $value = $input->param($key);
834 next unless defined($value) and $value ne '';
835 my $code = $input->param("${key}_code");
836 next if exists $dups{$code}->{$value};
837 $dups{$code}->{$value} = 1;
838 push @attr, { code => $code, value => $value };
840 return \@attr;
843 sub patron_attributes_form {
844 my $template = shift;
845 my $borrowernumber = shift;
847 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
848 if (scalar(@types) == 0) {
849 $template->param(no_patron_attribute_types => 1);
850 return;
852 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
853 my @classes = uniq( map {$_->{class}} @$attributes );
854 @classes = sort @classes;
856 # map patron's attributes into a more convenient structure
857 my %attr_hash = ();
858 foreach my $attr (@$attributes) {
859 push @{ $attr_hash{$attr->{code}} }, $attr;
862 my @attribute_loop = ();
863 my $i = 0;
864 my %items_by_class;
865 foreach my $type_code (map { $_->{code} } @types) {
866 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
867 my $entry = {
868 class => $attr_type->class(),
869 code => $attr_type->code(),
870 description => $attr_type->description(),
871 repeatable => $attr_type->repeatable(),
872 category => $attr_type->authorised_value_category(),
873 category_code => $attr_type->category_code(),
875 if (exists $attr_hash{$attr_type->code()}) {
876 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
877 my $newentry = { %$entry };
878 $newentry->{value} = $attr->{value};
879 $newentry->{use_dropdown} = 0;
880 if ($attr_type->authorised_value_category()) {
881 $newentry->{use_dropdown} = 1;
882 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
884 $i++;
885 $newentry->{form_id} = "patron_attr_$i";
886 push @{$items_by_class{$attr_type->class()}}, $newentry;
888 } else {
889 $i++;
890 my $newentry = { %$entry };
891 if ($attr_type->authorised_value_category()) {
892 $newentry->{use_dropdown} = 1;
893 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
895 $newentry->{form_id} = "patron_attr_$i";
896 push @{$items_by_class{$attr_type->class()}}, $newentry;
899 while ( my ($class, @items) = each %items_by_class ) {
900 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
901 my $lib = $av->count ? $av->next->lib : $class;
902 push @attribute_loop, {
903 class => $class,
904 items => @items,
905 lib => $lib,
909 $template->param(patron_attributes => \@attribute_loop);
913 # Local Variables:
914 # tab-width: 8
915 # End: