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