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