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