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