Bug Fixing 1782 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::Branch; # GetBranches
39
40 #use Smart::Comments;
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 my $select_city=$input->param('select_city');
74 my $zipcode=$input->param('zipcode');
75 my $city=$input->param('city');
76 my $nok=$input->param('nok');
77 my $guarantorinfo=$input->param('guarantorinfo');
78 my $step=$input->param('step') || 0;
79 my @errors;
80 my $default_city;
81 # $check_categorytype contains the value of duplicate borrowers category type to redirect in good template in step =2
82 my $check_categorytype=$input->param('check_categorytype');
83 # NOTE: Alert for ethnicity and ethnotes fields, they are invalid in all borrowers form
84 my $borrower_data;
85 my $NoUpdateLogin;
86 my $userenv = C4::Context->userenv;
87
88 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
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     $newdata{'city'}= $city;
177     $newdata{'zipcode'}=$zipcode; 
178 }
179
180 #builds default userid
181 if ( (defined $newdata{'userid'}) && ($newdata{'userid'} eq '')){
182   my $onefirstnameletter = substr($data{'firstname'},0,1);
183   my  $fivesurnameletter = substr($data{'surname'},0,9);
184   $newdata{'userid'}=lc($onefirstnameletter.$fivesurnameletter);
185 }
186   
187 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
188 my $loginexist=0;
189 my $extended_patron_attributes = ();
190 if ($op eq 'save' || $op eq 'insert'){
191   if (checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){ 
192     push @errors, 'ERROR_cardnumber';
193   } 
194   my $dateofbirthmandatory = (scalar grep {$_ eq "dateofbirth"} @field_check) ? 1 : 0;
195   if ($newdata{dateofbirth} && $dateofbirthmandatory) {
196     my $age = GetAge($newdata{dateofbirth});
197     my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});   
198         my ($low,$high) = ($borrowercategory->{'dateofbirthrequired'}, $borrowercategory->{'upperagelimit'});
199     if (($high && ($age > $high)) or ($age < $low)) {
200       push @errors, 'ERROR_age_limitations';
201           $template->param('ERROR_age_limitations' => "$low to $high");
202     }
203   }
204   if (C4::Context->preference("IndependantBranches")) {
205     if ($userenv && $userenv->{flags} != 1){
206       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
207       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
208         push @errors, "ERROR_branch";
209       }
210     }
211   }
212   # Check if the userid is unique
213   unless (Check_Userid($newdata{'userid'},$borrowernumber)) {
214     push @errors, "ERROR_login_exist";
215     $loginexist=1; 
216   }
217
218   if (C4::Context->preference('ExtendedPatronAttributes')) {
219     $extended_patron_attributes = parse_extended_patron_attributes($input);
220     foreach my $attr (@$extended_patron_attributes) {
221         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
222             push @errors, "ERROR_extended_unique_id_failed";
223             $template->param(ERROR_extended_unique_id_failed => "$attr->{code}/$attr->{value}");
224         }
225     }
226   }
227 }
228
229 if ($op eq 'modify' || $op eq 'insert'){
230   unless ($newdata{'dateexpiry'}){
231         my $arg2 = $newdata{'dateenrolled'} || C4::Dates->today('iso');
232     $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
233   }
234 }
235
236 ###  Error checks should happen before this line.
237
238 $nok = $nok || scalar(@errors);
239 if ((!$nok) and ($op eq 'insert' or $op eq 'save')){
240         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
241         if ($op eq 'insert'){
242                 # we know it's not a duplicate borrowernumber or there would already be an error
243                 $borrowernumber = &AddMember(%newdata);
244                 if ($data{'organisations'}){            
245                         # need to add the members organisations
246                         my @orgs=split(/\|/,$data{'organisations'});
247                         add_member_orgs($borrowernumber,\@orgs);
248                 }
249         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
250             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
251         }
252         } elsif ($op eq 'save'){ 
253                 if ($NoUpdateLogin) {
254                         delete $newdata{'password'};
255                         delete $newdata{'userid'};
256                 }
257                 &ModMember(%newdata);    
258         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
259             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
260         }
261         }
262         print scalar ($destination eq "circ") ? 
263                 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
264                 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
265         exit;           # You can only send 1 redirect!  After that, content or other headers don't matter.
266 }
267
268 if ($delete){
269         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
270         exit;           # same as above
271 }
272
273 if ($nok){
274   $op="add" if ($op eq "insert");
275   $op="modify" if ($op eq "save");
276   %data=%newdata; 
277   $template->param( updtype => ($op eq 'add' ?'I':'M'));        # used to check for $op eq "insert"... but we just changed $op!
278   unless ($step){  
279     $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1);
280   }  
281
282 if (C4::Context->preference("IndependantBranches")) {
283   my $userenv = C4::Context->userenv;
284   if ($userenv->{flags} != 1 && $data{branchcode}){
285     unless ($userenv->{branch} eq $data{'branchcode'}){
286       print $input->redirect("/cgi-bin/koha/members/members-home.pl");
287           exit;
288     }
289   }
290 }
291 if ($op eq 'add'){
292         my $arg2 = $newdata{'dateenrolled'} || C4::Dates->today('iso');
293         $data{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
294         $template->param( updtype => 'I',step_1=>1,step_2=>1,step_3=>1, step_4 => 1);
295         
296
297 if ($op eq "modify")  {
298   $template->param( updtype => 'M',modify => 1 );
299   $template->param( step_1=>1,step_2=>1,step_3=>1, step_4 => 1) unless $step;
300 }
301 # my $cardnumber=$data{'cardnumber'};
302 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if $op eq 'add';
303 if ($data{'sex'} eq 'F'){
304   $template->param(female => 1);
305 } elsif ($data{'sex'} eq 'M'){
306     $template->param(male => 1);
307 } else {
308     $template->param(none => 1);
309 }
310
311 ##Now all the data to modify a member.
312 my ($categories,$labels)=ethnicitycategories();
313   
314 my $ethnicitycategoriescount=$#{$categories};
315 my $ethcatpopup;
316 if ($ethnicitycategoriescount>=0) {
317   $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
318         -id => 'ethnicity',
319         -tabindex=>'',
320         -values=>$categories,
321         -default=>$data{'ethnicity'},
322         -labels=>$labels);
323   $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
324 }
325
326 my @typeloop;
327 foreach ( ($category_type) ? ($category_type) : qw(C A S P I X)){
328         my $action="WHERE category_type=?";
329         ($categories,$labels)=GetborCatFromCatType($_,$action);
330         my @categoryloop;
331         foreach my $cat (@$categories){
332                 push @categoryloop,{'categorycode' => $cat,
333                           'categoryname' => $labels->{$cat},
334                           'categorycodeselected' => ($cat eq $borrower_data->{'categorycode'} || $cat eq $categorycode),
335                 };
336         }
337         my %typehash;
338         $typehash{'typename'}=$_;
339         $typehash{'categoryloop'}=\@categoryloop;
340         push @typeloop,{'typename' => $_,
341           'categoryloop' => \@categoryloop};
342 }  
343 $template->param('typeloop' => \@typeloop);
344
345 # test in city
346 $select_city=getidcity($data{'city'}) if ($guarantorid ne '0');
347 ($default_city=$select_city) if ($step eq 0);
348 if ($select_city eq '' ){
349         $default_city = &getidcity($data{'city'});
350 }
351 my($cityid);
352 ($cityid,$name_city)=GetCities();
353 $template->param( city_cgipopup => 1) if ($cityid );
354 my $citypopup = CGI::popup_menu(-name=>'select_city',
355         -id => 'select_city',
356         -values=>$name_city,
357         -labels=>$name_city,
358         -default=>$default_city,
359         );  
360   
361 my $default_roadtype;
362 $default_roadtype=$data{'streettype'} ;
363 my($roadtypeid,$road_type)=GetRoadTypes();
364   $template->param( road_cgipopup => 1) if ($roadtypeid );
365 my $roadpopup = CGI::popup_menu(-name=>'streettype',
366         -id => 'streettype',
367         -values=>$roadtypeid,
368         -labels=>$road_type,
369         -override => 1,
370         -default=>$default_roadtype
371         );  
372
373 my $default_borrowertitle;
374 $default_borrowertitle=$data{'title'} ;
375 my($borrowertitle)=GetTitles();
376 $template->param( title_cgipopup => 1) if ($borrowertitle);
377 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
378         -id => 'btitle',
379         -values=>$borrowertitle,
380         -override => 1,
381         -default=>$default_borrowertitle
382         );    
383
384 my @relationships = split /,|\|/,C4::Context->preference('BorrowerRelationship');
385 my @relshipdata;
386 while (@relationships) {
387   my $relship = shift @relationships || '';
388   my %row = ('relationship' => $relship);
389   if ($data{'relationship'} eq $relship) {
390     $row{'selected'}=' selected';
391   } else {
392     $row{'selected'}='';
393   }
394   push(@relshipdata, \%row);
395 }
396
397 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
398         'lost'          => ['lost'],
399         'debarred'      => ['debarred']);
400
401  
402 my @flagdata;
403 foreach (keys(%flags)) {
404         my $key = $_;
405         my %row =  ('key'   => $key,
406                     'name'  => $flags{$key}[0]);
407         if ($data{$key}) {
408                 $row{'yes'}=' checked';
409                 $row{'no'}='';
410     }
411         else {
412                 $row{'yes'}='';
413                 $row{'no'}=' checked';
414         }
415         push @flagdata,\%row;
416 }
417
418 #get Branches
419 my @branches;
420 my @select_branch;
421 my %select_branches;
422
423 my $onlymine=(C4::Context->preference('IndependantBranches') && 
424               C4::Context->userenv && 
425               C4::Context->userenv->{flags} !=1  && 
426               C4::Context->userenv->{branch}?1:0);
427               
428 my $branches=GetBranches($onlymine);
429 my $default;
430
431 foreach my $branch (sort keys %$branches) {
432     push @select_branch,$branch;
433     $select_branches{$branch} = $branches->{$branch}->{'branchname'};
434     $default = C4::Context->userenv->{'branch'} if (C4::Context->userenv && C4::Context->userenv->{'branch'});
435 }
436 # --------------------------------------------------------------------------------------------------------
437   #in modify mod :default value from $CGIbranch comes from borrowers table
438   #in add mod: default value come from branches table (ip correspendence)
439 $default=$data{'branchcode'}  if ($op eq 'modify' || ($op eq 'add' && $category_type eq 'C'));
440 my $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
441             -name   => 'branchcode',
442             -values => \@select_branch,
443             -labels => \%select_branches,
444             -size   => 1,
445             -override => 1,  
446             -multiple =>0,
447             -default => $default,
448         );
449 my $CGIorganisations;
450 my $member_of_institution;
451 if (C4::Context->preference("memberofinstitution")){
452     my $organisations=get_institutions();
453     my @orgs;
454     my %org_labels;
455     foreach my $organisation (keys %$organisations) {
456         push @orgs,$organisation;
457         $org_labels{$organisation}=$organisations->{$organisation}->{'surname'};
458     }
459     $member_of_institution=1;
460     
461     $CGIorganisations = CGI::scrolling_list( -id => 'organisations',
462         -name     => 'organisations',
463         -labels   => \%org_labels,
464         -values   => \@orgs,
465         -size     => 5,
466         -multiple => 'true'
467
468     );
469 }
470
471
472 # --------------------------------------------------------------------------------------------------------
473
474 my $CGIsort = buildCGIsort("Bsort1","sort1",$data{'sort1'});
475 if ($CGIsort) {
476   $template->param(CGIsort1 => $CGIsort);
477 }
478 $template->param( sort1 => $data{'sort1'});             # shouldn't this be in an "else" statement like the 2nd one?
479
480 $CGIsort = buildCGIsort("Bsort2","sort2",$data{'sort2'});
481 if ($CGIsort) {
482   $template->param(CGIsort2 => $CGIsort);
483 } else {
484   $template->param( sort2 => $data{'sort2'});
485 }
486
487 if ($nok) {
488     foreach my $error (@errors) {
489         $template->param($error) || $template->param( $error => 1);
490     }
491     $template->param(nok => 1);
492 }
493   
494   #Formatting data for display    
495   
496 if ($data{'dateenrolled'} eq ''){
497   $data{'dateenrolled'}=C4::Dates->today('iso');
498 }
499 if (C4::Context->preference('uppercasesurnames')) {
500         $data{'surname'}    =uc($data{'surname'}    );
501         $data{'contactname'}=uc($data{'contactname'});
502 }
503 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
504         $data{$_} = format_date($data{$_});     # back to syspref for display
505         $template->param( $_ => $data{$_});
506 }
507
508 if (C4::Context->preference('ExtendedPatronAttributes')) {
509     $template->param(ExtendedPatronAttributes => 1);
510     patron_attributes_form($template, $borrowernumber);
511 }
512
513 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
514 $debug and warn "memberentry step: $step";
515 $template->param(%data);
516 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
517 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
518 $template->param( debug  => $debug  ) if $debug;
519 $template->param(
520   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
521   category_type => $category_type,#to know the category type of the borrower
522   DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
523   select_city => $select_city,
524   "$category_type"  => 1,# associate with step to know where u are
525   destination   => $destination,#to know wher u come from and wher u must go in redirect
526   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
527   flags   =>$data{'flags'},   
528   "op$op"   => 1,
529   nodouble  => $nodouble,
530   borrowernumber  => $borrowernumber,#register number
531   "contacttitle_".$data{'contacttitle'} => "SELECTED" ,
532   guarantorid => $guarantorid,
533   ethcatpopup => $ethcatpopup,
534   relshiploop => \@relshipdata,
535   citypopup => $citypopup,
536   roadpopup => $roadpopup,  
537   borrotitlepopup => $borrotitlepopup,
538   guarantorinfo   => $guarantorinfo,
539   flagloop  => \@flagdata,
540   dateformat      => C4::Dates->new()->visual(),
541   C4::Context->preference('dateformat') => 1,
542   check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
543   modify          => $modify,
544   nok     => $nok,#flag to konw if an error 
545   CGIbranch => $CGIbranch,
546   memberofinstution => $member_of_institution,
547   CGIorganisations => $CGIorganisations,
548   NoUpdateLogin =>  $NoUpdateLogin
549   );
550   
551 output_html_with_http_headers $input, $cookie, $template->output;
552
553 sub  parse_extended_patron_attributes {
554     my ($input) = @_;
555     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->param();
556
557     my @attr = ();
558     my %dups = ();
559     foreach my $key (@patron_attr) {
560         my $value = $input->param($key);
561         next unless defined($value) and $value ne '';
562         my $password = $input->param("${key}_password");
563         my $code = $input->param("${key}_code");
564         next if exists $dups{$code}->{$value};
565         $dups{$code}->{$value} = 1;
566         push @attr, { code => $code, value => $value, password => $password };
567     }
568     return \@attr;
569 }
570
571 sub patron_attributes_form {
572     my $template = shift;
573     my $borrowernumber = shift;
574
575     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
576     if (scalar(@types) == 0) {
577         $template->param(no_patron_attribute_types => 1);
578         return;
579     }
580     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
581
582     # map patron's attributes into a more convenient structure
583     my %attr_hash = ();
584     foreach my $attr (@$attributes) {
585         push @{ $attr_hash{$attr->{code}} }, $attr;
586     }
587
588     my @attribute_loop = ();
589     my $i = 0;
590     foreach my $type_code (map { $_->{code} } @types) {
591         my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
592         my $entry = {
593             code              => $attr_type->code(),
594             description       => $attr_type->description(),
595             repeatable        => $attr_type->repeatable(),
596             password_allowed  => $attr_type->password_allowed(),
597             category          => $attr_type->authorised_value_category(),
598             password          => '',
599         };
600         if (exists $attr_hash{$attr_type->code()}) {
601             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
602                 my $newentry = { map { $_ => $entry->{$_} } %$entry };
603                 $newentry->{value} = $attr->{value};
604                 $newentry->{password} = $attr->{password};
605                 $newentry->{use_dropdown} = 0;
606                 if ($attr_type->authorised_value_category()) {
607                     $newentry->{use_dropdown} = 1;
608                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
609                 }
610                 $i++;
611                 $newentry->{form_id} = "patron_attr_$i";
612                 #use Data::Dumper; die Dumper($entry) if  $entry->{use_dropdown};
613                 push @attribute_loop, $newentry;
614             }
615         } else {
616             $i++;
617             my $newentry = { map { $_ => $entry->{$_} } %$entry };
618             if ($attr_type->authorised_value_category()) {
619                 $newentry->{use_dropdown} = 1;
620                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
621             }
622             $newentry->{form_id} = "patron_attr_$i";
623             push @attribute_loop, $newentry;
624         }
625     }
626     $template->param(patron_attributes => \@attribute_loop);
627
628 }
629
630 # Local Variables:
631 # tab-width: 8
632 # End: