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