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