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