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