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