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