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