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