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