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