Bug 16530 - DBRev 16.12.00.013
[koha.git] / members / memberentry.pl
blobef0aa907587282206681193e32605fe4665d140e
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 strict;
23 use warnings;
25 # external modules
26 use CGI qw ( -utf8 );
27 use List::MoreUtils qw/uniq/;
28 use Digest::MD5 qw(md5_base64);
29 use Encode qw( encode );
31 # internal modules
32 use C4::Auth;
33 use C4::Context;
34 use C4::Output;
35 use C4::Members;
36 use C4::Members::Attributes;
37 use C4::Members::AttributeTypes;
38 use C4::Koha;
39 use C4::Log;
40 use C4::Letters;
41 use C4::Form::MessagingPreferences;
42 use Koha::AuthorisedValues;
43 use Koha::Patron::Debarments;
44 use Koha::Cities;
45 use Koha::DateUtils;
46 use Koha::Libraries;
47 use Koha::Patron::Categories;
48 use Koha::Patron::HouseboundRole;
49 use Koha::Patron::HouseboundRoles;
50 use Koha::Token;
51 use Email::Valid;
52 use Module::Load;
53 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
54 load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
56 use Koha::SMS::Providers;
58 use vars qw($debug);
60 BEGIN {
61 $debug = $ENV{DEBUG} || 0;
64 my $input = new CGI;
65 ($debug) or $debug = $input->param('debug') || 0;
66 my %data;
68 my $dbh = C4::Context->dbh;
70 my ($template, $loggedinuser, $cookie)
71 = get_template_and_user({template_name => "members/memberentrygen.tt",
72 query => $input,
73 type => "intranet",
74 authnotrequired => 0,
75 flagsrequired => {borrowers => 1},
76 debug => ($debug) ? 1 : 0,
77 });
79 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
80 my @providers = Koha::SMS::Providers->search();
81 $template->param( sms_providers => \@providers );
84 my $guarantorid = $input->param('guarantorid');
85 my $borrowernumber = $input->param('borrowernumber');
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 $guarantorinfo = $input->param('guarantorinfo');
102 my $step = $input->param('step') || 0;
103 my @errors;
104 my $borrower_data;
105 my $NoUpdateLogin;
106 my $userenv = C4::Context->userenv;
109 ## Deal with debarments
110 $template->param(
111 debarments => 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 ? output_pref(
122 { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
123 : undef;
125 AddDebarment(
127 borrowernumber => $borrowernumber,
128 type => 'MANUAL',
129 comment => scalar $input->param('debarred_comment'),
130 expiration => $expiration,
135 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
137 my $minpw = C4::Context->preference('minPasswordLength');
138 $template->param("minPasswordLength" => $minpw);
140 # function to designate mandatory fields (visually with css)
141 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
142 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
143 foreach (@field_check) {
144 $template->param( "mandatory$_" => 1);
146 # function to designate unwanted fields
147 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
148 @field_check=split(/\|/,$check_BorrowerUnwantedField);
149 foreach (@field_check) {
150 next unless m/\w/o;
151 $template->param( "no$_" => 1);
153 $template->param( "add" => 1 ) if ( $op eq 'add' );
154 $template->param( "quickadd" => 1 ) if ( $quickadd );
155 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
156 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
157 ( $borrower_data = GetMember( 'borrowernumber' => $borrowernumber ) ) if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' );
158 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
159 my $category_type = $input->param('category_type') || '';
160 unless ($category_type or !($categorycode)){
161 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
162 $category_type = $borrowercategory->category_type;
163 my $category_name = $borrowercategory->description;
164 $template->param("categoryname"=>$category_name);
166 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
168 # if a add or modify is requested => check validity of data.
169 %data = %$borrower_data if ($borrower_data);
171 # initialize %newdata
172 my %newdata; # comes from $input->param()
173 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
174 my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
175 foreach my $key (@names) {
176 if (defined $input->param($key)) {
177 $newdata{$key} = $input->param($key);
178 $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
182 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
183 next unless exists $newdata{$_};
184 my $userdate = $newdata{$_} or next;
186 my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
187 if ( $formatteddate ) {
188 $newdata{$_} = $formatteddate;
189 } else {
190 ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
191 $template->param( "ERROR_$_" => 1 );
192 push(@errors,"ERROR_$_");
195 # check permission to modify login info.
196 if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) ) {
197 $NoUpdateLogin = 1;
201 # remove keys from %newdata that ModMember() doesn't like
203 my @keys_to_delete = (
204 qr/^BorrowerMandatoryField$/,
205 qr/^category_type$/,
206 qr/^check_member$/,
207 qr/^destination$/,
208 qr/^nodouble$/,
209 qr/^op$/,
210 qr/^save$/,
211 qr/^updtype$/,
212 qr/^SMSnumber$/,
213 qr/^setting_extended_patron_attributes$/,
214 qr/^setting_messaging_prefs$/,
215 qr/^digest$/,
216 qr/^modify$/,
217 qr/^step$/,
218 qr/^\d+$/,
219 qr/^\d+-DAYS/,
220 qr/^patron_attr_/,
222 for my $regexp (@keys_to_delete) {
223 for (keys %newdata) {
224 delete($newdata{$_}) if /$regexp/;
229 # Test uniqueness of surname, firstname and dateofbirth
230 if ( ( $op eq 'insert' ) and !$nodouble ) {
231 my $conditions;
232 $conditions->{surname} = $newdata{surname} if $newdata{surname};
233 if ( $category_type ne 'I' ) {
234 $conditions->{firstname} = $newdata{firstname} if $newdata{firstname};
235 $conditions->{dateofbirth} = $newdata{dateofbirth} if $newdata{dateofbirth};
237 $nodouble = 1;
238 my $patrons = Koha::Patrons->search($conditions);
239 if ( $patrons->count > 0) {
240 $nodouble = 0;
241 $check_member = $patrons->next->borrowernumber;
245 #recover all data from guarantor address phone ,fax...
246 if ( $guarantorid ) {
247 if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
248 $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
249 $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
250 $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
251 $newdata{'contactname'} = $guarantordata->{'surname'};
252 $newdata{'contacttitle'} = $guarantordata->{'title'};
253 if ( $op eq 'add' ) {
254 foreach (qw(streetnumber address streettype address2
255 zipcode country city state phone phonepro mobile fax email emailpro branchcode
256 B_streetnumber B_streettype B_address B_address2
257 B_city B_state B_zipcode B_country B_email B_phone)) {
258 $newdata{$_} = $guarantordata->{$_};
264 ###############test to take the right zipcode, country and city name ##############
265 # set only if parameter was passed from the form
266 $newdata{'city'} = $input->param('city') if defined($input->param('city'));
267 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
268 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
270 # builds default userid
271 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
272 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ ) {
273 if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
274 # Full page edit, firstname and surname input zones are present
275 $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
277 elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
278 # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
279 # Still, if the userid field is erased, we can create a new userid with available firstname and surname
280 $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
282 else {
283 $newdata{'userid'} = $data{'userid'};
287 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
288 my $extended_patron_attributes = ();
289 if ($op eq 'save' || $op eq 'insert'){
291 die "Wrong CSRF token"
292 unless Koha::Token->new->check_csrf({
293 id => Encode::encode( 'UTF-8', C4::Context->userenv->{id} ),
294 secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
295 token => scalar $input->param('csrf_token'),
298 # If the cardnumber is blank, treat it as null.
299 $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
301 if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
302 push @errors, $error_code == 1
303 ? 'ERROR_cardnumber_already_exists'
304 : $error_code == 2
305 ? 'ERROR_cardnumber_length'
306 : ()
309 my $dateofbirth;
310 if ($op eq 'save' && $step == 3) {
311 my $borrower = C4::Members::GetMember(borrowernumber => $borrowernumber);
312 $dateofbirth = $borrower->{dateofbirth};
314 else {
315 $dateofbirth = $newdata{dateofbirth};
318 if ( $dateofbirth ) {
319 my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
320 my $age = $patron->get_age;
321 my $borrowercategory = Koha::Patron::Categories->find($categorycode);
322 my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
323 if (($high && ($age > $high)) or ($age < $low)) {
324 push @errors, 'ERROR_age_limitations';
325 $template->param( age_low => $low);
326 $template->param( age_high => $high);
330 if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
331 $newdata{'surname'} = uc($newdata{'surname'});
334 if (C4::Context->preference("IndependentBranches")) {
335 unless ( C4::Context->IsSuperLibrarian() ){
336 $debug and print STDERR " $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
337 unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
338 push @errors, "ERROR_branch";
342 # Check if the 'userid' is unique. 'userid' might not always be present in
343 # the edited values list when editing certain sub-forms. Get it straight
344 # from the DB if absent.
345 my $userid = $newdata{ userid } // $borrower_data->{ userid };
346 unless (Check_Userid($userid,$borrowernumber)) {
347 push @errors, "ERROR_login_exist";
350 my $password = $input->param('password');
351 my $password2 = $input->param('password2');
352 push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
353 push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
355 # Validate emails
356 my $emailprimary = $input->param('email');
357 my $emailsecondary = $input->param('emailpro');
358 my $emailalt = $input->param('B_email');
360 if ($emailprimary) {
361 push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
363 if ($emailsecondary) {
364 push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
366 if ($emailalt) {
367 push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
370 if (C4::Context->preference('ExtendedPatronAttributes')) {
371 $extended_patron_attributes = parse_extended_patron_attributes($input);
372 foreach my $attr (@$extended_patron_attributes) {
373 unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
374 my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
375 push @errors, "ERROR_extended_unique_id_failed";
376 $template->param(
377 ERROR_extended_unique_id_failed_code => $attr->{code},
378 ERROR_extended_unique_id_failed_value => $attr->{value},
379 ERROR_extended_unique_id_failed_description => $attr_info->description()
386 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
387 unless ($newdata{'dateexpiry'}){
388 my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
389 $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
393 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
394 my $sms = $input->param('SMSnumber');
395 if ( defined $sms ) {
396 $newdata{smsalertnumber} = $sms;
399 ### Error checks should happen before this line.
400 $nok = $nok || scalar(@errors);
401 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
402 $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
403 if ($op eq 'insert'){
404 # we know it's not a duplicate borrowernumber or there would already be an error
405 $borrowernumber = &AddMember(%newdata);
406 $newdata{'borrowernumber'} = $borrowernumber;
408 # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
409 if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'} && $newdata{'password'}) {
410 #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
411 my $emailaddr;
412 if (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF' &&
413 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~ /\w\@\w/ ) {
414 $emailaddr = $newdata{C4::Context->preference("AutoEmailPrimaryAddress")}
416 elsif ($newdata{email} =~ /\w\@\w/) {
417 $emailaddr = $newdata{email}
419 elsif ($newdata{emailpro} =~ /\w\@\w/) {
420 $emailaddr = $newdata{emailpro}
422 elsif ($newdata{B_email} =~ /\w\@\w/) {
423 $emailaddr = $newdata{B_email}
425 # if we manage to find a valid email address, send notice
426 if ($emailaddr) {
427 $newdata{emailaddr} = $emailaddr;
428 my $err;
429 eval {
430 $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
432 if ( $@ ) {
433 $template->param(error_alert => $@);
434 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
435 $template->{VARS}->{'error_alert'} = "no_email";
436 } else {
437 $template->{VARS}->{'info_alert'} = 1;
442 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
443 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
445 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
446 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
448 # Try to do the live sync with the Norwegian national patron database, if it is enabled
449 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
450 NLSync({ 'borrowernumber' => $borrowernumber });
453 # Create HouseboundRole if necessary.
454 # Borrower did not exist, so HouseboundRole *cannot* yet exist.
455 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
456 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
457 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
458 # Only create a HouseboundRole if patron has a role.
459 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
460 Koha::Patron::HouseboundRole->new({
461 borrowernumber_id => $borrowernumber,
462 housebound_chooser => $hsbnd_chooser,
463 housebound_deliverer => $hsbnd_deliverer,
464 })->store;
467 } elsif ($op eq 'save') {
469 # Update or create our HouseboundRole if necessary.
470 my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
471 my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
472 $hsbnd_chooser = 1 if $input->param('housebound_chooser');
473 $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
474 if ( $housebound_role ) {
475 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
476 # Update our HouseboundRole.
477 $housebound_role
478 ->housebound_chooser($hsbnd_chooser)
479 ->housebound_deliverer($hsbnd_deliverer)
480 ->store;
481 } else {
482 $housebound_role->delete; # No longer needed.
484 } else {
485 # Only create a HouseboundRole if patron has a role.
486 if ( $hsbnd_chooser || $hsbnd_deliverer ) {
487 $housebound_role = Koha::Patron::HouseboundRole->new({
488 borrowernumber_id => $borrowernumber,
489 housebound_chooser => $hsbnd_chooser,
490 housebound_deliverer => $hsbnd_deliverer,
491 })->store;
495 if ($NoUpdateLogin) {
496 delete $newdata{'password'};
497 delete $newdata{'userid'};
499 &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
500 # updating any columns in the borrowers table,
501 # which can happen if we're only editing the
502 # patron attributes or messaging preferences sections
503 if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
504 C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
506 if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
507 C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
510 print scalar ($destination eq "circ") ?
511 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
512 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
513 exit; # You can only send 1 redirect! After that, content or other headers don't matter.
516 if ($delete){
517 print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
518 exit; # same as above
521 if ($nok or !$nodouble){
522 $op="add" if ($op eq "insert");
523 $op="modify" if ($op eq "save");
524 %data=%newdata;
525 $template->param( updtype => ($op eq 'add' ?'I':'M')); # used to check for $op eq "insert"... but we just changed $op!
526 unless ($step){
527 $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
530 if (C4::Context->preference("IndependentBranches")) {
531 my $userenv = C4::Context->userenv;
532 if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
533 unless ($userenv->{branch} eq $data{'branchcode'}){
534 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
535 exit;
539 if ($op eq 'add'){
540 $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
542 if ($op eq "modify") {
543 $template->param( updtype => 'M',modify => 1 );
544 $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
545 if ( $step == 4 ) {
546 $template->param( categorycode => $borrower_data->{'categorycode'} );
548 # Add sync data to the user data
549 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
550 my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
551 if ( $sync ) {
552 $template->param(
553 sync => $sync->sync,
558 if ( $op eq "duplicate" ) {
559 $template->param( updtype => 'I' );
560 $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
561 $data{'cardnumber'} = "";
564 if(!defined($data{'sex'})){
565 $template->param( none => 1);
566 } elsif($data{'sex'} eq 'F'){
567 $template->param( female => 1);
568 } elsif ($data{'sex'} eq 'M'){
569 $template->param( male => 1);
570 } else {
571 $template->param( none => 1);
574 ##Now all the data to modify a member.
576 my @typeloop;
577 my $no_categories = 1;
578 my $no_add;
579 foreach my $category_type (qw(C A S P I X)) {
580 my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
581 $no_categories = 0 if $patron_categories->count > 0;
583 my @categoryloop;
584 while ( my $patron_category = $patron_categories->next ) {
585 push @categoryloop,
586 { 'categorycode' => $patron_category->categorycode,
587 'categoryname' => $patron_category->description,
588 'categorycodeselected' =>
589 ( ( defined( $borrower_data->{'categorycode'} ) && $patron_category->categorycode eq $borrower_data->{'categorycode'} ) || ( defined($categorycode) && $patron_category->categorycode eq $categorycode ) ),
592 my %typehash;
593 $typehash{'typename'} = $category_type;
594 my $typedescription = "typename_" . $typehash{'typename'};
595 $typehash{'categoryloop'} = \@categoryloop;
596 push @typeloop,
597 { 'typename' => $category_type,
598 $typedescription => 1,
599 'categoryloop' => \@categoryloop
603 $template->param('typeloop' => \@typeloop,
604 no_categories => $no_categories);
605 if($no_categories){ $no_add = 1; }
608 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
609 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
610 $template->param(
611 roadtypes => $roadtypes,
612 cities => $cities,
615 my $default_borrowertitle = '';
616 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
618 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
619 my @relshipdata;
620 while (@relationships) {
621 my $relship = shift @relationships || '';
622 my %row = ('relationship' => $relship);
623 if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
624 $row{'selected'}=' selected';
625 } else {
626 $row{'selected'}='';
628 push(@relshipdata, \%row);
631 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
632 'lost' => ['lost']);
635 my @flagdata;
636 foreach (keys(%flags)) {
637 my $key = $_;
638 my %row = ('key' => $key,
639 'name' => $flags{$key}[0]);
640 if ($data{$key}) {
641 $row{'yes'}=' checked';
642 $row{'no'}='';
644 else {
645 $row{'yes'}='';
646 $row{'no'}=' checked';
648 push @flagdata,\%row;
651 # get Branch Loop
652 # in modify mod: userbranch value comes from borrowers table
653 # in add mod: userbranch value comes from branches table (ip correspondence)
655 my $userbranch = '';
656 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
657 $userbranch = C4::Context->userenv->{'branch'};
660 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
661 $userbranch = $data{'branchcode'};
663 $template->param( userbranch => $userbranch );
665 if ( Koha::Libraries->search->count < 1 ){
666 $no_add = 1;
667 $template->param(no_branches => 1);
669 if($no_categories){
670 $no_add = 1;
671 $template->param(no_categories => 1);
673 $template->param(no_add => $no_add);
674 # --------------------------------------------------------------------------------------------------------
676 $template->param( sort1 => $data{'sort1'});
677 $template->param( sort2 => $data{'sort2'});
679 if ($nok) {
680 foreach my $error (@errors) {
681 $template->param($error) || $template->param( $error => 1);
683 $template->param(nok => 1);
686 #Formatting data for display
688 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
689 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
691 if ( $op eq 'duplicate' ) {
692 $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
693 my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
694 $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
696 if (C4::Context->preference('uppercasesurnames')) {
697 $data{'surname'} &&= uc( $data{'surname'} );
698 $data{'contactname'} &&= uc( $data{'contactname'} );
701 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
702 if ( $data{$_} ) {
703 $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); }; # back to syspref for display
705 $template->param( $_ => $data{$_});
708 if (C4::Context->preference('ExtendedPatronAttributes')) {
709 $template->param(ExtendedPatronAttributes => 1);
710 patron_attributes_form($template, $borrowernumber);
713 if (C4::Context->preference('EnhancedMessagingPreferences')) {
714 if ($op eq 'add') {
715 C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
716 } else {
717 C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
719 $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
720 $template->param(SMSnumber => $data{'smsalertnumber'} );
721 $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
724 $template->param( "showguarantor" => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
725 $debug and warn "memberentry step: $step";
726 $template->param(%data);
727 $template->param( "step_$step" => 1) if $step; # associate with step to know where u are
728 $template->param( step => $step ) if $step; # associate with step to know where u are
730 $template->param(
731 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
732 category_type => $category_type,#to know the category type of the borrower
733 "$category_type" => 1,# associate with step to know where u are
734 destination => $destination,#to know wher u come from and wher u must go in redirect
735 check_member => $check_member,#to know if the borrower already exist(=>1) or not (=>0)
736 "op$op" => 1);
738 $template->param(
739 nodouble => $nodouble,
740 borrowernumber => $borrowernumber, #register number
741 guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
742 relshiploop => \@relshipdata,
743 btitle=> $default_borrowertitle,
744 guarantorinfo => $guarantorinfo,
745 flagloop => \@flagdata,
746 category_type =>$category_type,
747 modify => $modify,
748 nok => $nok,#flag to know if an error
749 NoUpdateLogin => $NoUpdateLogin,
752 # Generate CSRF token
753 $template->param(
754 csrf_token => Koha::Token->new->generate_csrf(
755 { id => Encode::encode( 'UTF-8', C4::Context->userenv->{id} ),
756 secret => md5_base64( Encode::encode( 'UTF-8', C4::Context->config('pass') ) ),
761 # HouseboundModule data
762 $template->param(
763 housebound_role => Koha::Patron::HouseboundRoles->find($borrowernumber),
766 if(defined($data{'flags'})){
767 $template->param(flags=>$data{'flags'});
769 if(defined($data{'contacttitle'})){
770 $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
774 my ( $min, $max ) = C4::Members::get_cardnumber_length();
775 if ( defined $min ) {
776 $template->param(
777 minlength_cardnumber => $min,
778 maxlength_cardnumber => $max
782 output_html_with_http_headers $input, $cookie, $template->output;
784 sub parse_extended_patron_attributes {
785 my ($input) = @_;
786 my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
788 my @attr = ();
789 my %dups = ();
790 foreach my $key (@patron_attr) {
791 my $value = $input->param($key);
792 next unless defined($value) and $value ne '';
793 my $code = $input->param("${key}_code");
794 next if exists $dups{$code}->{$value};
795 $dups{$code}->{$value} = 1;
796 push @attr, { code => $code, value => $value };
798 return \@attr;
801 sub patron_attributes_form {
802 my $template = shift;
803 my $borrowernumber = shift;
805 my @types = C4::Members::AttributeTypes::GetAttributeTypes();
806 if (scalar(@types) == 0) {
807 $template->param(no_patron_attribute_types => 1);
808 return;
810 my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
811 my @classes = uniq( map {$_->{class}} @$attributes );
812 @classes = sort @classes;
814 # map patron's attributes into a more convenient structure
815 my %attr_hash = ();
816 foreach my $attr (@$attributes) {
817 push @{ $attr_hash{$attr->{code}} }, $attr;
820 my @attribute_loop = ();
821 my $i = 0;
822 my %items_by_class;
823 foreach my $type_code (map { $_->{code} } @types) {
824 my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
825 my $entry = {
826 class => $attr_type->class(),
827 code => $attr_type->code(),
828 description => $attr_type->description(),
829 repeatable => $attr_type->repeatable(),
830 category => $attr_type->authorised_value_category(),
831 category_code => $attr_type->category_code(),
833 if (exists $attr_hash{$attr_type->code()}) {
834 foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
835 my $newentry = { %$entry };
836 $newentry->{value} = $attr->{value};
837 $newentry->{use_dropdown} = 0;
838 if ($attr_type->authorised_value_category()) {
839 $newentry->{use_dropdown} = 1;
840 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
842 $i++;
843 $newentry->{form_id} = "patron_attr_$i";
844 push @{$items_by_class{$attr_type->class()}}, $newentry;
846 } else {
847 $i++;
848 my $newentry = { %$entry };
849 if ($attr_type->authorised_value_category()) {
850 $newentry->{use_dropdown} = 1;
851 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
853 $newentry->{form_id} = "patron_attr_$i";
854 push @{$items_by_class{$attr_type->class()}}, $newentry;
857 while ( my ($class, @items) = each %items_by_class ) {
858 my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
859 my $lib = $av->count ? $av->next->lib : $class;
860 push @attribute_loop, {
861 class => $class,
862 items => @items,
863 lib => $lib,
867 $template->param(patron_attributes => \@attribute_loop);
871 # Local Variables:
872 # tab-width: 8
873 # End: