Bug 14910: Redirect to the circulation module after a renew
[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::Dates qw/format_date format_date_in_iso/;
39 use C4::Log;
40 use C4::Letters;
41 use C4::Branch; # GetBranches
42 use C4::Form::MessagingPreferences;
43 use Koha::Borrower::Debarments;
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
51 use vars qw($debug);
52
53 BEGIN {
54         $debug = $ENV{DEBUG} || 0;
55 }
56         
57 my $input = new CGI;
58 ($debug) or $debug = $input->param('debug') || 0;
59 my %data;
60
61 my $dbh = C4::Context->dbh;
62
63 my ($template, $loggedinuser, $cookie)
64     = get_template_and_user({template_name => "members/memberentrygen.tt",
65            query => $input,
66            type => "intranet",
67            authnotrequired => 0,
68            flagsrequired => {borrowers => 1},
69            debug => ($debug) ? 1 : 0,
70        });
71
72 my $guarantorid    = $input->param('guarantorid');
73 my $borrowernumber = $input->param('borrowernumber');
74 my $actionType     = $input->param('actionType') || '';
75 my $modify         = $input->param('modify');
76 my $delete         = $input->param('delete');
77 my $op             = $input->param('op');
78 my $destination    = $input->param('destination');
79 my $cardnumber     = $input->param('cardnumber');
80 my $check_member   = $input->param('check_member');
81 my $nodouble       = $input->param('nodouble');
82 my $duplicate      = $input->param('duplicate');
83 $nodouble = 1 if ($op eq 'modify' or $op eq 'duplicate');    # FIXME hack to represent fact that if we're
84                                      # modifying an existing patron, it ipso facto
85                                      # isn't a duplicate.  Marking FIXME because this
86                                      # script needs to be refactored.
87 my $select_city   = $input->param('select_city');
88 my $nok           = $input->param('nok');
89 my $guarantorinfo = $input->param('guarantorinfo');
90 my $step          = $input->param('step') || 0;
91 my @errors;
92 my $default_city;
93 # NOTE: Alert for ethnicity and ethnotes fields, they are invalid in all borrowers form
94 my $borrower_data;
95 my $NoUpdateLogin;
96 my $userenv = C4::Context->userenv;
97
98
99 ## Deal with debarments
100 $template->param(
101     debarments => GetDebarments( { borrowernumber => $borrowernumber } ) );
102 my @debarments_to_remove = $input->param('remove_debarment');
103 foreach my $d ( @debarments_to_remove ) {
104     DelDebarment( $d );
105 }
106 if ( $input->param('add_debarment') ) {
107
108     my $expiration = $input->param('debarred_expiration');
109     $expiration =
110       $expiration
111       ? output_pref(
112         { 'dt' => dt_from_string($expiration), 'dateformat' => 'iso' } )
113       : undef;
114
115     AddDebarment(
116         {
117             borrowernumber => $borrowernumber,
118             type           => 'MANUAL',
119             comment        => $input->param('debarred_comment'),
120             expiration     => $expiration,
121         }
122     );
123 }
124
125 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
126
127 my $minpw = C4::Context->preference('minPasswordLength');
128 $template->param("minPasswordLength" => $minpw);
129
130 # function to designate mandatory fields (visually with css)
131 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
132 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
133 foreach (@field_check) {
134         $template->param( "mandatory$_" => 1);    
135 }
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 unless ($category_type or !($categorycode)){
150     my $borrowercategory = GetBorrowercategory($categorycode);
151     $category_type    = $borrowercategory->{'category_type'};
152     my $category_name = $borrowercategory->{'description'}; 
153     $template->param("categoryname"=>$category_name);
154 }
155 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
156
157 # if a add or modify is requested => check validity of data.
158 %data = %$borrower_data if ($borrower_data);
159
160 # initialize %newdata
161 my %newdata;                                                                             # comes from $input->param()
162 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
163     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
164     foreach my $key (@names) {
165         if (defined $input->param($key)) {
166             $newdata{$key} = $input->param($key);
167             $newdata{$key} =~ s/\"/&quot;/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
168         }
169     }
170
171     my $dateobject = C4::Dates->new();
172     my $syspref = $dateobject->regexp();                # same syspref format for all 3 dates
173     my $iso     = $dateobject->regexp('iso');   #
174     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
175         next unless exists $newdata{$_};
176         my $userdate = $newdata{$_} or next;
177         if ($userdate =~ /$syspref/) {
178             $newdata{$_} = format_date_in_iso($userdate);       # if they match syspref format, then convert to ISO
179         } elsif ($userdate =~ /$iso/) {
180             warn "Date $_ ($userdate) is already in ISO format";
181         } else {
182             ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
183             $template->param( "ERROR_$_" => 1 );        # else ERROR!
184             push(@errors,"ERROR_$_");
185         }
186     }
187   # check permission to modify login info.
188     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
189         $NoUpdateLogin = 1;
190     }
191 }
192
193 # remove keys from %newdata that ModMember() doesn't like
194 {
195     my @keys_to_delete = (
196         qr/^BorrowerMandatoryField$/,
197         qr/^category_type$/,
198         qr/^check_member$/,
199         qr/^destination$/,
200         qr/^nodouble$/,
201         qr/^op$/,
202         qr/^save$/,
203         qr/^updtype$/,
204         qr/^SMSnumber$/,
205         qr/^setting_extended_patron_attributes$/,
206         qr/^setting_messaging_prefs$/,
207         qr/^digest$/,
208         qr/^modify$/,
209         qr/^step$/,
210         qr/^\d+$/,
211         qr/^\d+-DAYS/,
212         qr/^patron_attr_/,
213     );
214     for my $regexp (@keys_to_delete) {
215         for (keys %newdata) {
216             delete($newdata{$_}) if /$regexp/;
217         }
218     }
219 }
220
221 #############test for member being unique #############
222 if ( ( $op eq 'insert' ) and !$nodouble ) {
223     my $category_type_send;
224     if ( $category_type eq 'I' ) {
225         $category_type_send = $category_type;
226     }
227     my $check_category;    # recover the category code of the doublon suspect borrowers
228      #   ($result,$categorycode) = checkuniquemember($collectivity,$surname,$firstname,$dateofbirth)
229     ( $check_member, $check_category ) = checkuniquemember(
230         $category_type_send,
231         ( $newdata{surname}     ? $newdata{surname}     : $data{surname} ),
232         ( $newdata{firstname}   ? $newdata{firstname}   : $data{firstname} ),
233         ( $newdata{dateofbirth} ? $newdata{dateofbirth} : $data{dateofbirth} )
234     );
235     if ( !$check_member ) {
236         $nodouble = 1;
237     }
238 }
239
240   #recover all data from guarantor address phone ,fax... 
241 if ( $guarantorid ) {
242     if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
243         $category_type = $guarantordata->{categorycode} eq 'I' ? 'P' : 'C';
244         $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
245         $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
246         $newdata{'contactname'}     = $guarantordata->{'surname'};
247         $newdata{'contacttitle'}    = $guarantordata->{'title'};
248         if ( $op eq 'add' ) {
249                 foreach (qw(streetnumber address streettype address2
250                         zipcode country city state phone phonepro mobile fax email emailpro branchcode
251                         B_streetnumber B_streettype B_address B_address2
252                         B_city B_state B_zipcode B_country B_email B_phone)) {
253                         $newdata{$_} = $guarantordata->{$_};
254                 }
255         }
256     }
257 }
258
259 ###############test to take the right zipcode, country and city name ##############
260 # set only if parameter was passed from the form
261 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
262 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
263 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
264
265 #builds default userid
266 if ( (defined $newdata{'userid'}) && ($newdata{'userid'} eq '')){
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'} || C4::Dates->today('iso');
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 my ($categories,$labels)=ethnicitycategories();
511   
512 my $ethnicitycategoriescount=$#{$categories};
513 my $ethcatpopup;
514 if ($ethnicitycategoriescount>=0) {
515   $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
516         -id => 'ethnicity',
517         -tabindex=>'',
518         -values=>$categories,
519         -default=>$data{'ethnicity'},
520         -labels=>$labels);
521   $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
522 }
523
524 my @typeloop;
525 my $no_categories = 1;
526 my $no_add;
527 foreach (qw(C A S P I X)) {
528     my $action="WHERE category_type=?";
529         ($categories,$labels)=GetborCatFromCatType($_,$action);
530     if(scalar(@$categories) > 0){ $no_categories = 0; }
531         my @categoryloop;
532         foreach my $cat (@$categories){
533                 push @categoryloop,{'categorycode' => $cat,
534                           'categoryname' => $labels->{$cat},
535                           'categorycodeselected' => ((defined($borrower_data->{'categorycode'}) && 
536                                                      $cat eq $borrower_data->{'categorycode'}) 
537                                                      || (defined($categorycode) && $cat eq $categorycode)),
538                 };
539         }
540         my %typehash;
541         $typehash{'typename'}=$_;
542     my $typedescription = "typename_".$typehash{'typename'};
543         $typehash{'categoryloop'}=\@categoryloop;
544         push @typeloop,{'typename' => $_,
545         $typedescription => 1,
546           'categoryloop' => \@categoryloop};
547 }
548 $template->param('typeloop' => \@typeloop,
549         no_categories => $no_categories);
550 if($no_categories){ $no_add = 1; }
551 # test in city
552 if ( $guarantorid ) {
553     $select_city = getidcity($data{city});
554 }
555 ($default_city=$select_city) if ($step eq 0);
556 if (!defined($select_city) or $select_city eq '' ){
557         $default_city = &getidcity($data{'city'});
558 }
559
560 my $city_arrayref = GetCities();
561 if (@{$city_arrayref} ) {
562     $template->param( city_cgipopup => 1);
563
564     if ($default_city) { # flag the current or default val
565         for my $city ( @{$city_arrayref} ) {
566             if ($default_city == $city->{cityid}) {
567                 $city->{selected} = 1;
568                 last;
569             }
570         }
571     }
572 }
573   
574 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE', $data{streettype} );
575 $template->param( roadtypes => $roadtypes);
576
577 my $default_borrowertitle = '';
578 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
579 my($borrowertitle)=GetTitles();
580 $template->param( title_cgipopup => 1) if ($borrowertitle);
581 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
582         -id => 'btitle',
583         -values=>$borrowertitle,
584         -override => 1,
585         -default=>$default_borrowertitle
586         );    
587
588 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
589 my @relshipdata;
590 while (@relationships) {
591   my $relship = shift @relationships || '';
592   my %row = ('relationship' => $relship);
593   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
594     $row{'selected'}=' selected';
595   } else {
596     $row{'selected'}='';
597   }
598   push(@relshipdata, \%row);
599 }
600
601 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
602         'lost'          => ['lost']);
603
604  
605 my @flagdata;
606 foreach (keys(%flags)) {
607         my $key = $_;
608         my %row =  ('key'   => $key,
609                     'name'  => $flags{$key}[0]);
610         if ($data{$key}) {
611                 $row{'yes'}=' checked';
612                 $row{'no'}='';
613     }
614         else {
615                 $row{'yes'}='';
616                 $row{'no'}=' checked';
617         }
618         push @flagdata,\%row;
619 }
620
621 # get Branch Loop
622 # in modify mod: userbranch value for GetBranchesLoop() comes from borrowers table
623 # in add    mod: userbranch value come from branches table (ip correspondence)
624
625 my $userbranch = '';
626 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
627     $userbranch = C4::Context->userenv->{'branch'};
628 }
629
630 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
631     $userbranch = $data{'branchcode'};
632 }
633
634 my $branchloop = GetBranchesLoop( $userbranch );
635
636 if( !$branchloop ){
637     $no_add = 1;
638     $template->param(no_branches => 1);
639 }
640 if($no_categories){
641     $no_add = 1;
642     $template->param(no_categories => 1);
643 }
644 $template->param(no_add => $no_add);
645 # --------------------------------------------------------------------------------------------------------
646
647 $template->param( sort1 => $data{'sort1'});
648 $template->param( sort2 => $data{'sort2'});
649
650 if ($nok) {
651     foreach my $error (@errors) {
652         $template->param($error) || $template->param( $error => 1);
653     }
654     $template->param(nok => 1);
655 }
656   
657   #Formatting data for display    
658   
659 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
660   $data{'dateenrolled'}=C4::Dates->today('iso');
661 }
662 if ( $op eq 'duplicate' ) {
663     $data{'dateenrolled'} = C4::Dates->today('iso');
664     $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, $data{'dateenrolled'} );
665 }
666 if (C4::Context->preference('uppercasesurnames')) {
667     $data{'surname'} &&= uc( $data{'surname'} );
668     $data{'contactname'} &&= uc( $data{'contactname'} );
669 }
670
671 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
672         $data{$_} = format_date($data{$_});     # back to syspref for display
673         $template->param( $_ => $data{$_});
674 }
675
676 if (C4::Context->preference('ExtendedPatronAttributes')) {
677     $template->param(ExtendedPatronAttributes => 1);
678     patron_attributes_form($template, $borrowernumber);
679 }
680
681 if (C4::Context->preference('EnhancedMessagingPreferences')) {
682     if ($op eq 'add') {
683         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
684     } else {
685         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
686     }
687     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
688     $template->param(SMSnumber     => $data{'smsalertnumber'} );
689     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
690 }
691
692 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
693 $debug and warn "memberentry step: $step";
694 $template->param(%data);
695 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
696 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
697
698 $template->param(
699   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
700   category_type => $category_type,#to know the category type of the borrower
701   select_city => $select_city,
702   "$category_type"  => 1,# associate with step to know where u are
703   destination   => $destination,#to know wher u come from and wher u must go in redirect
704   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
705   "op$op"   => 1);
706
707 $template->param( branchloop => $branchloop ) if ( $branchloop );
708 $template->param(
709   nodouble  => $nodouble,
710   borrowernumber  => $borrowernumber, #register number
711   guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
712   ethcatpopup => $ethcatpopup,
713   relshiploop => \@relshipdata,
714   city_loop => $city_arrayref,
715   borrotitlepopup => $borrotitlepopup,
716   guarantorinfo   => $guarantorinfo,
717   flagloop  => \@flagdata,
718   category_type =>$category_type,
719   modify          => $modify,
720   nok     => $nok,#flag to konw if an error 
721   NoUpdateLogin =>  $NoUpdateLogin
722   );
723
724 if(defined($data{'flags'})){
725   $template->param(flags=>$data{'flags'});
726 }
727 if(defined($data{'contacttitle'})){
728   $template->param("contacttitle_" . $data{'contacttitle'} => "SELECTED");
729 }
730
731
732 my ( $min, $max ) = C4::Members::get_cardnumber_length();
733 if ( defined $min ) {
734     $template->param(
735         minlength_cardnumber => $min,
736         maxlength_cardnumber => $max
737     );
738 }
739
740 output_html_with_http_headers $input, $cookie, $template->output;
741
742 sub  parse_extended_patron_attributes {
743     my ($input) = @_;
744     my @patron_attr = grep { /^patron_attr_\d+$/ } $input->param();
745
746     my @attr = ();
747     my %dups = ();
748     foreach my $key (@patron_attr) {
749         my $value = $input->param($key);
750         next unless defined($value) and $value ne '';
751         my $password = $input->param("${key}_password");
752         my $code     = $input->param("${key}_code");
753         next if exists $dups{$code}->{$value};
754         $dups{$code}->{$value} = 1;
755         push @attr, { code => $code, value => $value, password => $password };
756     }
757     return \@attr;
758 }
759
760 sub patron_attributes_form {
761     my $template = shift;
762     my $borrowernumber = shift;
763
764     my @types = C4::Members::AttributeTypes::GetAttributeTypes();
765     if (scalar(@types) == 0) {
766         $template->param(no_patron_attribute_types => 1);
767         return;
768     }
769     my $attributes = C4::Members::Attributes::GetBorrowerAttributes($borrowernumber);
770     my @classes = uniq( map {$_->{class}} @$attributes );
771     @classes = sort @classes;
772
773     # map patron's attributes into a more convenient structure
774     my %attr_hash = ();
775     foreach my $attr (@$attributes) {
776         push @{ $attr_hash{$attr->{code}} }, $attr;
777     }
778
779     my @attribute_loop = ();
780     my $i = 0;
781     my %items_by_class;
782     foreach my $type_code (map { $_->{code} } @types) {
783         my $attr_type = C4::Members::AttributeTypes->fetch($type_code);
784         my $entry = {
785             class             => $attr_type->class(),
786             code              => $attr_type->code(),
787             description       => $attr_type->description(),
788             repeatable        => $attr_type->repeatable(),
789             password_allowed  => $attr_type->password_allowed(),
790             category          => $attr_type->authorised_value_category(),
791             category_code     => $attr_type->category_code(),
792             password          => '',
793         };
794         if (exists $attr_hash{$attr_type->code()}) {
795             foreach my $attr (@{ $attr_hash{$attr_type->code()} }) {
796                 my $newentry = { %$entry };
797                 $newentry->{value} = $attr->{value};
798                 $newentry->{password} = $attr->{password};
799                 $newentry->{use_dropdown} = 0;
800                 if ($attr_type->authorised_value_category()) {
801                     $newentry->{use_dropdown} = 1;
802                     $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category(), $attr->{value});
803                 }
804                 $i++;
805                 $newentry->{form_id} = "patron_attr_$i";
806                 push @{$items_by_class{$attr_type->class()}}, $newentry;
807             }
808         } else {
809             $i++;
810             my $newentry = { %$entry };
811             if ($attr_type->authorised_value_category()) {
812                 $newentry->{use_dropdown} = 1;
813                 $newentry->{auth_val_loop} = GetAuthorisedValues($attr_type->authorised_value_category());
814             }
815             $newentry->{form_id} = "patron_attr_$i";
816             push @{$items_by_class{$attr_type->class()}}, $newentry;
817         }
818     }
819     while ( my ($class, @items) = each %items_by_class ) {
820         my $lib = GetAuthorisedValueByCode( 'PA_CLASS', $class ) || $class;
821         push @attribute_loop, {
822             class => $class,
823             items => @items,
824             lib   => $lib,
825         }
826     }
827
828     $template->param(patron_attributes => \@attribute_loop);
829
830 }
831
832 # Local Variables:
833 # tab-width: 8
834 # End: