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