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