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