Merge remote branch 'kc/new/enh/bug_3495' into kcmaster
[koha.git] / members / memberentry.pl
1 #!/usr/bin/perl
2
3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 # pragma
21 use strict;
22 use warnings;
23
24 # external modules
25 use CGI;
26 # use Digest::MD5 qw(md5_base64);
27
28 # internal modules
29 use C4::Auth;
30 use C4::Context;
31 use C4::Output;
32 use C4::Members;
33 use C4::Members::Attributes;
34 use C4::Members::AttributeTypes;
35 use C4::Koha;
36 use C4::Dates qw/format_date format_date_in_iso/;
37 use C4::Input;
38 use C4::Log;
39 use C4::Letters;
40 use C4::Branch; # GetBranches
41 use C4::Form::MessagingPreferences;
42
43 use vars qw($debug);
44
45 BEGIN {
46         $debug = $ENV{DEBUG} || 0;
47 }
48         
49 my $input = new CGI;
50 ($debug) or $debug = $input->param('debug') || 0;
51 my %data;
52
53 my $dbh = C4::Context->dbh;
54
55 my ($template, $loggedinuser, $cookie)
56     = get_template_and_user({template_name => "members/memberentrygen.tmpl",
57            query => $input,
58            type => "intranet",
59            authnotrequired => 0,
60            flagsrequired => {borrowers => 1},
61            debug => ($debug) ? 1 : 0,
62        });
63 my $guarantorid    = $input->param('guarantorid');
64 my $borrowernumber = $input->param('borrowernumber');
65 my $actionType     = $input->param('actionType') || '';
66 my $modify         = $input->param('modify');
67 my $delete         = $input->param('delete');
68 my $op             = $input->param('op');
69 my $destination    = $input->param('destination');
70 my $cardnumber     = $input->param('cardnumber');
71 my $check_member   = $input->param('check_member');
72 my $nodouble       = $input->param('nodouble');
73 my $duplicate      = $input->param('duplicate');
74 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
75                                      # modifying an existing patron, it ipso facto
76                                      # isn't a duplicate.  Marking FIXME because this
77                                      # script needs to be refactored.
78 my $select_city   = $input->param('select_city');
79 my $nok           = $input->param('nok');
80 my $guarantorinfo = $input->param('guarantorinfo');
81 my $step          = $input->param('step') || 0;
82 my @errors;
83 my $default_city;
84 # $check_categorytype contains the value of duplicate borrowers category type to redirect in good template in step =2
85 my $check_categorytype=$input->param('check_categorytype');
86 # NOTE: Alert for ethnicity and ethnotes fields, they are invalid in all borrowers form
87 my $borrower_data;
88 my $NoUpdateLogin;
89 my $userenv = C4::Context->userenv;
90
91 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
92
93 my $minpw = C4::Context->preference('minPasswordLength');
94 $template->param("minPasswordLength" => $minpw);
95
96 # function to designate mandatory fields (visually with css)
97 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
98 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
99 foreach (@field_check) {
100         $template->param( "mandatory$_" => 1);    
101 }
102 $template->param( "add" => 1 ) if ( $op eq 'add' );
103 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
104 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
105 ( $borrower_data = GetMember( 'borrowernumber' => $borrowernumber ) ) if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' );
106 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
107 my $category_type = $input->param('category_type');
108 my $new_c_type = $category_type; #if we have input param, then we've already chosen the cat_type.
109 unless ($category_type or !($categorycode)){
110     my $borrowercategory = GetBorrowercategory($categorycode);
111     $category_type    = $borrowercategory->{'category_type'};
112     my $category_name = $borrowercategory->{'description'}; 
113     $template->param("categoryname"=>$category_name);
114 }
115 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
116
117 # if a add or modify is requested => check validity of data.
118 %data = %$borrower_data if ($borrower_data);
119
120 # initialize %newdata
121 my %newdata;                                                                             # comes from $input->param()
122 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
123     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
124     foreach my $key (@names) {
125         if (defined $input->param($key)) {
126             $newdata{$key} = $input->param($key);
127             $newdata{$key} =~ s/\"/"/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
128         }
129     }
130     my $dateobject = C4::Dates->new();
131     my $syspref = $dateobject->regexp();                # same syspref format for all 3 dates
132     my $iso     = $dateobject->regexp('iso');   #
133     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
134         next unless exists $newdata{$_};
135         my $userdate = $newdata{$_} or next;
136         if ($userdate =~ /$syspref/) {
137             $newdata{$_} = format_date_in_iso($userdate);       # if they match syspref format, then convert to ISO
138         } elsif ($userdate =~ /$iso/) {
139             warn "Date $_ ($userdate) is already in ISO format";
140         } else {
141             ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
142             $template->param( "ERROR_$_" => 1 );        # else ERROR!
143             push(@errors,"ERROR_$_");
144         }
145     }
146   # check permission to modify login info.
147     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
148         $NoUpdateLogin = 1;
149     }
150 }
151
152 # remove keys from %newdata that ModMember() doesn't like
153 {
154     my @keys_to_delete = (
155         qr/^BorrowerMandatoryField$/,
156         qr/^category_type$/,
157         qr/^check_member$/,
158         qr/^destination$/,
159         qr/^nodouble$/,
160         qr/^op$/,
161         qr/^save$/,
162         qr/^select_roadtype$/,
163         qr/^updtype$/,
164         qr/^SMSnumber$/,
165         qr/^setting_extended_patron_attributes$/,
166         qr/^setting_messaging_prefs$/,
167         qr/^digest$/,
168         qr/^modify$/,
169         qr/^step$/,
170         qr/^\d+$/,
171         qr/^\d+-DAYS/,
172         qr/^patron_attr_/,
173     );
174     for my $regexp (@keys_to_delete) {
175         for (keys %newdata) {
176             delete($newdata{$_}) if /$regexp/;
177         }
178     }
179 }
180
181 #############test for member being unique #############
182 if (($op eq 'insert') and !$nodouble){
183         my $category_type_send=$category_type if ($category_type eq 'I'); 
184         my $check_category; # recover the category code of the doublon suspect borrowers
185                         #   ($result,$categorycode) = checkuniquemember($collectivity,$surname,$firstname,$dateofbirth)
186         ($check_member,$check_category) = checkuniquemember(
187                         $category_type_send, 
188                         ($newdata{surname}     ? $newdata{surname}     : $data{surname}    ),
189                         ($newdata{firstname}   ? $newdata{firstname}   : $data{firstname}  ),
190                         ($newdata{dateofbirth} ? $newdata{dateofbirth} : $data{dateofbirth})
191                 );
192         if(!$check_member){
193             $nodouble = 1;
194         }
195   #   recover the category type if the borrowers is a doublon
196     if ($check_category) {
197       my $tmpborrowercategory=GetBorrowercategory($check_category);
198       $check_categorytype=$tmpborrowercategory->{'category_type'};
199     }   
200 }
201
202   #recover all data from guarantor address phone ,fax... 
203 if ( $guarantorid and ( $category_type eq 'C' || $category_type eq 'P' )) {
204     if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
205         $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
206         if ( !defined($data{'contactname'}) or $data{'contactname'} eq '' or
207              $data{'contactname'} ne $guarantordata->{'surname'} ) {
208             $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
209             $newdata{'contactname'}     = $guarantordata->{'surname'};
210             $newdata{'contacttitle'}    = $guarantordata->{'title'};
211                 foreach (qw(streetnumber address streettype address2
212                         zipcode country city phone phonepro mobile fax email emailpro branchcode)) {
213                         $newdata{$_} = $guarantordata->{$_};
214                 }
215         }
216     }
217 }
218
219 ###############test to take the right zipcode, country and city name ##############
220 if (!defined($guarantorid) or $guarantorid eq '' or $guarantorid eq '0') {
221     # set only if parameter was passed from the form
222     $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
223     $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
224     $newdata{'country'} = $input->param('country') if defined($input->param('country'));
225 }
226
227 #builds default userid
228 if ( (defined $newdata{'userid'}) && ($newdata{'userid'} eq '')){
229     $newdata{'userid'} = Generate_Userid($borrowernumber, $newdata{'firstname'}, $newdata{'surname'});
230 }
231   
232 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
233 my $extended_patron_attributes = ();
234 if ($op eq 'save' || $op eq 'insert'){
235   if (checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){ 
236     push @errors, 'ERROR_cardnumber';
237   } 
238   my $dateofbirthmandatory = (scalar grep {$_ eq "dateofbirth"} @field_check) ? 1 : 0;
239   if ($newdata{dateofbirth} && $dateofbirthmandatory) {
240     my $age = GetAge($newdata{dateofbirth});
241     my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});   
242         my ($low,$high) = ($borrowercategory->{'dateofbirthrequired'}, $borrowercategory->{'upperagelimit'});
243     if (($high && ($age > $high)) or ($age < $low)) {
244       push @errors, 'ERROR_age_limitations';
245           $template->param('ERROR_age_limitations' => "$low to $high");
246     }
247   }
248   
249     if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
250         $newdata{'surname'} = uc($newdata{'surname'});
251     }
252
253   if (C4::Context->preference("IndependantBranches")) {
254     if ($userenv && $userenv->{flags} % 2 != 1){
255       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
256       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
257         push @errors, "ERROR_branch";
258       }
259     }
260   }
261   # Check if the userid is unique
262   unless (Check_Userid($newdata{'userid'},$borrowernumber)) {
263     push @errors, "ERROR_login_exist";
264   }
265   
266   my $password = $input->param('password');
267   push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
268
269   if (C4::Context->preference('ExtendedPatronAttributes')) {
270     $extended_patron_attributes = parse_extended_patron_attributes($input);
271     foreach my $attr (@$extended_patron_attributes) {
272         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
273             push @errors, "ERROR_extended_unique_id_failed";
274             $template->param(ERROR_extended_unique_id_failed => "$attr->{code}/$attr->{value}");
275         }
276     }
277   }
278 }
279
280 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
281     unless ($newdata{'dateexpiry'}){
282         my $arg2 = $newdata{'dateenrolled'} || C4::Dates->today('iso');
283         $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
284     }
285 }
286
287 if ( ( defined $input->param('SMSnumber') ) && ( $input->param('SMSnumber') ne $newdata{'mobile'} ) ) {
288     $newdata{smsalertnumber} = $input->param('SMSnumber');
289 }
290
291 ###  Error checks should happen before this line.
292 $nok = $nok || scalar(@errors);
293 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
294         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
295         if ($op eq 'insert'){
296                 # we know it's not a duplicate borrowernumber or there would already be an error
297         $borrowernumber = &AddMember(%newdata);
298
299         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
300         if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'}  && $newdata{'password'}) {
301             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
302             my $emailaddr;
303             if  (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF'  && 
304                 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~  /\w\@\w/ ) {
305                 $emailaddr =   $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} 
306             } 
307             elsif ($newdata{email} =~ /\w\@\w/) {
308                 $emailaddr = $newdata{email} 
309             }
310             elsif ($newdata{emailpro} =~ /\w\@\w/) {
311                 $emailaddr = $newdata{emailpro} 
312             }
313             elsif ($newdata{B_email} =~ /\w\@\w/) {
314                 $emailaddr = $newdata{B_email} 
315             }
316             # if we manage to find a valid email address, send notice 
317             if ($emailaddr) {
318                 $newdata{emailaddr} = $emailaddr;
319                 my $letter = getletter ('members', "ACCTDETAILS:$newdata{'branchcode'}") ;
320                 # if $branch notice fails, then email a default notice instead.
321                 $letter = getletter ('members', "ACCTDETAILS")  if !$letter;
322                 SendAlerts ( 'members' , \%newdata , $letter ) if $letter
323             }
324         } 
325
326                 if ($data{'organisations'}){            
327                         # need to add the members organisations
328                         my @orgs=split(/\|/,$data{'organisations'});
329                         add_member_orgs($borrowernumber,\@orgs);
330                 }
331         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
332             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
333         }
334         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
335             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
336         }
337         } elsif ($op eq 'save'){ 
338                 if ($NoUpdateLogin) {
339                         delete $newdata{'password'};
340                         delete $newdata{'userid'};
341                 }
342                 &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
343                                                                 # updating any columns in the borrowers table,
344                                                                 # which can happen if we're only editing the
345                                                                 # patron attributes or messaging preferences sections
346         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
347             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
348         }
349         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
350             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
351         }
352         }
353         print scalar ($destination eq "circ") ? 
354                 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
355                 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
356         exit;           # You can only send 1 redirect!  After that, content or other headers don't matter.
357 }
358
359 if ($delete){
360         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
361         exit;           # same as above
362 }
363
364 if ($nok or !$nodouble){
365     $op="add" if ($op eq "insert");
366     $op="modify" if ($op eq "save");
367     %data=%newdata; 
368     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
369     unless ($step){  
370         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
371     }  
372
373 if (C4::Context->preference("IndependantBranches")) {
374     my $userenv = C4::Context->userenv;
375     if ($userenv->{flags} % 2 != 1 && $data{branchcode}){
376         unless ($userenv->{branch} eq $data{'branchcode'}){
377             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
378             exit;
379         }
380     }
381 }
382 if ($op eq 'add'){
383     $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
384 }
385 if ($op eq "modify")  {
386     $template->param( updtype => 'M',modify => 1 );
387     $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
388 }
389 if ( $op eq "duplicate" ) {
390     $template->param( updtype => 'I' );
391     $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
392 }
393
394 # my $cardnumber=$data{'cardnumber'};
395 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if $op eq 'add';
396 if(!defined($data{'sex'})){
397     $template->param( none => 1);
398 } elsif($data{'sex'} eq 'F'){
399     $template->param( female => 1);
400 } elsif ($data{'sex'} eq 'M'){
401     $template->param(  male => 1);
402 } else {
403     $template->param(  none => 1);
404 }
405
406 ##Now all the data to modify a member.
407 my ($categories,$labels)=ethnicitycategories();
408   
409 my $ethnicitycategoriescount=$#{$categories};
410 my $ethcatpopup;
411 if ($ethnicitycategoriescount>=0) {
412   $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
413         -id => 'ethnicity',
414         -tabindex=>'',
415         -values=>$categories,
416         -default=>$data{'ethnicity'},
417         -labels=>$labels);
418   $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
419 }
420
421 my @typeloop;
422 my $no_categories = 1;
423 my $no_add;
424 foreach (qw(C A S P I X)) {
425     my $action="WHERE category_type=?";
426         ($categories,$labels)=GetborCatFromCatType($_,$action);
427     if(scalar(@$categories) > 0){ $no_categories = 0; }
428         my @categoryloop;
429         foreach my $cat (@$categories){
430                 push @categoryloop,{'categorycode' => $cat,
431                           'categoryname' => $labels->{$cat},
432                           'categorycodeselected' => ((defined($borrower_data->{'categorycode'}) && 
433                                                      $cat eq $borrower_data->{'categorycode'}) 
434                                                      || (defined($categorycode) && $cat eq $categorycode)),
435                 };
436         }
437         my %typehash;
438         $typehash{'typename'}=$_;
439     my $typedescription = "typename_".$typehash{'typename'};
440         $typehash{'categoryloop'}=\@categoryloop;
441         push @typeloop,{'typename' => $_,
442         $typedescription => 1,
443           'categoryloop' => \@categoryloop};
444 }
445 $template->param('typeloop' => \@typeloop,
446         no_categories => $no_categories);
447 if($no_categories){ $no_add = 1; }
448 # test in city
449 if ( $guarantorid ) {
450     $select_city = getidcity($data{city});
451 }
452 ($default_city=$select_city) if ($step eq 0);
453 if (!defined($select_city) or $select_city eq '' ){
454         $default_city = &getidcity($data{'city'});
455 }
456
457 my $city_arrayref = GetCities();
458 if (@{$city_arrayref} ) {
459     $template->param( city_cgipopup => 1);
460
461     if ($default_city) { # flag the current or default val
462         for my $city ( @{$city_arrayref} ) {
463             if ($default_city == $city->{cityid}) {
464                 $city->{selected} = 1;
465                 last;
466             }
467         }
468     }
469 }
470   
471 my $default_roadtype;
472 $default_roadtype=$data{'streettype'} ;
473 my($roadtypeid,$road_type)=GetRoadTypes();
474   $template->param( road_cgipopup => 1) if ($roadtypeid );
475 my $roadpopup = CGI::popup_menu(-name=>'streettype',
476         -id => 'streettype',
477         -values=>$roadtypeid,
478         -labels=>$road_type,
479         -override => 1,
480         -default=>$default_roadtype
481         );  
482
483 my $default_borrowertitle;
484 $default_borrowertitle=$data{'title'} ;
485 my($borrowertitle)=GetTitles();
486 $template->param( title_cgipopup => 1) if ($borrowertitle);
487 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
488         -id => 'btitle',
489         -values=>$borrowertitle,
490         -override => 1,
491         -default=>$default_borrowertitle
492         );    
493
494 my @relationships = split /,|\|/, C4::Context->preference('BorrowerRelationship');
495 my @relshipdata;
496 while (@relationships) {
497   my $relship = shift @relationships || '';
498   my %row = ('relationship' => $relship);
499   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
500     $row{'selected'}=' selected';
501   } else {
502     $row{'selected'}='';
503   }
504   push(@relshipdata, \%row);
505 }
506
507 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
508         'lost'          => ['lost'],
509         'debarred'      => ['debarred']);
510
511  
512 my @flagdata;
513 foreach (keys(%flags)) {
514         my $key = $_;
515         my %row =  ('key'   => $key,
516                     'name'  => $flags{$key}[0]);
517         if ($data{$key}) {
518                 $row{'yes'}=' checked';
519                 $row{'no'}='';
520     }
521         else {
522                 $row{'yes'}='';
523                 $row{'no'}=' checked';
524         }
525         push @flagdata,\%row;
526 }
527
528 #get Branches
529 my @branches;
530 my @select_branch;
531 my %select_branches;
532
533 my $onlymine=(C4::Context->preference('IndependantBranches') && 
534               C4::Context->userenv && 
535               C4::Context->userenv->{flags} % 2 !=1  && 
536               C4::Context->userenv->{branch}?1:0);
537               
538 my $branches=GetBranches($onlymine);
539 my $default;
540 my $CGIbranch;
541 for my $branch (sort { $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname} } keys %$branches) {
542     push @select_branch,$branch;
543     $select_branches{$branch} = $branches->{$branch}->{'branchname'};
544     $default = C4::Context->userenv->{'branch'} if (C4::Context->userenv && C4::Context->userenv->{'branch'});
545 }
546 if(scalar(@select_branch) > 0){
547 # --------------------------------------------------------------------------------------------------------
548   #in modify mod :default value from $CGIbranch comes from borrowers table
549   #in add mod: default value come from branches table (ip correspendence)
550 $default=$data{'branchcode'}  if ($op eq 'modify' || ($op eq 'add' && $category_type eq 'C'));
551 $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
552             -name   => 'branchcode',
553             -values => \@select_branch,
554             -labels => \%select_branches,
555             -size   => 1,
556             -override => 1,  
557             -multiple =>0,
558             -default => $default,
559         );
560 }
561
562 if(!$CGIbranch){
563     $no_add = 1;
564     $template->param(no_branches => 1);
565 }
566 if($no_categories){
567     $no_add = 1;
568     $template->param(no_categories => 1);
569 }
570 $template->param(no_add => $no_add);
571 my $CGIorganisations;
572 my $member_of_institution;
573 if (C4::Context->preference("memberofinstitution")){
574     my $organisations=get_institutions();
575     my @orgs;
576     my %org_labels;
577     foreach my $organisation (keys %$organisations) {
578         push @orgs,$organisation;
579         $org_labels{$organisation}=$organisations->{$organisation}->{'surname'};
580     }
581     $member_of_institution=1;
582
583     $CGIorganisations = CGI::scrolling_list( -id => 'organisations',
584         -name     => 'organisations',
585         -labels   => \%org_labels,
586         -values   => \@orgs,
587         -size     => 5,
588         -multiple => 'true'
589
590     );
591 }
592
593 # --------------------------------------------------------------------------------------------------------
594
595 my $CGIsort = buildCGIsort("Bsort1","sort1",$data{'sort1'});
596 if ($CGIsort) {
597     $template->param(CGIsort1 => $CGIsort);
598 }
599 $template->param( sort1 => $data{'sort1'});             # shouldn't this be in an "else" statement like the 2nd one?
600
601 $CGIsort = buildCGIsort("Bsort2","sort2",$data{'sort2'});
602 if ($CGIsort) {
603     $template->param(CGIsort2 => $CGIsort);
604 } else {
605     $template->param( sort2 => $data{'sort2'});
606 }
607
608 if ($nok) {
609     foreach my $error (@errors) {
610         $template->param($error) || $template->param( $error => 1);
611     }
612     $template->param(nok => 1);
613 }
614   
615   #Formatting data for display    
616   
617 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
618   $data{'dateenrolled'}=C4::Dates->today('iso');
619 }
620 if (C4::Context->preference('uppercasesurnames')) {
621         $data{'surname'}    =uc($data{'surname'}    );
622         $data{'contactname'}=uc($data{'contactname'});
623 }
624 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
625         $data{$_} = format_date($data{$_});     # back to syspref for display
626         $template->param( $_ => $data{$_});
627 }
628
629 if (C4::Context->preference('ExtendedPatronAttributes')) {
630     $template->param(ExtendedPatronAttributes => 1);
631     patron_attributes_form($template, $borrowernumber);
632 }
633
634 if (C4::Context->preference('EnhancedMessagingPreferences')) {
635     if ($op eq 'add') {
636         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
637     } else {
638         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
639     }
640     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
641     $template->param(SMSnumber     => defined $data{'smsalertnumber'} ? $data{'smsalertnumber'} : $data{'mobile'});
642 }
643
644 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
645 $debug and warn "memberentry step: $step";
646 $template->param(%data);
647 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
648 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
649 $template->param( debug  => $debug  ) if $debug;
650
651 $template->param(
652   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
653   category_type => $category_type,#to know the category type of the borrower
654   DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
655   select_city => $select_city,
656   "$category_type"  => 1,# associate with step to know where u are
657   destination   => $destination,#to know wher u come from and wher u must go in redirect
658   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
659   "op$op"   => 1);
660
661 $template->param(CGIbranch=>$CGIbranch) if ($CGIbranch);
662 $template->param(
663   nodouble  => $nodouble,
664   borrowernumber  => $borrowernumber, #register number
665   guarantorid => (($borrower_data->{'guarantorid'})) ? $borrower_data->{'guarantorid'} : $guarantorid,
666   ethcatpopup => $ethcatpopup,
667   relshiploop => \@relshipdata,
668   city_loop => $city_arrayref,
669   roadpopup => $roadpopup,  
670   borrotitlepopup => $borrotitlepopup,
671   guarantorinfo   => $guarantorinfo,
672   flagloop  => \@flagdata,
673   dateformat      => C4::Dates->new()->visual(),
674   C4::Context->preference('dateformat') => 1,
675   check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
676   category_type =>$category_type,
677   modify          => $modify,
678   nok     => $nok,#flag to konw if an error 
679   memberofinstution => $member_of_institution,
680   CGIorganisations => $CGIorganisations,
681   NoUpdateLogin =>  $NoUpdateLogin
682   );
683
684 if(defined($data{'flags'})){
685   $template->param(flags=>$data{'flags'});
686 }
687 if(defined($data{'contacttitle'})){
688   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
689 }
690
691   
692 output_html_with_http_headers $input, $cookie, $template->output;
693
694 sub  parse_extended_patron_attributes {
695     my ($input) = @_;
696     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->param();
697
698     my @attr = ();
699     my %dups = ();
700     foreach my $key (@patron_attr) {
701         my $value = $input->param($key);
702         next unless defined($value) and $value ne '';
703         my $password = $input->param("${key}_password");
704         my $code     = $input->param("${key}_code");
705         next if exists $dups{$code}->{$value};
706         $dups{$code}->{$value} = 1;
707         push @attr, { code => $code, value => $value, password => $password };
708     }
709     return \@attr;
710 }
711
712 sub patron_attributes_form {
713     my $template = shift;
714     my $borrowernumber = shift;
715
716     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
717     if (scalar(@types) == 0) {
718         $template->param(no_patron_attribute_types => 1);
719         return;
720     }
721     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
722
723     # map patron's attributes into a more convenient structure
724     my %attr_hash = ();
725     foreach my $attr (@$attributes) {
726         push @{ $attr_hash{$attr->{code}} }, $attr;
727     }
728
729     my @attribute_loop = ();
730     my $i = 0;
731     foreach my $type_code (map { $_->{code} } @types) {
732         my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
733         my $entry = {
734             code              => $attr_type->code(),
735             description       => $attr_type->description(),
736             repeatable        => $attr_type->repeatable(),
737             password_allowed  => $attr_type->password_allowed(),
738             category          => $attr_type->authorised_value_category(),
739             password          => '',
740         };
741         if (exists $attr_hash{$attr_type->code()}) {
742             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
743                 my $newentry = { map { $_ => $entry->{$_} } %$entry };
744                 $newentry->{value} = $attr->{value};
745                 $newentry->{password} = $attr->{password};
746                 $newentry->{use_dropdown} = 0;
747                 if ($attr_type->authorised_value_category()) {
748                     $newentry->{use_dropdown} = 1;
749                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
750                 }
751                 $i++;
752                 $newentry->{form_id} = "patron_attr_$i";
753                 #use Data::Dumper; die Dumper($entry) if  $entry->{use_dropdown};
754                 push @attribute_loop, $newentry;
755             }
756         } else {
757             $i++;
758             my $newentry = { map { $_ => $entry->{$_} } %$entry };
759             if ($attr_type->authorised_value_category()) {
760                 $newentry->{use_dropdown} = 1;
761                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
762             }
763             $newentry->{form_id} = "patron_attr_$i";
764             push @attribute_loop, $newentry;
765         }
766     }
767     $template->param(patron_attributes => \@attribute_loop);
768
769 }
770
771 # Local Variables:
772 # tab-width: 8
773 # End: