Bug 9978: Replace license header with the correct license (GPLv3+)
[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
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 # pragma
22 use strict;
23 use warnings;
24
25 # external modules
26 use CGI qw ( -utf8 );
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 use Koha::Borrower::Debarments;
45 use Koha::DateUtils;
46 use Module::Load;
47 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
48     load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
49 }
50
51 use vars qw($debug);
52
53 BEGIN {
54         $debug = $ENV{DEBUG} || 0;
55 }
56         
57 my $input = new CGI;
58 ($debug) or $debug = $input->param('debug') || 0;
59 my %data;
60
61 my $dbh = C4::Context->dbh;
62
63 my ($template, $loggedinuser, $cookie)
64     = get_template_and_user({template_name => "members/memberentrygen.tt",
65            query => $input,
66            type => "intranet",
67            authnotrequired => 0,
68            flagsrequired => {borrowers => 1},
69            debug => ($debug) ? 1 : 0,
70        });
71
72 my $guarantorid    = $input->param('guarantorid');
73 my $borrowernumber = $input->param('borrowernumber');
74 my $actionType     = $input->param('actionType') || '';
75 my $modify         = $input->param('modify');
76 my $delete         = $input->param('delete');
77 my $op             = $input->param('op');
78 my $destination    = $input->param('destination');
79 my $cardnumber     = $input->param('cardnumber');
80 my $check_member   = $input->param('check_member');
81 my $nodouble       = $input->param('nodouble');
82 my $duplicate      = $input->param('duplicate');
83 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
84                                      # modifying an existing patron, it ipso facto
85                                      # isn't a duplicate.  Marking FIXME because this
86                                      # script needs to be refactored.
87 my $select_city   = $input->param('select_city');
88 my $nok           = $input->param('nok');
89 my $guarantorinfo = $input->param('guarantorinfo');
90 my $step          = $input->param('step') || 0;
91 my @errors;
92 my $default_city;
93 # $check_categorytype contains the value of duplicate borrowers category type to redirect in good template in step =2
94 my $check_categorytype=$input->param('check_categorytype');
95 # NOTE: Alert for ethnicity and ethnotes fields, they are invalid in all borrowers form
96 my $borrower_data;
97 my $NoUpdateLogin;
98 my $userenv = C4::Context->userenv;
99
100
101 ## Deal with debarments
102 $template->param(
103     debarments => GetDebarments( { borrowernumber => $borrowernumber } ) );
104 my @debarments_to_remove = $input->param('remove_debarment');
105 foreach my $d ( @debarments_to_remove ) {
106     DelDebarment( $d );
107 }
108 if ( $input->param('add_debarment') ) {
109
110     my $expiration = $input->param('debarred_expiration');
111     $expiration =
112       $expiration
113       ? output_pref(
114         { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
115       : undef;
116
117     AddDebarment(
118         {
119             borrowernumber => $borrowernumber,
120             type           => 'MANUAL',
121             comment        => $input->param('debarred_comment'),
122             expiration     => $expiration,
123         }
124     );
125 }
126
127 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
128
129 my $minpw = C4::Context->preference('minPasswordLength');
130 $template->param("minPasswordLength" => $minpw);
131
132 # function to designate mandatory fields (visually with css)
133 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
134 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
135 foreach (@field_check) {
136         $template->param( "mandatory$_" => 1);    
137 }
138 # we'll need this, later.
139 my $dateofbirthmandatory = (scalar grep {$_ eq "dateofbirth"} @field_check) ? 1 : 0;
140 # function to designate unwanted fields
141 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
142 @field_check=split(/\|/,$check_BorrowerUnwantedField);
143 foreach (@field_check) {
144     next unless m/\w/o;
145         $template->param( "no$_" => 1);
146 }
147 $template->param( "add" => 1 ) if ( $op eq 'add' );
148 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
149 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
150 ( $borrower_data = GetMember( 'borrowernumber' => $borrowernumber ) ) if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' );
151 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
152 my $category_type = $input->param('category_type') || '';
153 if ($category_type){
154     $template->{VARS}->{'type_only'} = 1;
155 }
156 my $new_c_type = $category_type; #if we have input param, then we've already chosen the cat_type.
157 unless ($category_type or !($categorycode)){
158     my $borrowercategory = GetBorrowercategory($categorycode);
159     $category_type    = $borrowercategory->{'category_type'};
160     my $category_name = $borrowercategory->{'description'}; 
161     $template->param("categoryname"=>$category_name);
162  }
163 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
164
165 # if a add or modify is requested => check validity of data.
166 %data = %$borrower_data if ($borrower_data);
167
168 # initialize %newdata
169 my %newdata;                                                                             # comes from $input->param()
170 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
171     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
172     foreach my $key (@names) {
173         if (defined $input->param($key)) {
174             $newdata{$key} = $input->param($key);
175             $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
176         }
177     }
178
179     my $dateobject = C4::Dates->new();
180     my $syspref = $dateobject->regexp();                # same syspref format for all 3 dates
181     my $iso     = $dateobject->regexp('iso');   #
182     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
183         next unless exists $newdata{$_};
184         my $userdate = $newdata{$_} or next;
185         if ($userdate =~ /$syspref/) {
186             $newdata{$_} = format_date_in_iso($userdate);       # if they match syspref format, then convert to ISO
187         } elsif ($userdate =~ /$iso/) {
188             warn "Date $_ ($userdate) is already in ISO format";
189         } else {
190             ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
191             $template->param( "ERROR_$_" => 1 );        # else ERROR!
192             push(@errors,"ERROR_$_");
193         }
194     }
195   # check permission to modify login info.
196     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
197         $NoUpdateLogin = 1;
198     }
199 }
200
201 # remove keys from %newdata that ModMember() doesn't like
202 {
203     my @keys_to_delete = (
204         qr/^BorrowerMandatoryField$/,
205         qr/^category_type$/,
206         qr/^check_member$/,
207         qr/^destination$/,
208         qr/^nodouble$/,
209         qr/^op$/,
210         qr/^save$/,
211         qr/^updtype$/,
212         qr/^SMSnumber$/,
213         qr/^setting_extended_patron_attributes$/,
214         qr/^setting_messaging_prefs$/,
215         qr/^digest$/,
216         qr/^modify$/,
217         qr/^step$/,
218         qr/^\d+$/,
219         qr/^\d+-DAYS/,
220         qr/^patron_attr_/,
221     );
222     for my $regexp (@keys_to_delete) {
223         for (keys %newdata) {
224             delete($newdata{$_}) if /$regexp/;
225         }
226     }
227 }
228
229 #############test for member being unique #############
230 if ( ( $op eq 'insert' ) and !$nodouble ) {
231     my $category_type_send;
232     if ( $category_type eq 'I' ) {
233         $category_type_send = $category_type;
234     }
235     my $check_category;    # recover the category code of the doublon suspect borrowers
236      #   ($result,$categorycode) = checkuniquemember($collectivity,$surname,$firstname,$dateofbirth)
237     ( $check_member, $check_category ) = checkuniquemember(
238         $category_type_send,
239         ( $newdata{surname}     ? $newdata{surname}     : $data{surname} ),
240         ( $newdata{firstname}   ? $newdata{firstname}   : $data{firstname} ),
241         ( $newdata{dateofbirth} ? $newdata{dateofbirth} : $data{dateofbirth} )
242     );
243     if ( !$check_member ) {
244         $nodouble = 1;
245     }
246
247     #   recover the category type if the borrowers is a doublon
248     if ($check_category) {
249         my $tmpborrowercategory = GetBorrowercategory($check_category);
250         $check_categorytype = $tmpborrowercategory->{'category_type'};
251     }
252 }
253
254   #recover all data from guarantor address phone ,fax... 
255 if ( $guarantorid and ( $category_type eq 'C' || $category_type eq 'P' )) {
256     if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
257         $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
258         $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
259         $newdata{'contactname'}     = $guarantordata->{'surname'};
260         $newdata{'contacttitle'}    = $guarantordata->{'title'};
261         if ( $op eq 'add' ) {
262                 foreach (qw(streetnumber address streettype address2
263                         zipcode country city state phone phonepro mobile fax email emailpro branchcode
264                         B_streetnumber B_streettype B_address B_address2
265                         B_city B_state B_zipcode B_country B_email B_phone)) {
266                         $newdata{$_} = $guarantordata->{$_};
267                 }
268         }
269     }
270 }
271
272 ###############test to take the right zipcode, country and city name ##############
273 # set only if parameter was passed from the form
274 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
275 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
276 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
277
278 #builds default userid
279 if ( (defined $newdata{'userid'}) && ($newdata{'userid'} eq '')){
280     if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
281         # Full page edit, firstname and surname input zones are present
282         $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
283     }
284     elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
285         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
286         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
287         $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
288     }
289     else {
290         $newdata{'userid'} = $data{'userid'};
291     }
292 }
293   
294 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
295 my $extended_patron_attributes = ();
296 if ($op eq 'save' || $op eq 'insert'){
297     # If the cardnumber is blank, treat it as null.
298     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
299
300     if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
301         push @errors, $error_code == 1
302             ? 'ERROR_cardnumber_already_exists'
303             : $error_code == 2
304                 ? 'ERROR_cardnumber_length'
305                 : ()
306     }
307
308     if ($newdata{dateofbirth} && $dateofbirthmandatory) {
309         my $age = GetAge($newdata{dateofbirth});
310         my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});   
311         my ($low,$high) = ($borrowercategory->{'dateofbirthrequired'}, $borrowercategory->{'upperagelimit'});
312         if (($high && ($age > $high)) or ($age < $low)) {
313             push @errors, 'ERROR_age_limitations';
314             $template->param( age_low => $low);
315             $template->param( age_high => $high);
316         }
317     }
318   
319     if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
320         $newdata{'surname'} = uc($newdata{'surname'});
321     }
322
323   if (C4::Context->preference("IndependentBranches")) {
324     unless ( C4::Context->IsSuperLibrarian() ){
325       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
326       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
327         push @errors, "ERROR_branch";
328       }
329     }
330   }
331   # Check if the 'userid' is unique. 'userid' might not always be present in
332   # the edited values list when editing certain sub-forms. Get it straight
333   # from the DB if absent.
334   my $userid = $newdata{ userid } // $borrower_data->{ userid };
335   unless (Check_Userid($userid,$borrowernumber)) {
336     push @errors, "ERROR_login_exist";
337   }
338   
339   my $password = $input->param('password');
340   my $password2 = $input->param('password2');
341   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
342   push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
343
344   if (C4::Context->preference('ExtendedPatronAttributes')) {
345     $extended_patron_attributes = parse_extended_patron_attributes($input);
346     foreach my $attr (@$extended_patron_attributes) {
347         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
348             my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
349             push @errors, "ERROR_extended_unique_id_failed";
350             $template->param(
351                 ERROR_extended_unique_id_failed_code => $attr->{code},
352                 ERROR_extended_unique_id_failed_value => $attr->{value},
353                 ERROR_extended_unique_id_failed_description => $attr_info->description()
354             );
355         }
356     }
357   }
358 }
359
360 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
361     unless ($newdata{'dateexpiry'}){
362         my $arg2 = $newdata{'dateenrolled'} || C4::Dates->today('iso');
363         $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
364     }
365 }
366
367 if (
368         defined $input->param('SMSnumber')
369     &&  (
370            $input->param('SMSnumber') eq ""
371         or $input->param('SMSnumber') ne $newdata{'mobile'}
372         )
373 ) {
374     $newdata{smsalertnumber} = $input->param('SMSnumber');
375 }
376
377 ###  Error checks should happen before this line.
378 $nok = $nok || scalar(@errors);
379 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
380         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
381         if ($op eq 'insert'){
382                 # we know it's not a duplicate borrowernumber or there would already be an error
383         $borrowernumber = &AddMember(%newdata);
384         $newdata{'borrowernumber'} = $borrowernumber;
385
386         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
387         if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'}  && $newdata{'password'}) {
388             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
389             my $emailaddr;
390             if  (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF'  && 
391                 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~  /\w\@\w/ ) {
392                 $emailaddr =   $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} 
393             } 
394             elsif ($newdata{email} =~ /\w\@\w/) {
395                 $emailaddr = $newdata{email} 
396             }
397             elsif ($newdata{emailpro} =~ /\w\@\w/) {
398                 $emailaddr = $newdata{emailpro} 
399             }
400             elsif ($newdata{B_email} =~ /\w\@\w/) {
401                 $emailaddr = $newdata{B_email} 
402             }
403             # if we manage to find a valid email address, send notice 
404             if ($emailaddr) {
405                 $newdata{emailaddr} = $emailaddr;
406                 my $err;
407                 eval {
408                     $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
409                 };
410                 if ( $@ ) {
411                     $template->param(error_alert => $@);
412                 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
413                     $template->{VARS}->{'error_alert'} = "no_email";
414                 } else {
415                     $template->{VARS}->{'info_alert'} = 1;
416                 }
417             }
418         }
419
420         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
421             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
422         }
423         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
424             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
425         }
426         # Try to do the live sync with the Norwegian national patron database, if it is enabled
427         if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
428             NLSync({ 'borrowernumber' => $borrowernumber });
429         }
430         } elsif ($op eq 'save'){ 
431                 if ($NoUpdateLogin) {
432                         delete $newdata{'password'};
433                         delete $newdata{'userid'};
434                 }
435         &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
436                                                                 # updating any columns in the borrowers table,
437                                                                 # which can happen if we're only editing the
438                                                                 # patron attributes or messaging preferences sections
439         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
440             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
441         }
442         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
443             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
444         }
445         }
446         print scalar ($destination eq "circ") ? 
447                 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
448                 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
449         exit;           # You can only send 1 redirect!  After that, content or other headers don't matter.
450 }
451
452 if ($delete){
453         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
454         exit;           # same as above
455 }
456
457 if ($nok or !$nodouble){
458     $op="add" if ($op eq "insert");
459     $op="modify" if ($op eq "save");
460     %data=%newdata; 
461     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
462     unless ($step){  
463         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
464     }  
465
466 if (C4::Context->preference("IndependentBranches")) {
467     my $userenv = C4::Context->userenv;
468     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
469         unless ($userenv->{branch} eq $data{'branchcode'}){
470             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
471             exit;
472         }
473     }
474 }
475 if ($op eq 'add'){
476     $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
477 }
478 if ($op eq "modify")  {
479     $template->param( updtype => 'M',modify => 1 );
480     $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
481     if ( $step == 4 ) {
482         $template->param( categorycode => $borrower_data->{'categorycode'} );
483     }
484     # Add sync data to the user data
485     if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
486         my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
487         if ( $sync ) {
488             $template->param(
489                 sync => $sync->sync,
490             );
491         }
492     }
493 }
494 if ( $op eq "duplicate" ) {
495     $template->param( updtype => 'I' );
496     $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
497     $data{'cardnumber'} = "";
498 }
499
500 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if ( ( $op eq 'add' ) or ( $op eq 'duplicate' ) );
501 if(!defined($data{'sex'})){
502     $template->param( none => 1);
503 } elsif($data{'sex'} eq 'F'){
504     $template->param( female => 1);
505 } elsif ($data{'sex'} eq 'M'){
506     $template->param(  male => 1);
507 } else {
508     $template->param(  none => 1);
509 }
510
511 ##Now all the data to modify a member.
512 my ($categories,$labels)=ethnicitycategories();
513   
514 my $ethnicitycategoriescount=$#{$categories};
515 my $ethcatpopup;
516 if ($ethnicitycategoriescount>=0) {
517   $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
518         -id => 'ethnicity',
519         -tabindex=>'',
520         -values=>$categories,
521         -default=>$data{'ethnicity'},
522         -labels=>$labels);
523   $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
524 }
525
526 my @typeloop;
527 my $no_categories = 1;
528 my $no_add;
529 foreach (qw(C A S P I X)) {
530     my $action="WHERE category_type=?";
531         ($categories,$labels)=GetborCatFromCatType($_,$action);
532     if(scalar(@$categories) > 0){ $no_categories = 0; }
533         my @categoryloop;
534         foreach my $cat (@$categories){
535                 push @categoryloop,{'categorycode' => $cat,
536                           'categoryname' => $labels->{$cat},
537                           'categorycodeselected' => ((defined($borrower_data->{'categorycode'}) && 
538                                                      $cat eq $borrower_data->{'categorycode'}) 
539                                                      || (defined($categorycode) && $cat eq $categorycode)),
540                 };
541         }
542         my %typehash;
543         $typehash{'typename'}=$_;
544     my $typedescription = "typename_".$typehash{'typename'};
545         $typehash{'categoryloop'}=\@categoryloop;
546         push @typeloop,{'typename' => $_,
547         $typedescription => 1,
548           'categoryloop' => \@categoryloop};
549 }
550 $template->param('typeloop' => \@typeloop,
551         no_categories => $no_categories);
552 if($no_categories){ $no_add = 1; }
553 # test in city
554 if ( $guarantorid ) {
555     $select_city = getidcity($data{city});
556 }
557 ($default_city=$select_city) if ($step eq 0);
558 if (!defined($select_city) or $select_city eq '' ){
559         $default_city = &getidcity($data{'city'});
560 }
561
562 my $city_arrayref = GetCities();
563 if (@{$city_arrayref} ) {
564     $template->param( city_cgipopup => 1);
565
566     if ($default_city) { # flag the current or default val
567         for my $city ( @{$city_arrayref} ) {
568             if ($default_city == $city->{cityid}) {
569                 $city->{selected} = 1;
570                 last;
571             }
572         }
573     }
574 }
575   
576 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE', $data{streettype} );
577 $template->param( roadtypes => $roadtypes);
578
579 my $default_borrowertitle = '';
580 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
581 my($borrowertitle)=GetTitles();
582 $template->param( title_cgipopup => 1) if ($borrowertitle);
583 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
584         -id => 'btitle',
585         -values=>$borrowertitle,
586         -override => 1,
587         -default=>$default_borrowertitle
588         );    
589
590 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
591 my @relshipdata;
592 while (@relationships) {
593   my $relship = shift @relationships || '';
594   my %row = ('relationship' => $relship);
595   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
596     $row{'selected'}=' selected';
597   } else {
598     $row{'selected'}='';
599   }
600   push(@relshipdata, \%row);
601 }
602
603 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
604         'lost'          => ['lost']);
605
606  
607 my @flagdata;
608 foreach (keys(%flags)) {
609         my $key = $_;
610         my %row =  ('key'   => $key,
611                     'name'  => $flags{$key}[0]);
612         if ($data{$key}) {
613                 $row{'yes'}=' checked';
614                 $row{'no'}='';
615     }
616         else {
617                 $row{'yes'}='';
618                 $row{'no'}=' checked';
619         }
620         push @flagdata,\%row;
621 }
622
623 # get Branch Loop
624 # in modify mod: userbranch value for GetBranchesLoop() comes from borrowers table
625 # in add    mod: userbranch value come from branches table (ip correspondence)
626
627 my $userbranch = '';
628 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
629     $userbranch = C4::Context->userenv->{'branch'};
630 }
631
632 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
633     $userbranch = $data{'branchcode'};
634 }
635
636 my $branchloop = GetBranchesLoop( $userbranch );
637
638 if( !$branchloop ){
639     $no_add = 1;
640     $template->param(no_branches => 1);
641 }
642 if($no_categories){
643     $no_add = 1;
644     $template->param(no_categories => 1);
645 }
646 $template->param(no_add => $no_add);
647 # --------------------------------------------------------------------------------------------------------
648
649 $template->param( sort1 => $data{'sort1'});
650 $template->param( sort2 => $data{'sort2'});
651
652 if ($nok) {
653     foreach my $error (@errors) {
654         $template->param($error) || $template->param( $error => 1);
655     }
656     $template->param(nok => 1);
657 }
658   
659   #Formatting data for display    
660   
661 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
662   $data{'dateenrolled'}=C4::Dates->today('iso');
663 }
664 if ( $op eq 'duplicate' ) {
665     $data{'dateenrolled'} = C4::Dates->today('iso');
666     $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, $data{'dateenrolled'} );
667 }
668 if (C4::Context->preference('uppercasesurnames')) {
669     $data{'surname'} &&= uc( $data{'surname'} );
670     $data{'contactname'} &&= uc( $data{'contactname'} );
671 }
672
673 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
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     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
692 }
693
694 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
695 $debug and warn "memberentry step: $step";
696 $template->param(%data);
697 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
698 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
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   select_city => $select_city,
704   "$category_type"  => 1,# associate with step to know where u are
705   destination   => $destination,#to know wher u come from and wher u must go in redirect
706   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
707   "op$op"   => 1);
708
709 $template->param( branchloop => $branchloop ) if ( $branchloop );
710 $template->param(
711   nodouble  => $nodouble,
712   borrowernumber  => $borrowernumber, #register number
713   guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
714   ethcatpopup => $ethcatpopup,
715   relshiploop => \@relshipdata,
716   city_loop => $city_arrayref,
717   borrotitlepopup => $borrotitlepopup,
718   guarantorinfo   => $guarantorinfo,
719   flagloop  => \@flagdata,
720   check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
721   category_type =>$category_type,
722   modify          => $modify,
723   nok     => $nok,#flag to konw if an error 
724   NoUpdateLogin =>  $NoUpdateLogin
725   );
726
727 if(defined($data{'flags'})){
728   $template->param(flags=>$data{'flags'});
729 }
730 if(defined($data{'contacttitle'})){
731   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
732 }
733
734
735 my ( $min, $max ) = C4::Members::get_cardnumber_length();
736 if ( defined $min ) {
737     $template->param(
738         minlength_cardnumber => $min,
739         maxlength_cardnumber => $max
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 = { %$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 = { %$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: