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