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