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