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