Bug 10020: Remove code related to ethnicity
[koha.git] / members / memberentry.pl
1 #!/usr/bin/perl
2
3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 # Copyright 2010 BibLibre
5 #
6 # This file is part of Koha.
7 #
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.
12 #
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.
17 #
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>.
20
21 # pragma
22 use strict;
23 use warnings;
24
25 # external modules
26 use CGI qw ( -utf8 );
27 # use Digest::MD5 qw(md5_base64);
28 use List::MoreUtils qw/uniq/;
29
30 # internal modules
31 use C4::Auth;
32 use C4::Context;
33 use C4::Output;
34 use C4::Members;
35 use C4::Members::Attributes;
36 use C4::Members::AttributeTypes;
37 use C4::Koha;
38 use C4::Dates qw/format_date format_date_in_iso/;
39 use C4::Log;
40 use C4::Letters;
41 use C4::Branch; # GetBranches
42 use C4::Form::MessagingPreferences;
43 use Koha::Borrower::Debarments;
44 use Koha::DateUtils;
45 use Email::Valid;
46 use Module::Load;
47 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
48     load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
49 }
50
51 use vars qw($debug);
52
53 BEGIN {
54         $debug = $ENV{DEBUG} || 0;
55 }
56         
57 my $input = new CGI;
58 ($debug) or $debug = $input->param('debug') || 0;
59 my %data;
60
61 my $dbh = C4::Context->dbh;
62
63 my ($template, $loggedinuser, $cookie)
64     = get_template_and_user({template_name => "members/memberentrygen.tt",
65            query => $input,
66            type => "intranet",
67            authnotrequired => 0,
68            flagsrequired => {borrowers => 1},
69            debug => ($debug) ? 1 : 0,
70        });
71
72 my $guarantorid    = $input->param('guarantorid');
73 my $borrowernumber = $input->param('borrowernumber');
74 my $actionType     = $input->param('actionType') || '';
75 my $modify         = $input->param('modify');
76 my $delete         = $input->param('delete');
77 my $op             = $input->param('op');
78 my $destination    = $input->param('destination');
79 my $cardnumber     = $input->param('cardnumber');
80 my $check_member   = $input->param('check_member');
81 my $nodouble       = $input->param('nodouble');
82 my $duplicate      = $input->param('duplicate');
83 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
84                                      # modifying an existing patron, it ipso facto
85                                      # isn't a duplicate.  Marking FIXME because this
86                                      # script needs to be refactored.
87 my $select_city   = $input->param('select_city');
88 my $nok           = $input->param('nok');
89 my $guarantorinfo = $input->param('guarantorinfo');
90 my $step          = $input->param('step') || 0;
91 my @errors;
92 my $default_city;
93 my $borrower_data;
94 my $NoUpdateLogin;
95 my $userenv = C4::Context->userenv;
96
97
98 ## Deal with debarments
99 $template->param(
100     debarments => GetDebarments( { borrowernumber => $borrowernumber } ) );
101 my @debarments_to_remove = $input->param('remove_debarment');
102 foreach my $d ( @debarments_to_remove ) {
103     DelDebarment( $d );
104 }
105 if ( $input->param('add_debarment') ) {
106
107     my $expiration = $input->param('debarred_expiration');
108     $expiration =
109       $expiration
110       ? output_pref(
111         { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
112       : undef;
113
114     AddDebarment(
115         {
116             borrowernumber => $borrowernumber,
117             type           => 'MANUAL',
118             comment        => $input->param('debarred_comment'),
119             expiration     => $expiration,
120         }
121     );
122 }
123
124 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
125
126 my $minpw = C4::Context->preference('minPasswordLength');
127 $template->param("minPasswordLength" => $minpw);
128
129 # function to designate mandatory fields (visually with css)
130 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
131 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
132 foreach (@field_check) {
133         $template->param( "mandatory$_" => 1);    
134 }
135 # function to designate unwanted fields
136 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
137 @field_check=split(/\|/,$check_BorrowerUnwantedField);
138 foreach (@field_check) {
139     next unless m/\w/o;
140         $template->param( "no$_" => 1);
141 }
142 $template->param( "add" => 1 ) if ( $op eq 'add' );
143 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
144 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
145 ( $borrower_data = GetMember( 'borrowernumber' => $borrowernumber ) ) if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' );
146 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
147 my $category_type = $input->param('category_type') || '';
148 unless ($category_type or !($categorycode)){
149     my $borrowercategory = GetBorrowercategory($categorycode);
150     $category_type    = $borrowercategory->{'category_type'};
151     my $category_name = $borrowercategory->{'description'}; 
152     $template->param("categoryname"=>$category_name);
153 }
154 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
155
156 # if a add or modify is requested => check validity of data.
157 %data = %$borrower_data if ($borrower_data);
158
159 # initialize %newdata
160 my %newdata;                                                                             # comes from $input->param()
161 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
162     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
163     foreach my $key (@names) {
164         if (defined $input->param($key)) {
165             $newdata{$key} = $input->param($key);
166             $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
167         }
168     }
169
170     my $dateobject = C4::Dates->new();
171     my $syspref = $dateobject->regexp();                # same syspref format for all 3 dates
172     my $iso     = $dateobject->regexp('iso');   #
173     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
174         next unless exists $newdata{$_};
175         my $userdate = $newdata{$_} or next;
176         if ($userdate =~ /$syspref/) {
177             $newdata{$_} = format_date_in_iso($userdate);       # if they match syspref format, then convert to ISO
178         } elsif ($userdate =~ /$iso/) {
179             warn "Date $_ ($userdate) is already in ISO format";
180         } else {
181             ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
182             $template->param( "ERROR_$_" => 1 );        # else ERROR!
183             push(@errors,"ERROR_$_");
184         }
185     }
186   # check permission to modify login info.
187     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
188         $NoUpdateLogin = 1;
189     }
190 }
191
192 # remove keys from %newdata that ModMember() doesn't like
193 {
194     my @keys_to_delete = (
195         qr/^BorrowerMandatoryField$/,
196         qr/^category_type$/,
197         qr/^check_member$/,
198         qr/^destination$/,
199         qr/^nodouble$/,
200         qr/^op$/,
201         qr/^save$/,
202         qr/^updtype$/,
203         qr/^SMSnumber$/,
204         qr/^setting_extended_patron_attributes$/,
205         qr/^setting_messaging_prefs$/,
206         qr/^digest$/,
207         qr/^modify$/,
208         qr/^step$/,
209         qr/^\d+$/,
210         qr/^\d+-DAYS/,
211         qr/^patron_attr_/,
212     );
213     for my $regexp (@keys_to_delete) {
214         for (keys %newdata) {
215             delete($newdata{$_}) if /$regexp/;
216         }
217     }
218 }
219
220 #############test for member being unique #############
221 if ( ( $op eq 'insert' ) and !$nodouble ) {
222     my $category_type_send;
223     if ( $category_type eq 'I' ) {
224         $category_type_send = $category_type;
225     }
226     my $check_category;    # recover the category code of the doublon suspect borrowers
227      #   ($result,$categorycode) = checkuniquemember($collectivity,$surname,$firstname,$dateofbirth)
228     ( $check_member, $check_category ) = checkuniquemember(
229         $category_type_send,
230         ( $newdata{surname}     ? $newdata{surname}     : $data{surname} ),
231         ( $newdata{firstname}   ? $newdata{firstname}   : $data{firstname} ),
232         ( $newdata{dateofbirth} ? $newdata{dateofbirth} : $data{dateofbirth} )
233     );
234     if ( !$check_member ) {
235         $nodouble = 1;
236     }
237 }
238
239   #recover all data from guarantor address phone ,fax... 
240 if ( $guarantorid ) {
241     if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
242         $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
243         $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
244         $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
245         $newdata{'contactname'}     = $guarantordata->{'surname'};
246         $newdata{'contacttitle'}    = $guarantordata->{'title'};
247         if ( $op eq 'add' ) {
248                 foreach (qw(streetnumber address streettype address2
249                         zipcode country city state phone phonepro mobile fax email emailpro branchcode
250                         B_streetnumber B_streettype B_address B_address2
251                         B_city B_state B_zipcode B_country B_email B_phone)) {
252                         $newdata{$_} = $guarantordata->{$_};
253                 }
254         }
255     }
256 }
257
258 ###############test to take the right zipcode, country and city name ##############
259 # set only if parameter was passed from the form
260 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
261 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
262 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
263
264 #builds default userid
265 if ( (defined $newdata{'userid'}) && ($newdata{'userid'} eq '')){
266     if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
267         # Full page edit, firstname and surname input zones are present
268         $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
269     }
270     elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
271         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
272         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
273         $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
274     }
275     else {
276         $newdata{'userid'} = $data{'userid'};
277     }
278 }
279   
280 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
281 my $extended_patron_attributes = ();
282 if ($op eq 'save' || $op eq 'insert'){
283     # If the cardnumber is blank, treat it as null.
284     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
285
286     if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
287         push @errors, $error_code == 1
288             ? 'ERROR_cardnumber_already_exists'
289             : $error_code == 2
290                 ? 'ERROR_cardnumber_length'
291                 : ()
292     }
293
294     if ( $newdata{dateofbirth} ) {
295         my $age = GetAge($newdata{dateofbirth});
296         my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});   
297         my ($low,$high) = ($borrowercategory->{'dateofbirthrequired'}, $borrowercategory->{'upperagelimit'});
298         if (($high && ($age > $high)) or ($age < $low)) {
299             push @errors, 'ERROR_age_limitations';
300             $template->param( age_low => $low);
301             $template->param( age_high => $high);
302         }
303     }
304   
305     if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
306         $newdata{'surname'} = uc($newdata{'surname'});
307     }
308
309   if (C4::Context->preference("IndependentBranches")) {
310     unless ( C4::Context->IsSuperLibrarian() ){
311       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
312       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
313         push @errors, "ERROR_branch";
314       }
315     }
316   }
317   # Check if the 'userid' is unique. 'userid' might not always be present in
318   # the edited values list when editing certain sub-forms. Get it straight
319   # from the DB if absent.
320   my $userid = $newdata{ userid } // $borrower_data->{ userid };
321   unless (Check_Userid($userid,$borrowernumber)) {
322     push @errors, "ERROR_login_exist";
323   }
324   
325   my $password = $input->param('password');
326   my $password2 = $input->param('password2');
327   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
328   push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
329
330   # Validate emails
331   my $emailprimary = $input->param('email');
332   my $emailsecondary = $input->param('emailpro');
333   my $emailalt = $input->param('B_email');
334
335   if ($emailprimary) {
336       push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
337   }
338   if ($emailsecondary) {
339       push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
340   }
341   if ($emailalt) {
342       push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
343   }
344
345   if (C4::Context->preference('ExtendedPatronAttributes')) {
346     $extended_patron_attributes = parse_extended_patron_attributes($input);
347     foreach my $attr (@$extended_patron_attributes) {
348         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
349             my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
350             push @errors, "ERROR_extended_unique_id_failed";
351             $template->param(
352                 ERROR_extended_unique_id_failed_code => $attr->{code},
353                 ERROR_extended_unique_id_failed_value => $attr->{value},
354                 ERROR_extended_unique_id_failed_description => $attr_info->description()
355             );
356         }
357     }
358   }
359 }
360
361 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
362     unless ($newdata{'dateexpiry'}){
363         my $arg2 = $newdata{'dateenrolled'} || C4::Dates->today('iso');
364         $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
365     }
366 }
367
368 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
369 my $sms = $input->param('SMSnumber');
370 if ( defined $sms ) {
371     $newdata{smsalertnumber} = $sms;
372 }
373
374 ###  Error checks should happen before this line.
375 $nok = $nok || scalar(@errors);
376 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
377         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
378         if ($op eq 'insert'){
379                 # we know it's not a duplicate borrowernumber or there would already be an error
380         $borrowernumber = &AddMember(%newdata);
381         $newdata{'borrowernumber'} = $borrowernumber;
382
383         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
384         if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'}  && $newdata{'password'}) {
385             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
386             my $emailaddr;
387             if  (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF'  && 
388                 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~  /\w\@\w/ ) {
389                 $emailaddr =   $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} 
390             } 
391             elsif ($newdata{email} =~ /\w\@\w/) {
392                 $emailaddr = $newdata{email} 
393             }
394             elsif ($newdata{emailpro} =~ /\w\@\w/) {
395                 $emailaddr = $newdata{emailpro} 
396             }
397             elsif ($newdata{B_email} =~ /\w\@\w/) {
398                 $emailaddr = $newdata{B_email} 
399             }
400             # if we manage to find a valid email address, send notice 
401             if ($emailaddr) {
402                 $newdata{emailaddr} = $emailaddr;
403                 my $err;
404                 eval {
405                     $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
406                 };
407                 if ( $@ ) {
408                     $template->param(error_alert => $@);
409                 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
410                     $template->{VARS}->{'error_alert'} = "no_email";
411                 } else {
412                     $template->{VARS}->{'info_alert'} = 1;
413                 }
414             }
415         }
416
417         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
418             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
419         }
420         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
421             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
422         }
423         # Try to do the live sync with the Norwegian national patron database, if it is enabled
424         if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
425             NLSync({ 'borrowernumber' => $borrowernumber });
426         }
427         } elsif ($op eq 'save'){ 
428                 if ($NoUpdateLogin) {
429                         delete $newdata{'password'};
430                         delete $newdata{'userid'};
431                 }
432         &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
433                                                                 # updating any columns in the borrowers table,
434                                                                 # which can happen if we're only editing the
435                                                                 # patron attributes or messaging preferences sections
436         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
437             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
438         }
439         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
440             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
441         }
442         }
443         print scalar ($destination eq "circ") ? 
444                 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
445                 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
446         exit;           # You can only send 1 redirect!  After that, content or other headers don't matter.
447 }
448
449 if ($delete){
450         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
451         exit;           # same as above
452 }
453
454 if ($nok or !$nodouble){
455     $op="add" if ($op eq "insert");
456     $op="modify" if ($op eq "save");
457     %data=%newdata; 
458     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
459     unless ($step){  
460         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
461     }  
462
463 if (C4::Context->preference("IndependentBranches")) {
464     my $userenv = C4::Context->userenv;
465     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
466         unless ($userenv->{branch} eq $data{'branchcode'}){
467             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
468             exit;
469         }
470     }
471 }
472 if ($op eq 'add'){
473     $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
474 }
475 if ($op eq "modify")  {
476     $template->param( updtype => 'M',modify => 1 );
477     $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
478     if ( $step == 4 ) {
479         $template->param( categorycode => $borrower_data->{'categorycode'} );
480     }
481     # Add sync data to the user data
482     if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
483         my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
484         if ( $sync ) {
485             $template->param(
486                 sync => $sync->sync,
487             );
488         }
489     }
490 }
491 if ( $op eq "duplicate" ) {
492     $template->param( updtype => 'I' );
493     $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
494     $data{'cardnumber'} = "";
495 }
496
497 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if ( ( $op eq 'add' ) or ( $op eq 'duplicate' ) );
498 if(!defined($data{'sex'})){
499     $template->param( none => 1);
500 } elsif($data{'sex'} eq 'F'){
501     $template->param( female => 1);
502 } elsif ($data{'sex'} eq 'M'){
503     $template->param(  male => 1);
504 } else {
505     $template->param(  none => 1);
506 }
507
508 ##Now all the data to modify a member.
509
510 my @typeloop;
511 my $no_categories = 1;
512 my $no_add;
513 foreach (qw(C A S P I X)) {
514     my $action="WHERE category_type=?";
515     my ($categories,$labels)=GetborCatFromCatType($_,$action);
516     if(scalar(@$categories) > 0){ $no_categories = 0; }
517         my @categoryloop;
518         foreach my $cat (@$categories){
519                 push @categoryloop,{'categorycode' => $cat,
520                           'categoryname' => $labels->{$cat},
521                           'categorycodeselected' => ((defined($borrower_data->{'categorycode'}) && 
522                                                      $cat eq $borrower_data->{'categorycode'}) 
523                                                      || (defined($categorycode) && $cat eq $categorycode)),
524                 };
525         }
526         my %typehash;
527         $typehash{'typename'}=$_;
528     my $typedescription = "typename_".$typehash{'typename'};
529         $typehash{'categoryloop'}=\@categoryloop;
530         push @typeloop,{'typename' => $_,
531         $typedescription => 1,
532           'categoryloop' => \@categoryloop};
533 }
534 $template->param('typeloop' => \@typeloop,
535         no_categories => $no_categories);
536 if($no_categories){ $no_add = 1; }
537 # test in city
538 if ( $guarantorid ) {
539     $select_city = getidcity($data{city});
540 }
541 ($default_city=$select_city) if ($step eq 0);
542 if (!defined($select_city) or $select_city eq '' ){
543         $default_city = &getidcity($data{'city'});
544 }
545
546 my $city_arrayref = GetCities();
547 if (@{$city_arrayref} ) {
548     $template->param( city_cgipopup => 1);
549
550     if ($default_city) { # flag the current or default val
551         for my $city ( @{$city_arrayref} ) {
552             if ($default_city == $city->{cityid}) {
553                 $city->{selected} = 1;
554                 last;
555             }
556         }
557     }
558 }
559   
560 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE', $data{streettype} );
561 $template->param( roadtypes => $roadtypes);
562
563 my $default_borrowertitle = '';
564 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
565 my($borrowertitle)=GetTitles();
566 $template->param( title_cgipopup => 1) if ($borrowertitle);
567 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
568         -id => 'btitle',
569         -values=>$borrowertitle,
570         -override => 1,
571         -default=>$default_borrowertitle
572         );    
573
574 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
575 my @relshipdata;
576 while (@relationships) {
577   my $relship = shift @relationships || '';
578   my %row = ('relationship' => $relship);
579   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
580     $row{'selected'}=' selected';
581   } else {
582     $row{'selected'}='';
583   }
584   push(@relshipdata, \%row);
585 }
586
587 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
588         'lost'          => ['lost']);
589
590  
591 my @flagdata;
592 foreach (keys(%flags)) {
593         my $key = $_;
594         my %row =  ('key'   => $key,
595                     'name'  => $flags{$key}[0]);
596         if ($data{$key}) {
597                 $row{'yes'}=' checked';
598                 $row{'no'}='';
599     }
600         else {
601                 $row{'yes'}='';
602                 $row{'no'}=' checked';
603         }
604         push @flagdata,\%row;
605 }
606
607 # get Branch Loop
608 # in modify mod: userbranch value for GetBranchesLoop() comes from borrowers table
609 # in add    mod: userbranch value come from branches table (ip correspondence)
610
611 my $userbranch = '';
612 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
613     $userbranch = C4::Context->userenv->{'branch'};
614 }
615
616 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
617     $userbranch = $data{'branchcode'};
618 }
619
620 my $branchloop = GetBranchesLoop( $userbranch );
621
622 if( !$branchloop ){
623     $no_add = 1;
624     $template->param(no_branches => 1);
625 }
626 if($no_categories){
627     $no_add = 1;
628     $template->param(no_categories => 1);
629 }
630 $template->param(no_add => $no_add);
631 # --------------------------------------------------------------------------------------------------------
632
633 $template->param( sort1 => $data{'sort1'});
634 $template->param( sort2 => $data{'sort2'});
635
636 if ($nok) {
637     foreach my $error (@errors) {
638         $template->param($error) || $template->param( $error => 1);
639     }
640     $template->param(nok => 1);
641 }
642   
643   #Formatting data for display    
644   
645 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
646   $data{'dateenrolled'}=C4::Dates->today('iso');
647 }
648 if ( $op eq 'duplicate' ) {
649     $data{'dateenrolled'} = C4::Dates->today('iso');
650     $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, $data{'dateenrolled'} );
651 }
652 if (C4::Context->preference('uppercasesurnames')) {
653     $data{'surname'} &&= uc( $data{'surname'} );
654     $data{'contactname'} &&= uc( $data{'contactname'} );
655 }
656
657 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
658         $data{$_} = format_date($data{$_});     # back to syspref for display
659         $template->param( $_ => $data{$_});
660 }
661
662 if (C4::Context->preference('ExtendedPatronAttributes')) {
663     $template->param(ExtendedPatronAttributes => 1);
664     patron_attributes_form($template, $borrowernumber);
665 }
666
667 if (C4::Context->preference('EnhancedMessagingPreferences')) {
668     if ($op eq 'add') {
669         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
670     } else {
671         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
672     }
673     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
674     $template->param(SMSnumber     => $data{'smsalertnumber'} );
675     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
676 }
677
678 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
679 $debug and warn "memberentry step: $step";
680 $template->param(%data);
681 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
682 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
683
684 $template->param(
685   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
686   category_type => $category_type,#to know the category type of the borrower
687   select_city => $select_city,
688   "$category_type"  => 1,# associate with step to know where u are
689   destination   => $destination,#to know wher u come from and wher u must go in redirect
690   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
691   "op$op"   => 1);
692
693 $template->param( branchloop => $branchloop ) if ( $branchloop );
694 $template->param(
695   nodouble  => $nodouble,
696   borrowernumber  => $borrowernumber, #register number
697   guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
698   relshiploop => \@relshipdata,
699   city_loop => $city_arrayref,
700   borrotitlepopup => $borrotitlepopup,
701   guarantorinfo   => $guarantorinfo,
702   flagloop  => \@flagdata,
703   category_type =>$category_type,
704   modify          => $modify,
705   nok     => $nok,#flag to konw if an error 
706   NoUpdateLogin =>  $NoUpdateLogin
707   );
708
709 if(defined($data{'flags'})){
710   $template->param(flags=>$data{'flags'});
711 }
712 if(defined($data{'contacttitle'})){
713   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
714 }
715
716
717 my ( $min, $max ) = C4::Members::get_cardnumber_length();
718 if ( defined $min ) {
719     $template->param(
720         minlength_cardnumber => $min,
721         maxlength_cardnumber => $max
722     );
723 }
724
725 output_html_with_http_headers $input, $cookie, $template->output;
726
727 sub  parse_extended_patron_attributes {
728     my ($input) = @_;
729     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->param();
730
731     my @attr = ();
732     my %dups = ();
733     foreach my $key (@patron_attr) {
734         my $value = $input->param($key);
735         next unless defined($value) and $value ne '';
736         my $password = $input->param("${key}_password");
737         my $code     = $input->param("${key}_code");
738         next if exists $dups{$code}->{$value};
739         $dups{$code}->{$value} = 1;
740         push @attr, { code => $code, value => $value, password => $password };
741     }
742     return \@attr;
743 }
744
745 sub patron_attributes_form {
746     my $template = shift;
747     my $borrowernumber = shift;
748
749     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
750     if (scalar(@types) == 0) {
751         $template->param(no_patron_attribute_types => 1);
752         return;
753     }
754     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
755     my @classes = uniq( map {$_->{class}} @$attributes );
756     @classes = sort @classes;
757
758     # map patron's attributes into a more convenient structure
759     my %attr_hash = ();
760     foreach my $attr (@$attributes) {
761         push @{ $attr_hash{$attr->{code}} }, $attr;
762     }
763
764     my @attribute_loop = ();
765     my $i = 0;
766     my %items_by_class;
767     foreach my $type_code (map { $_->{code} } @types) {
768         my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
769         my $entry = {
770             class             => $attr_type->class(),
771             code              => $attr_type->code(),
772             description       => $attr_type->description(),
773             repeatable        => $attr_type->repeatable(),
774             password_allowed  => $attr_type->password_allowed(),
775             category          => $attr_type->authorised_value_category(),
776             category_code     => $attr_type->category_code(),
777             password          => '',
778         };
779         if (exists $attr_hash{$attr_type->code()}) {
780             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
781                 my $newentry = { %$entry };
782                 $newentry->{value} = $attr->{value};
783                 $newentry->{password} = $attr->{password};
784                 $newentry->{use_dropdown} = 0;
785                 if ($attr_type->authorised_value_category()) {
786                     $newentry->{use_dropdown} = 1;
787                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
788                 }
789                 $i++;
790                 $newentry->{form_id} = "patron_attr_$i";
791                 push @{$items_by_class{$attr_type->class()}}, $newentry;
792             }
793         } else {
794             $i++;
795             my $newentry = { %$entry };
796             if ($attr_type->authorised_value_category()) {
797                 $newentry->{use_dropdown} = 1;
798                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
799             }
800             $newentry->{form_id} = "patron_attr_$i";
801             push @{$items_by_class{$attr_type->class()}}, $newentry;
802         }
803     }
804     while ( my ($class, @items) = each %items_by_class ) {
805         my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
806         push @attribute_loop, {
807             class => $class,
808             items => @items,
809             lib   => $lib,
810         }
811     }
812
813     $template->param(patron_attributes => \@attribute_loop);
814
815 }
816
817 # Local Variables:
818 # tab-width: 8
819 # End: