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