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