Bug 14570: Make it possible to add multiple guarantors to a record
[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::Members::Attributes;
34 use C4::Members::AttributeTypes;
35 use C4::Koha;
36 use C4::Log;
37 use C4::Letters;
38 use C4::Form::MessagingPreferences;
39 use Koha::AuthUtils;
40 use Koha::AuthorisedValues;
41 use Koha::Patron::Debarments;
42 use Koha::Cities;
43 use Koha::DateUtils;
44 use Koha::Libraries;
45 use Koha::Patrons;
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 Koha::SMS::Providers;
52
53 use vars qw($debug);
54
55 BEGIN {
56         $debug = $ENV{DEBUG} || 0;
57 }
58         
59 my $input = new CGI;
60 ($debug) or $debug = $input->param('debug') || 0;
61 my %data;
62
63 my $dbh = C4::Context->dbh;
64
65 my ($template, $loggedinuser, $cookie)
66     = get_template_and_user({template_name => "members/memberentrygen.tt",
67            query => $input,
68            type => "intranet",
69            authnotrequired => 0,
70            flagsrequired => {borrowers => 'edit_borrowers'},
71            debug => ($debug) ? 1 : 0,
72        });
73
74 my $borrowernumber = $input->param('borrowernumber');
75 my $patron         = Koha::Patrons->find($borrowernumber);
76
77 if ( $borrowernumber and not $patron ) {
78     output_and_exit( $input, $cookie, $template,  'unknown_patron' );
79 }
80
81 if ( C4::Context->preference('SMSSendDriver') eq 'Email' ) {
82     my @providers = Koha::SMS::Providers->search();
83     $template->param( sms_providers => \@providers );
84 }
85
86 my $actionType     = $input->param('actionType') || '';
87 my $modify         = $input->param('modify');
88 my $delete         = $input->param('delete');
89 my $op             = $input->param('op');
90 my $destination    = $input->param('destination');
91 my $cardnumber     = $input->param('cardnumber');
92 my $check_member   = $input->param('check_member');
93 my $nodouble       = $input->param('nodouble');
94 my $duplicate      = $input->param('duplicate');
95 my $quickadd       = $input->param('quickadd');
96 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
97                                      # modifying an existing patron, it ipso facto
98                                      # isn't a duplicate.  Marking FIXME because this
99                                      # script needs to be refactored.
100 my $nok           = $input->param('nok');
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 ## 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 = 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 ) or die "Not logged in";
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
266 ###############test to take the right zipcode, country and city name ##############
267 # set only if parameter was passed from the form
268 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
269 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
270 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
271
272 $newdata{'lang'}    = $input->param('lang')    if defined($input->param('lang'));
273
274 # builds default userid
275 # userid input text may be empty or missing because of syspref BorrowerUnwantedField
276 if ( ( defined $newdata{'userid'} && $newdata{'userid'} eq '' ) || $check_BorrowerUnwantedField =~ /userid/ && !defined $data{'userid'} ) {
277     my $fake_patron = Koha::Patron->new;
278     $fake_patron->userid($patron->userid) if $patron; # editing
279     if ( ( defined $newdata{'firstname'} || $category_type eq 'I' ) && ( defined $newdata{'surname'} ) ) {
280         # Full page edit, firstname and surname input zones are present
281         $fake_patron->firstname($newdata{firstname});
282         $fake_patron->surname($newdata{surname});
283         $fake_patron->generate_userid;
284         $newdata{'userid'} = $fake_patron->userid;
285     }
286     elsif ( ( defined $data{'firstname'} || $category_type eq 'I' ) && ( defined $data{'surname'} ) ) {
287         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
288         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
289         # FIXME clean thiscode newdata vs data is very confusing
290         $fake_patron->firstname($data{firstname});
291         $fake_patron->surname($data{surname});
292         $fake_patron->generate_userid;
293         $newdata{'userid'} = $fake_patron->userid;
294     }
295     else {
296         $newdata{'userid'} = $data{'userid'};
297     }
298 }
299   
300 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
301 my $extended_patron_attributes = ();
302 if ($op eq 'save' || $op eq 'insert'){
303
304     output_and_exit( $input, $cookie, $template,  'wrong_csrf_token' )
305         unless Koha::Token->new->check_csrf({
306             session_id => scalar $input->cookie('CGISESSID'),
307             token  => scalar $input->param('csrf_token'),
308         });
309
310     # If the cardnumber is blank, treat it as null.
311     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
312
313     if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
314         push @errors, $error_code == 1
315             ? 'ERROR_cardnumber_already_exists'
316             : $error_code == 2
317                 ? 'ERROR_cardnumber_length'
318                 : ()
319     }
320
321     my $dateofbirth;
322     if ($op eq 'save' && $step == 3) {
323         $dateofbirth = $patron->dateofbirth;
324     }
325     else {
326         $dateofbirth = $newdata{dateofbirth};
327     }
328
329     if ( $dateofbirth ) {
330         my $patron = Koha::Patron->new({ dateofbirth => $dateofbirth });
331         my $age = $patron->get_age;
332         my $borrowercategory = Koha::Patron::Categories->find($categorycode);
333         my ($low,$high) = ($borrowercategory->dateofbirthrequired, $borrowercategory->upperagelimit);
334         if (($high && ($age > $high)) or ($age < $low)) {
335             push @errors, 'ERROR_age_limitations';
336             $template->param( age_low => $low);
337             $template->param( age_high => $high);
338         }
339     }
340   
341   if (C4::Context->preference("IndependentBranches")) {
342     unless ( C4::Context->IsSuperLibrarian() ){
343       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
344       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
345         push @errors, "ERROR_branch";
346       }
347     }
348   }
349   # Check if the 'userid' is unique. 'userid' might not always be present in
350   # the edited values list when editing certain sub-forms. Get it straight
351   # from the DB if absent.
352   my $userid = $newdata{ userid } // $borrower_data->{ userid };
353   my $p = $borrowernumber ? Koha::Patrons->find( $borrowernumber ) : Koha::Patron->new;
354   $p->userid( $userid );
355   unless ( $p->has_valid_userid ) {
356     push @errors, "ERROR_login_exist";
357   }
358
359   my $password = $input->param('password');
360   my $password2 = $input->param('password2');
361   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
362
363   if ( $password and $password ne '****' ) {
364       my ( $is_valid, $error ) = Koha::AuthUtils::is_password_valid( $password );
365       unless ( $is_valid ) {
366           push @errors, 'ERROR_password_too_short' if $error eq 'too_short';
367           push @errors, 'ERROR_password_too_weak' if $error eq 'too_weak';
368           push @errors, 'ERROR_password_has_whitespaces' if $error eq 'has_whitespaces';
369       }
370   }
371
372   # Validate emails
373   my $emailprimary = $input->param('email');
374   my $emailsecondary = $input->param('emailpro');
375   my $emailalt = $input->param('B_email');
376
377   if ($emailprimary) {
378       push (@errors, "ERROR_bad_email") if (!Email::Valid->address($emailprimary));
379   }
380   if ($emailsecondary) {
381       push (@errors, "ERROR_bad_email_secondary") if (!Email::Valid->address($emailsecondary));
382   }
383   if ($emailalt) {
384       push (@errors, "ERROR_bad_email_alternative") if (!Email::Valid->address($emailalt));
385   }
386
387   if (C4::Context->preference('ExtendedPatronAttributes')) {
388     $extended_patron_attributes = parse_extended_patron_attributes($input);
389     foreach my $attr (@$extended_patron_attributes) {
390         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
391             my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
392             push @errors, "ERROR_extended_unique_id_failed";
393             $template->param(
394                 ERROR_extended_unique_id_failed_code => $attr->{code},
395                 ERROR_extended_unique_id_failed_value => $attr->{value},
396                 ERROR_extended_unique_id_failed_description => $attr_info->description()
397             );
398         }
399     }
400   }
401 }
402
403 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
404     unless ($newdata{'dateexpiry'}){
405         my $patron_category = Koha::Patron::Categories->find( $newdata{categorycode} );
406         $newdata{'dateexpiry'} = $patron_category->get_expiry_date( $newdata{dateenrolled} ) if $patron_category;
407     }
408 }
409
410 # BZ 14683: Do not mixup mobile [read: other phone] with smsalertnumber
411 my $sms = $input->param('SMSnumber');
412 if ( defined $sms ) {
413     $newdata{smsalertnumber} = $sms;
414 }
415
416 ###  Error checks should happen before this line.
417 $nok = $nok || scalar(@errors);
418 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
419         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
420         if ($op eq 'insert'){
421                 # we know it's not a duplicate borrowernumber or there would already be an error
422         delete $newdata{password2};
423         my $patron = eval { Koha::Patron->new(\%newdata)->store };
424         if ( $@ ) {
425             # FIXME Urgent error handling here, we cannot fail without relevant feedback
426             # Lot of code will need to be removed from this script to handle exceptions raised by Koha::Patron->store
427             warn "Patron creation failed! - $@"; # Maybe we must die instead of just warn
428         } else {
429             add_guarantors( $patron, $input );
430             $borrowernumber = $patron->borrowernumber;
431             $newdata{'borrowernumber'} = $borrowernumber;
432         }
433
434         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
435         if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'}  && $newdata{'password'}) {
436             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
437             my $emailaddr;
438             if  (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF'  && 
439                 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~  /\w\@\w/ ) {
440                 $emailaddr =   $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} 
441             } 
442             elsif ($newdata{email} =~ /\w\@\w/) {
443                 $emailaddr = $newdata{email} 
444             }
445             elsif ($newdata{emailpro} =~ /\w\@\w/) {
446                 $emailaddr = $newdata{emailpro} 
447             }
448             elsif ($newdata{B_email} =~ /\w\@\w/) {
449                 $emailaddr = $newdata{B_email} 
450             }
451             # if we manage to find a valid email address, send notice 
452             if ($emailaddr) {
453                 $newdata{emailaddr} = $emailaddr;
454                 my $err;
455                 eval {
456                     $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
457                 };
458                 if ( $@ ) {
459                     $template->param(error_alert => $@);
460                 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
461                     $template->{VARS}->{'error_alert'} = "no_email";
462                 } else {
463                     $template->{VARS}->{'info_alert'} = 1;
464                 }
465             }
466         }
467
468         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
469             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
470         }
471         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
472             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
473         }
474
475         # Create HouseboundRole if necessary.
476         # Borrower did not exist, so HouseboundRole *cannot* yet exist.
477         my ( $hsbnd_chooser, $hsbnd_deliverer ) = ( 0, 0 );
478         $hsbnd_chooser = 1 if $input->param('housebound_chooser');
479         $hsbnd_deliverer = 1 if $input->param('housebound_deliverer');
480         # Only create a HouseboundRole if patron has a role.
481         if ( $hsbnd_chooser || $hsbnd_deliverer ) {
482             Koha::Patron::HouseboundRole->new({
483                 borrowernumber_id    => $borrowernumber,
484                 housebound_chooser   => $hsbnd_chooser,
485                 housebound_deliverer => $hsbnd_deliverer,
486             })->store;
487         }
488
489     } elsif ($op eq 'save') {
490
491         # Update or create our HouseboundRole if necessary.
492         my $housebound_role = Koha::Patron::HouseboundRoles->find($borrowernumber);
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         if ( $housebound_role ) {
497             if ( $hsbnd_chooser || $hsbnd_deliverer ) {
498                 # Update our HouseboundRole.
499                 $housebound_role
500                     ->housebound_chooser($hsbnd_chooser)
501                     ->housebound_deliverer($hsbnd_deliverer)
502                     ->store;
503             } else {
504                 $housebound_role->delete; # No longer needed.
505             }
506         } else {
507             # Only create a HouseboundRole if patron has a role.
508             if ( $hsbnd_chooser || $hsbnd_deliverer ) {
509                 $housebound_role = Koha::Patron::HouseboundRole->new({
510                     borrowernumber_id    => $borrowernumber,
511                     housebound_chooser   => $hsbnd_chooser,
512                     housebound_deliverer => $hsbnd_deliverer,
513                 })->store;
514             }
515         }
516
517         if ($NoUpdateLogin) {
518             delete $newdata{'password'};
519             delete $newdata{'userid'};
520         }
521
522         my $patron = Koha::Patrons->find( $borrowernumber );
523         $newdata{debarredcomment} = $newdata{debarred_comment};
524         delete $newdata{debarred_comment};
525         delete $newdata{password2};
526         $patron->set(\%newdata)->store if scalar(keys %newdata) > 1; # bug 4508 - avoid crash if we're not
527                                                                 # updating any columns in the borrowers table,
528                                                                 # which can happen if we're only editing the
529                                                                 # patron attributes or messaging preferences sections
530
531         # should never raise an exception as password validity is checked above
532         my $password = $newdata{password};
533         if ( $password and $password ne '****' ) {
534             $patron->set_password({ password => $password });
535         }
536
537         add_guarantors( $patron, $input );
538         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
539             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
540         }
541         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
542             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
543         }
544         }
545
546     if ( $destination eq 'circ' and not C4::Auth::haspermission( C4::Context->userenv->{id}, { circulate => 'circulate_remaining_permissions' } ) ) {
547         # If we want to redirect to circulation.pl and need to check if the logged in user has the necessary permission
548         $destination = 'not_circ';
549     }
550     print scalar( $destination eq "circ" )
551       ? $input->redirect(
552         "/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber")
553       : $input->redirect(
554         "/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber"
555       );
556     exit; # You can only send 1 redirect!  After that, content or other headers don't matter.
557 }
558
559 if ($delete){
560         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
561         exit;           # same as above
562 }
563
564 if ($nok or !$nodouble){
565     $op="add" if ($op eq "insert");
566     $op="modify" if ($op eq "save");
567     %data=%newdata; 
568     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
569     unless ($step){  
570         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1, step_7 => 1 );
571     }  
572
573 if (C4::Context->preference("IndependentBranches")) {
574     my $userenv = C4::Context->userenv;
575     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
576         unless ($userenv->{branch} eq $data{'branchcode'}){
577             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
578             exit;
579         }
580     }
581 }
582 if ($op eq 'add'){
583     $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);
584 }
585 if ($op eq "modify")  {
586     $template->param( updtype => 'M',modify => 1 );
587     $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;
588     if ( $step == 4 ) {
589         $template->param( categorycode => $borrower_data->{'categorycode'} );
590     }
591 }
592 if ( $op eq "duplicate" ) {
593     $template->param( updtype => 'I' );
594     $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;
595     $data{'cardnumber'} = "";
596 }
597
598 if(!defined($data{'sex'})){
599     $template->param( none => 1);
600 } elsif($data{'sex'} eq 'F'){
601     $template->param( female => 1);
602 } elsif ($data{'sex'} eq 'M'){
603     $template->param(  male => 1);
604 } else {
605     $template->param(  none => 1);
606 }
607
608 ##Now all the data to modify a member.
609
610 my @typeloop;
611 my $no_categories = 1;
612 my $no_add;
613 foreach my $category_type (qw(C A S P I X)) {
614     my $patron_categories = Koha::Patron::Categories->search_limited({ category_type => $category_type }, {order_by => ['categorycode']});
615     $no_categories = 0 if $patron_categories->count > 0;
616
617     my @categoryloop;
618     while ( my $patron_category = $patron_categories->next ) {
619         push @categoryloop,
620           { 'categorycode' => $patron_category->categorycode,
621             'categoryname' => $patron_category->description,
622             'categorycodeselected' =>
623               ( defined($categorycode) && $patron_category->categorycode eq $categorycode ),
624           };
625     }
626     my %typehash;
627     $typehash{'typename'} = $category_type;
628     my $typedescription = "typename_" . $typehash{'typename'};
629     $typehash{'categoryloop'} = \@categoryloop;
630     push @typeloop,
631       { 'typename'       => $category_type,
632         $typedescription => 1,
633         'categoryloop'   => \@categoryloop
634       };
635 }
636 $template->param(
637     typeloop      => \@typeloop,
638     no_categories => $no_categories,
639 );
640
641 my $cities = Koha::Cities->search( {}, { order_by => 'city_name' } );
642 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE' );
643 $template->param(
644     roadtypes => $roadtypes,
645     cities    => $cities,
646 );
647
648 my $default_borrowertitle = '';
649 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
650
651 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
652 my @relshipdata;
653 while (@relationships) {
654   my $relship = shift @relationships || '';
655   my %row = ('relationship' => $relship);
656   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
657     $row{'selected'}=' selected';
658   } else {
659     $row{'selected'}='';
660   }
661   push(@relshipdata, \%row);
662 }
663
664 my %flags = (
665     'gonenoaddress' => ['gonenoaddress'],
666     'lost'          => ['lost']
667 );
668
669 my @flagdata;
670 foreach ( keys(%flags) ) {
671     my $key = $_;
672     my %row = (
673         'key'  => $key,
674         'name' => $flags{$key}[0]
675     );
676     if ( $data{$key} ) {
677         $row{'yes'} = ' checked';
678         $row{'no'}  = '';
679     }
680     else {
681         $row{'yes'} = '';
682         $row{'no'}  = ' checked';
683     }
684     push @flagdata, \%row;
685 }
686
687 # get Branch Loop
688 # in modify mod: userbranch value comes from borrowers table
689 # in add    mod: userbranch value comes from branches table (ip correspondence)
690
691 my $userbranch = '';
692 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
693     $userbranch = C4::Context->userenv->{'branch'};
694 }
695
696 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
697     $userbranch = $data{'branchcode'};
698 }
699 $template->param( userbranch => $userbranch );
700
701 if ( Koha::Libraries->search->count < 1 ){
702     $no_add = 1;
703     $template->param(no_branches => 1);
704 }
705 if($no_categories){
706     $no_add = 1;
707     $template->param(no_categories => 1);
708 }
709 $template->param(no_add => $no_add);
710 # --------------------------------------------------------------------------------------------------------
711
712 $template->param( sort1 => $data{'sort1'});
713 $template->param( sort2 => $data{'sort2'});
714
715 if ($nok) {
716     foreach my $error (@errors) {
717         $template->param($error) || $template->param( $error => 1);
718     }
719     $template->param(nok => 1);
720 }
721   
722   #Formatting data for display    
723   
724 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
725   $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
726 }
727 if ( $op eq 'duplicate' ) {
728     $data{'dateenrolled'} = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
729     my $patron_category = Koha::Patron::Categories->find( $data{categorycode} );
730     $data{dateexpiry} = $patron_category->get_expiry_date( $data{dateenrolled} );
731 }
732 if (C4::Context->preference('uppercasesurnames')) {
733     $data{'surname'} &&= uc( $data{'surname'} );
734     $data{'contactname'} &&= uc( $data{'contactname'} );
735 }
736
737 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
738     if ( $data{$_} ) {
739        $data{$_} = eval { output_pref({ dt => dt_from_string( $data{$_} ), dateonly => 1 } ); };  # back to syspref for display
740     }
741     $template->param( $_ => $data{$_});
742 }
743
744 if (C4::Context->preference('ExtendedPatronAttributes')) {
745     patron_attributes_form($template, $borrowernumber, $op);
746 }
747
748 if (C4::Context->preference('EnhancedMessagingPreferences')) {
749     if ($op eq 'add') {
750         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
751     } else {
752         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
753     }
754     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
755     $template->param(SMSnumber     => $data{'smsalertnumber'} );
756     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
757 }
758
759 $template->param( "show_guarantor" => ( $category_type =~ /A|I|S|X/ ) ? 0 : 1 ); # associate with step to know where you are
760 $debug and warn "memberentry step: $step";
761 $template->param(%data);
762 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
763 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
764
765 $template->param(
766   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
767   category_type => $category_type,#to know the category type of the borrower
768   "$category_type"  => 1,# associate with step to know where u are
769   destination   => $destination,#to know wher u come from and wher u must go in redirect
770   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
771   "op$op"   => 1);
772
773 $template->param(
774   patron => $patron ? $patron : \%newdata, # Used by address include templates now
775   nodouble  => $nodouble,
776   borrowernumber  => $borrowernumber, #register number
777   relshiploop => \@relshipdata,
778   btitle=> $default_borrowertitle,
779   flagloop  => \@flagdata,
780   category_type =>$category_type,
781   modify          => $modify,
782   nok     => $nok,#flag to know if an error
783   NoUpdateLogin =>  $NoUpdateLogin,
784   );
785
786 # Generate CSRF token
787 $template->param( csrf_token =>
788       Koha::Token->new->generate_csrf( { session_id => scalar $input->cookie('CGISESSID'), } ),
789 );
790
791 # HouseboundModule data
792 $template->param(
793     housebound_role  => scalar Koha::Patron::HouseboundRoles->find($borrowernumber),
794 );
795
796 if(defined($data{'flags'})){
797   $template->param(flags=>$data{'flags'});
798 }
799 if(defined($data{'contacttitle'})){
800   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
801 }
802
803
804 my ( $min, $max ) = C4::Members::get_cardnumber_length();
805 if ( defined $min ) {
806     $template->param(
807         minlength_cardnumber => $min,
808         maxlength_cardnumber => $max
809     );
810 }
811
812 if ( C4::Context->preference('TranslateNotices') ) {
813     my $translated_languages = C4::Languages::getTranslatedLanguages( 'opac', C4::Context->preference('template') );
814     $template->param( languages => $translated_languages );
815 }
816
817 output_html_with_http_headers $input, $cookie, $template->output;
818
819 sub  parse_extended_patron_attributes {
820     my ($input) = @_;
821     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->multi_param();
822
823     my @attr = ();
824     my %dups = ();
825     foreach my $key (@patron_attr) {
826         my $value = $input->param($key);
827         next unless defined($value) and $value ne '';
828         my $code     = $input->param("${key}_code");
829         next if exists $dups{$code}->{$value};
830         $dups{$code}->{$value} = 1;
831         push @attr, { code => $code, value => $value };
832     }
833     return \@attr;
834 }
835
836 sub patron_attributes_form {
837     my $template = shift;
838     my $borrowernumber = shift;
839     my $op = shift;
840
841     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
842     if (scalar(@types) == 0) {
843         $template->param(no_patron_attribute_types => 1);
844         return;
845     }
846     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
847     my @classes = uniq( map {$_->{class}} @$attributes );
848     @classes = sort @classes;
849
850     # map patron's attributes into a more convenient structure
851     my %attr_hash = ();
852     foreach my $attr (@$attributes) {
853         push @{ $attr_hash{$attr->{code}} }, $attr;
854     }
855
856     my @attribute_loop = ();
857     my $i = 0;
858     my %items_by_class;
859     foreach my $type_code (map { $_->{code} } @types) {
860         my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
861         my $entry = {
862             class             => $attr_type->class(),
863             code              => $attr_type->code(),
864             description       => $attr_type->description(),
865             repeatable        => $attr_type->repeatable(),
866             category          => $attr_type->authorised_value_category(),
867             category_code     => $attr_type->category_code(),
868         };
869         if (exists $attr_hash{$attr_type->code()}) {
870             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
871                 my $newentry = { %$entry };
872                 $newentry->{value} = $attr->{value};
873                 $newentry->{use_dropdown} = 0;
874                 if ($attr_type->authorised_value_category()) {
875                     $newentry->{use_dropdown} = 1;
876                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
877                 }
878                 $i++;
879                 undef $newentry->{value} if ($attr_type->unique_id() && $op eq 'duplicate');
880                 $newentry->{form_id} = "patron_attr_$i";
881                 push @{$items_by_class{$attr_type->class()}}, $newentry;
882             }
883         } else {
884             $i++;
885             my $newentry = { %$entry };
886             if ($attr_type->authorised_value_category()) {
887                 $newentry->{use_dropdown} = 1;
888                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
889             }
890             $newentry->{form_id} = "patron_attr_$i";
891             push @{$items_by_class{$attr_type->class()}}, $newentry;
892         }
893     }
894     while ( my ($class, @items) = each %items_by_class ) {
895         my $av = Koha::AuthorisedValues->search({ category => 'PA_CLASS', authorised_value => $class });
896         my $lib = $av->count ? $av->next->lib : $class;
897         push @attribute_loop, {
898             class => $class,
899             items => @items,
900             lib   => $lib,
901         }
902     }
903
904     $template->param(patron_attributes => \@attribute_loop);
905
906 }
907
908 sub add_guarantors {
909     my ( $patron, $input ) = @_;
910
911     my @new_guarantor_id           = $input->multi_param('new_guarantor_id');
912     my @new_guarantor_relationship = $input->multi_param('new_guarantor_relationship');
913
914     for ( my $i = 0 ; $i < scalar @new_guarantor_id; $i++ ) {
915         my $guarantor_id = $new_guarantor_id[$i];
916         my $relationship = $new_guarantor_relationship[$i];
917
918         next unless $guarantor_id;
919
920         $patron->add_guarantor(
921             {
922                 guarantee_id => $patron->id,
923                 guarantor_id => $guarantor_id,
924                 relationship => $relationship,
925             }
926         );
927     }
928 }
929
930 # Local Variables:
931 # tab-width: 8
932 # End: