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