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