Bug 9021 [QA Followup] - Switch to Koha::Object(s)
[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::Log;
39 use C4::Letters;
40 use C4::Branch; # GetBranches
41 use C4::Form::MessagingPreferences;
42 use Koha::Borrower::Debarments;
43 use Koha::DateUtils;
44 use Email::Valid;
45 use Module::Load;
46 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
47     load Koha::NorwegianPatronDB, qw( NLGetSyncDataFromBorrowernumber );
48 }
49 use Koha::SMS::Providers;
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 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
73     my @providers = Koha::SMS::Providers->search();
74     $template->param( sms_providers => \@providers );
75 }
76
77 my $guarantorid    = $input->param('guarantorid');
78 my $borrowernumber = $input->param('borrowernumber');
79 my $actionType     = $input->param('actionType') || '';
80 my $modify         = $input->param('modify');
81 my $delete         = $input->param('delete');
82 my $op             = $input->param('op');
83 my $destination    = $input->param('destination');
84 my $cardnumber     = $input->param('cardnumber');
85 my $check_member   = $input->param('check_member');
86 my $nodouble       = $input->param('nodouble');
87 my $duplicate      = $input->param('duplicate');
88 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
89                                      # modifying an existing patron, it ipso facto
90                                      # isn't a duplicate.  Marking FIXME because this
91                                      # script needs to be refactored.
92 my $select_city   = $input->param('select_city');
93 my $nok           = $input->param('nok');
94 my $guarantorinfo = $input->param('guarantorinfo');
95 my $step          = $input->param('step') || 0;
96 my @errors;
97 my $default_city;
98 my $borrower_data;
99 my $NoUpdateLogin;
100 my $userenv = C4::Context->userenv;
101
102
103 ## Deal with debarments
104 $template->param(
105     debarments => GetDebarments( { borrowernumber => $borrowernumber } ) );
106 my @debarments_to_remove = $input->param('remove_debarment');
107 foreach my $d ( @debarments_to_remove ) {
108     DelDebarment( $d );
109 }
110 if ( $input->param('add_debarment') ) {
111
112     my $expiration = $input->param('debarred_expiration');
113     $expiration =
114       $expiration
115       ? output_pref(
116         { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
117       : undef;
118
119     AddDebarment(
120         {
121             borrowernumber => $borrowernumber,
122             type           => 'MANUAL',
123             comment        => $input->param('debarred_comment'),
124             expiration     => $expiration,
125         }
126     );
127 }
128
129 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
130
131 my $minpw = C4::Context->preference('minPasswordLength');
132 $template->param("minPasswordLength" => $minpw);
133
134 # function to designate mandatory fields (visually with css)
135 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
136 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
137 foreach (@field_check) {
138         $template->param( "mandatory$_" => 1);    
139 }
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 unless ($category_type or !($categorycode)){
154     my $borrowercategory = GetBorrowercategory($categorycode);
155     $category_type    = $borrowercategory->{'category_type'};
156     my $category_name = $borrowercategory->{'description'}; 
157     $template->param("categoryname"=>$category_name);
158 }
159 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
160
161 # if a add or modify is requested => check validity of data.
162 %data = %$borrower_data if ($borrower_data);
163
164 # initialize %newdata
165 my %newdata;                                                                             # comes from $input->param()
166 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
167     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
168     foreach my $key (@names) {
169         if (defined $input->param($key)) {
170             $newdata{$key} = $input->param($key);
171             $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
172         }
173     }
174
175     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
176         next unless exists $newdata{$_};
177         my $userdate = $newdata{$_} or next;
178
179         my $formatteddate = eval { output_pref({ dt => dt_from_string( $userdate ), dateformat => 'iso', dateonly => 1 } ); };
180         if ( $formatteddate ) {
181             $newdata{$_} = $formatteddate;
182         } else {
183             ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
184             $template->param( "ERROR_$_" => 1 );
185             push(@errors,"ERROR_$_");
186         }
187     }
188   # check permission to modify login info.
189     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
190         $NoUpdateLogin = 1;
191     }
192 }
193
194 # remove keys from %newdata that ModMember() doesn't like
195 {
196     my @keys_to_delete = (
197         qr/^BorrowerMandatoryField$/,
198         qr/^category_type$/,
199         qr/^check_member$/,
200         qr/^destination$/,
201         qr/^nodouble$/,
202         qr/^op$/,
203         qr/^save$/,
204         qr/^updtype$/,
205         qr/^SMSnumber$/,
206         qr/^setting_extended_patron_attributes$/,
207         qr/^setting_messaging_prefs$/,
208         qr/^digest$/,
209         qr/^modify$/,
210         qr/^step$/,
211         qr/^\d+$/,
212         qr/^\d+-DAYS/,
213         qr/^patron_attr_/,
214     );
215     for my $regexp (@keys_to_delete) {
216         for (keys %newdata) {
217             delete($newdata{$_}) if /$regexp/;
218         }
219     }
220 }
221
222 #############test for member being unique #############
223 if ( ( $op eq 'insert' ) and !$nodouble ) {
224     my $category_type_send;
225     if ( $category_type eq 'I' ) {
226         $category_type_send = $category_type;
227     }
228     my $check_category;    # recover the category code of the doublon suspect borrowers
229      #   ($result,$categorycode) = checkuniquemember($collectivity,$surname,$firstname,$dateofbirth)
230     ( $check_member, $check_category ) = checkuniquemember(
231         $category_type_send,
232         ( $newdata{surname}     ? $newdata{surname}     : $data{surname} ),
233         ( $newdata{firstname}   ? $newdata{firstname}   : $data{firstname} ),
234         ( $newdata{dateofbirth} ? $newdata{dateofbirth} : $data{dateofbirth} )
235     );
236     if ( !$check_member ) {
237         $nodouble = 1;
238     }
239 }
240
241   #recover all data from guarantor address phone ,fax... 
242 if ( $guarantorid ) {
243     if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
244         $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
245         $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
246         $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
247         $newdata{'contactname'}     = $guarantordata->{'surname'};
248         $newdata{'contacttitle'}    = $guarantordata->{'title'};
249         if ( $op eq 'add' ) {
250                 foreach (qw(streetnumber address streettype address2
251                         zipcode country city state phone phonepro mobile fax email emailpro branchcode
252                         B_streetnumber B_streettype B_address B_address2
253                         B_city B_state B_zipcode B_country B_email B_phone)) {
254                         $newdata{$_} = $guarantordata->{$_};
255                 }
256         }
257     }
258 }
259
260 ###############test to take the right zipcode, country and city name ##############
261 # set only if parameter was passed from the form
262 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
263 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
264 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
265
266 # builds default userid
267 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
268 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ ) {
269     if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
270         # Full page edit, firstname and surname input zones are present
271         $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
272     }
273     elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
274         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
275         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
276         $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
277     }
278     else {
279         $newdata{'userid'} = $data{'userid'};
280     }
281 }
282   
283 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
284 my $extended_patron_attributes = ();
285 if ($op eq 'save' || $op eq 'insert'){
286     # If the cardnumber is blank, treat it as null.
287     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
288
289     if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
290         push @errors, $error_code == 1
291             ? 'ERROR_cardnumber_already_exists'
292             : $error_code == 2
293                 ? 'ERROR_cardnumber_length'
294                 : ()
295     }
296
297     if ( $newdata{dateofbirth} ) {
298         my $age = GetAge($newdata{dateofbirth});
299         my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});   
300         my ($low,$high) = ($borrowercategory->{'dateofbirthrequired'}, $borrowercategory->{'upperagelimit'});
301         if (($high && ($age > $high)) or ($age < $low)) {
302             push @errors, 'ERROR_age_limitations';
303             $template->param( age_low => $low);
304             $template->param( age_high => $high);
305         }
306     }
307   
308     if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
309         $newdata{'surname'} = uc($newdata{'surname'});
310     }
311
312   if (C4::Context->preference("IndependentBranches")) {
313     unless ( C4::Context->IsSuperLibrarian() ){
314       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
315       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
316         push @errors, "ERROR_branch";
317       }
318     }
319   }
320   # Check if the 'userid' is unique. 'userid' might not always be present in
321   # the edited values list when editing certain sub-forms. Get it straight
322   # from the DB if absent.
323   my $userid = $newdata{ userid } // $borrower_data->{ userid };
324   unless (Check_Userid($userid,$borrowernumber)) {
325     push @errors, "ERROR_login_exist";
326   }
327   
328   my $password = $input->param('password');
329   my $password2 = $input->param('password2');
330   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
331   push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
332
333   # Validate emails
334   my $emailprimary = $input->param('email');
335   my $emailsecondary = $input->param('emailpro');
336   my $emailalt = $input->param('B_email');
337
338   if ($emailprimary) {
339       push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
340   }
341   if ($emailsecondary) {
342       push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
343   }
344   if ($emailalt) {
345       push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
346   }
347
348   if (C4::Context->preference('ExtendedPatronAttributes')) {
349     $extended_patron_attributes = parse_extended_patron_attributes($input);
350     foreach my $attr (@$extended_patron_attributes) {
351         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
352             my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
353             push @errors, "ERROR_extended_unique_id_failed";
354             $template->param(
355                 ERROR_extended_unique_id_failed_code => $attr->{code},
356                 ERROR_extended_unique_id_failed_value => $attr->{value},
357                 ERROR_extended_unique_id_failed_description => $attr_info->description()
358             );
359         }
360     }
361   }
362 }
363
364 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
365     unless ($newdata{'dateexpiry'}){
366         my $arg2 = $newdata{'dateenrolled'} || output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
367         $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
368     }
369 }
370
371 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
372 my $sms = $input->param('SMSnumber');
373 if ( defined $sms ) {
374     $newdata{smsalertnumber} = $sms;
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
513 my @typeloop;
514 my $no_categories = 1;
515 my $no_add;
516 foreach (qw(C A S P I X)) {
517     my $action="WHERE category_type=?";
518     my ($categories,$labels)=GetborCatFromCatType($_,$action);
519     if(scalar(@$categories) > 0){ $no_categories = 0; }
520         my @categoryloop;
521         foreach my $cat (@$categories){
522                 push @categoryloop,{'categorycode' => $cat,
523                           'categoryname' => $labels->{$cat},
524                           'categorycodeselected' => ((defined($borrower_data->{'categorycode'}) && 
525                                                      $cat eq $borrower_data->{'categorycode'}) 
526                                                      || (defined($categorycode) && $cat eq $categorycode)),
527                 };
528         }
529         my %typehash;
530         $typehash{'typename'}=$_;
531     my $typedescription = "typename_".$typehash{'typename'};
532         $typehash{'categoryloop'}=\@categoryloop;
533         push @typeloop,{'typename' => $_,
534         $typedescription => 1,
535           'categoryloop' => \@categoryloop};
536 }
537 $template->param('typeloop' => \@typeloop,
538         no_categories => $no_categories);
539 if($no_categories){ $no_add = 1; }
540 # test in city
541 if ( $guarantorid ) {
542     $select_city = getidcity($data{city});
543 }
544 ($default_city=$select_city) if ($step eq 0);
545 if (!defined($select_city) or $select_city eq '' ){
546         $default_city = &getidcity($data{'city'});
547 }
548
549 my $city_arrayref = GetCities();
550 if (@{$city_arrayref} ) {
551     $template->param( city_cgipopup => 1);
552
553     if ($default_city) { # flag the current or default val
554         for my $city ( @{$city_arrayref} ) {
555             if ($default_city == $city->{cityid}) {
556                 $city->{selected} = 1;
557                 last;
558             }
559         }
560     }
561 }
562   
563 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE', $data{streettype} );
564 $template->param( roadtypes => $roadtypes);
565
566 my $default_borrowertitle = '';
567 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
568 my($borrowertitle)=GetTitles();
569 $template->param( title_cgipopup => 1) if ($borrowertitle);
570 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
571         -id => 'btitle',
572         -values=>$borrowertitle,
573         -override => 1,
574         -default=>$default_borrowertitle
575         );    
576
577 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
578 my @relshipdata;
579 while (@relationships) {
580   my $relship = shift @relationships || '';
581   my %row = ('relationship' => $relship);
582   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
583     $row{'selected'}=' selected';
584   } else {
585     $row{'selected'}='';
586   }
587   push(@relshipdata, \%row);
588 }
589
590 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
591         'lost'          => ['lost']);
592
593  
594 my @flagdata;
595 foreach (keys(%flags)) {
596         my $key = $_;
597         my %row =  ('key'   => $key,
598                     'name'  => $flags{$key}[0]);
599         if ($data{$key}) {
600                 $row{'yes'}=' checked';
601                 $row{'no'}='';
602     }
603         else {
604                 $row{'yes'}='';
605                 $row{'no'}=' checked';
606         }
607         push @flagdata,\%row;
608 }
609
610 # get Branch Loop
611 # in modify mod: userbranch value for GetBranchesLoop() comes from borrowers table
612 # in add    mod: userbranch value come from branches table (ip correspondence)
613
614 my $userbranch = '';
615 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
616     $userbranch = C4::Context->userenv->{'branch'};
617 }
618
619 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
620     $userbranch = $data{'branchcode'};
621 }
622
623 my $branchloop = GetBranchesLoop( $userbranch );
624
625 if( !$branchloop ){
626     $no_add = 1;
627     $template->param(no_branches => 1);
628 }
629 if($no_categories){
630     $no_add = 1;
631     $template->param(no_categories => 1);
632 }
633 $template->param(no_add => $no_add);
634 # --------------------------------------------------------------------------------------------------------
635
636 $template->param( sort1 => $data{'sort1'});
637 $template->param( sort2 => $data{'sort2'});
638
639 if ($nok) {
640     foreach my $error (@errors) {
641         $template->param($error) || $template->param( $error => 1);
642     }
643     $template->param(nok => 1);
644 }
645   
646   #Formatting data for display    
647   
648 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
649   $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
650 }
651 if ( $op eq 'duplicate' ) {
652     $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
653     $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, $data{'dateenrolled'} );
654 }
655 if (C4::Context->preference('uppercasesurnames')) {
656     $data{'surname'} &&= uc( $data{'surname'} );
657     $data{'contactname'} &&= uc( $data{'contactname'} );
658 }
659
660 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
661     if ( $data{$_} ) {
662        $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); };  # back to syspref for display
663     }
664     $template->param( $_ => $data{$_});
665 }
666
667 if (C4::Context->preference('ExtendedPatronAttributes')) {
668     $template->param(ExtendedPatronAttributes => 1);
669     patron_attributes_form($template, $borrowernumber);
670 }
671
672 if (C4::Context->preference('EnhancedMessagingPreferences')) {
673     if ($op eq 'add') {
674         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
675     } else {
676         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
677     }
678     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
679     $template->param(SMSnumber     => $data{'smsalertnumber'} );
680     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
681 }
682
683 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
684 $debug and warn "memberentry step: $step";
685 $template->param(%data);
686 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
687 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
688
689 $template->param(
690   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
691   category_type => $category_type,#to know the category type of the borrower
692   select_city => $select_city,
693   "$category_type"  => 1,# associate with step to know where u are
694   destination   => $destination,#to know wher u come from and wher u must go in redirect
695   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
696   "op$op"   => 1);
697
698 $template->param( branchloop => $branchloop ) if ( $branchloop );
699 $template->param(
700   nodouble  => $nodouble,
701   borrowernumber  => $borrowernumber, #register number
702   guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
703   relshiploop => \@relshipdata,
704   city_loop => $city_arrayref,
705   borrotitlepopup => $borrotitlepopup,
706   guarantorinfo   => $guarantorinfo,
707   flagloop  => \@flagdata,
708   category_type =>$category_type,
709   modify          => $modify,
710   nok     => $nok,#flag to know if an error
711   NoUpdateLogin =>  $NoUpdateLogin
712   );
713
714 if(defined($data{'flags'})){
715   $template->param(flags=>$data{'flags'});
716 }
717 if(defined($data{'contacttitle'})){
718   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
719 }
720
721
722 my ( $min, $max ) = C4::Members::get_cardnumber_length();
723 if ( defined $min ) {
724     $template->param(
725         minlength_cardnumber => $min,
726         maxlength_cardnumber => $max
727     );
728 }
729
730 output_html_with_http_headers $input, $cookie, $template->output;
731
732 sub  parse_extended_patron_attributes {
733     my ($input) = @_;
734     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->param();
735
736     my @attr = ();
737     my %dups = ();
738     foreach my $key (@patron_attr) {
739         my $value = $input->param($key);
740         next unless defined($value) and $value ne '';
741         my $password = $input->param("${key}_password");
742         my $code     = $input->param("${key}_code");
743         next if exists $dups{$code}->{$value};
744         $dups{$code}->{$value} = 1;
745         push @attr, { code => $code, value => $value, password => $password };
746     }
747     return \@attr;
748 }
749
750 sub patron_attributes_form {
751     my $template = shift;
752     my $borrowernumber = shift;
753
754     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
755     if (scalar(@types) == 0) {
756         $template->param(no_patron_attribute_types => 1);
757         return;
758     }
759     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
760     my @classes = uniq( map {$_->{class}} @$attributes );
761     @classes = sort @classes;
762
763     # map patron's attributes into a more convenient structure
764     my %attr_hash = ();
765     foreach my $attr (@$attributes) {
766         push @{ $attr_hash{$attr->{code}} }, $attr;
767     }
768
769     my @attribute_loop = ();
770     my $i = 0;
771     my %items_by_class;
772     foreach my $type_code (map { $_->{code} } @types) {
773         my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
774         my $entry = {
775             class             => $attr_type->class(),
776             code              => $attr_type->code(),
777             description       => $attr_type->description(),
778             repeatable        => $attr_type->repeatable(),
779             password_allowed  => $attr_type->password_allowed(),
780             category          => $attr_type->authorised_value_category(),
781             category_code     => $attr_type->category_code(),
782             password          => '',
783         };
784         if (exists $attr_hash{$attr_type->code()}) {
785             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
786                 my $newentry = { %$entry };
787                 $newentry->{value} = $attr->{value};
788                 $newentry->{password} = $attr->{password};
789                 $newentry->{use_dropdown} = 0;
790                 if ($attr_type->authorised_value_category()) {
791                     $newentry->{use_dropdown} = 1;
792                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
793                 }
794                 $i++;
795                 $newentry->{form_id} = "patron_attr_$i";
796                 push @{$items_by_class{$attr_type->class()}}, $newentry;
797             }
798         } else {
799             $i++;
800             my $newentry = { %$entry };
801             if ($attr_type->authorised_value_category()) {
802                 $newentry->{use_dropdown} = 1;
803                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
804             }
805             $newentry->{form_id} = "patron_attr_$i";
806             push @{$items_by_class{$attr_type->class()}}, $newentry;
807         }
808     }
809     while ( my ($class, @items) = each %items_by_class ) {
810         my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
811         push @attribute_loop, {
812             class => $class,
813             items => @items,
814             lib   => $lib,
815         }
816     }
817
818     $template->param(patron_attributes => \@attribute_loop);
819
820 }
821
822 # Local Variables:
823 # tab-width: 8
824 # End: