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