Bug 11271 - Serials table off the screen in smaller viewports
[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 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 # we'll need this, later.
139 my $dateofbirthmandatory = (scalar grep {$_ eq "dateofbirth"} @field_check) ? 1 : 0;
140 # function to designate unwanted fields
141 my $check_BorrowerUnwantedField=C4::Context->preference("BorrowerUnwantedField");
142 @field_check=split(/\|/,$check_BorrowerUnwantedField);
143 foreach (@field_check) {
144     next unless m/\w/o;
145         $template->param( "no$_" => 1);
146 }
147 $template->param( "add" => 1 ) if ( $op eq 'add' );
148 $template->param( "duplicate" => 1 ) if ( $op eq 'duplicate' );
149 $template->param( "checked" => 1 ) if ( defined($nodouble) && $nodouble eq 1 );
150 ( $borrower_data = GetMember( 'borrowernumber' => $borrowernumber ) ) if ( $op eq 'modify' or $op eq 'save' or $op eq 'duplicate' );
151 my $categorycode  = $input->param('categorycode') || $borrower_data->{'categorycode'};
152 my $category_type = $input->param('category_type') || '';
153 if ($category_type){
154     $template->{VARS}->{'type_only'} = 1;
155 }
156 my $new_c_type = $category_type; #if we have input param, then we've already chosen the cat_type.
157 unless ($category_type or !($categorycode)){
158     my $borrowercategory = GetBorrowercategory($categorycode);
159     $category_type    = $borrowercategory->{'category_type'};
160     my $category_name = $borrowercategory->{'description'}; 
161     $template->param("categoryname"=>$category_name);
162  }
163 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
164
165 # if a add or modify is requested => check validity of data.
166 %data = %$borrower_data if ($borrower_data);
167
168 # initialize %newdata
169 my %newdata;                                                                             # comes from $input->param()
170 if ( $op eq 'insert' || $op eq 'modify' || $op eq 'save' || $op eq 'duplicate' ) {
171     my @names = ( $borrower_data && $op ne 'save' ) ? keys %$borrower_data : $input->param();
172     foreach my $key (@names) {
173         if (defined $input->param($key)) {
174             $newdata{$key} = $input->param($key);
175             $newdata{$key} =~ s/\"/"/g unless $key eq 'borrowernotes' or $key eq 'opacnote';
176         }
177     }
178
179     my $dateobject = C4::Dates->new();
180     my $syspref = $dateobject->regexp();                # same syspref format for all 3 dates
181     my $iso     = $dateobject->regexp('iso');   #
182     foreach (qw(dateenrolled dateexpiry dateofbirth)) {
183         next unless exists $newdata{$_};
184         my $userdate = $newdata{$_} or next;
185         if ($userdate =~ /$syspref/) {
186             $newdata{$_} = format_date_in_iso($userdate);       # if they match syspref format, then convert to ISO
187         } elsif ($userdate =~ /$iso/) {
188             warn "Date $_ ($userdate) is already in ISO format";
189         } else {
190             ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
191             $template->param( "ERROR_$_" => 1 );        # else ERROR!
192             push(@errors,"ERROR_$_");
193         }
194     }
195   # check permission to modify login info.
196     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($userenv->{'id'},{'staffaccess'=>1})) )  {
197         $NoUpdateLogin = 1;
198     }
199 }
200
201 # remove keys from %newdata that ModMember() doesn't like
202 {
203     my @keys_to_delete = (
204         qr/^BorrowerMandatoryField$/,
205         qr/^category_type$/,
206         qr/^check_member$/,
207         qr/^destination$/,
208         qr/^nodouble$/,
209         qr/^op$/,
210         qr/^save$/,
211         qr/^updtype$/,
212         qr/^SMSnumber$/,
213         qr/^setting_extended_patron_attributes$/,
214         qr/^setting_messaging_prefs$/,
215         qr/^digest$/,
216         qr/^modify$/,
217         qr/^step$/,
218         qr/^\d+$/,
219         qr/^\d+-DAYS/,
220         qr/^patron_attr_/,
221     );
222     for my $regexp (@keys_to_delete) {
223         for (keys %newdata) {
224             delete($newdata{$_}) if /$regexp/;
225         }
226     }
227 }
228
229 #############test for member being unique #############
230 if ( ( $op eq 'insert' ) and !$nodouble ) {
231     my $category_type_send;
232     if ( $category_type eq 'I' ) {
233         $category_type_send = $category_type;
234     }
235     my $check_category;    # recover the category code of the doublon suspect borrowers
236      #   ($result,$categorycode) = checkuniquemember($collectivity,$surname,$firstname,$dateofbirth)
237     ( $check_member, $check_category ) = checkuniquemember(
238         $category_type_send,
239         ( $newdata{surname}     ? $newdata{surname}     : $data{surname} ),
240         ( $newdata{firstname}   ? $newdata{firstname}   : $data{firstname} ),
241         ( $newdata{dateofbirth} ? $newdata{dateofbirth} : $data{dateofbirth} )
242     );
243     if ( !$check_member ) {
244         $nodouble = 1;
245     }
246
247     #   recover the category type if the borrowers is a doublon
248     if ($check_category) {
249         my $tmpborrowercategory = GetBorrowercategory($check_category);
250         $check_categorytype = $tmpborrowercategory->{'category_type'};
251     }
252 }
253
254   #recover all data from guarantor address phone ,fax... 
255 if ( $guarantorid and ( $category_type eq 'C' || $category_type eq 'P' )) {
256     if (my $guarantordata=GetMember(borrowernumber => $guarantorid)) {
257         $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
258         $newdata{'contactfirstname'}= $guarantordata->{'firstname'};
259         $newdata{'contactname'}     = $guarantordata->{'surname'};
260         $newdata{'contacttitle'}    = $guarantordata->{'title'};
261         if ( $op eq 'add' ) {
262                 foreach (qw(streetnumber address streettype address2
263                         zipcode country city state phone phonepro mobile fax email emailpro branchcode
264                         B_streetnumber B_streettype B_address B_address2
265                         B_city B_state B_zipcode B_country B_email B_phone)) {
266                         $newdata{$_} = $guarantordata->{$_};
267                 }
268         }
269     }
270 }
271
272 ###############test to take the right zipcode, country and city name ##############
273 # set only if parameter was passed from the form
274 $newdata{'city'}    = $input->param('city')    if defined($input->param('city'));
275 $newdata{'zipcode'} = $input->param('zipcode') if defined($input->param('zipcode'));
276 $newdata{'country'} = $input->param('country') if defined($input->param('country'));
277
278 #builds default userid
279 if ( (defined $newdata{'userid'}) && ($newdata{'userid'} eq '')){
280     if ( ( defined $newdata{'firstname'} ) && ( defined $newdata{'surname'} ) ) {
281         # Full page edit, firstname and surname input zones are present
282         $newdata{'userid'} = Generate_Userid( $borrowernumber, $newdata{'firstname'}, $newdata{'surname'} );
283     }
284     elsif ( ( defined $data{'firstname'} ) && ( defined $data{'surname'} ) ) {
285         # Partial page edit (access through "Details"/"Library details" tab), firstname and surname input zones are not used
286         # Still, if the userid field is erased, we can create a new userid with available firstname and surname
287         $newdata{'userid'} = Generate_Userid( $borrowernumber, $data{'firstname'}, $data{'surname'} );
288     }
289     else {
290         $newdata{'userid'} = $data{'userid'};
291     }
292 }
293   
294 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
295 my $extended_patron_attributes = ();
296 if ($op eq 'save' || $op eq 'insert'){
297     # If the cardnumber is blank, treat it as null.
298     $newdata{'cardnumber'} = undef if $newdata{'cardnumber'} =~ /^\s*$/;
299
300     if (my $error_code = checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){
301         push @errors, $error_code == 1
302             ? 'ERROR_cardnumber_already_exists'
303             : $error_code == 2
304                 ? 'ERROR_cardnumber_length'
305                 : ()
306     }
307
308     if ($newdata{dateofbirth} && $dateofbirthmandatory) {
309         my $age = GetAge($newdata{dateofbirth});
310         my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});   
311         my ($low,$high) = ($borrowercategory->{'dateofbirthrequired'}, $borrowercategory->{'upperagelimit'});
312         if (($high && ($age > $high)) or ($age < $low)) {
313             push @errors, 'ERROR_age_limitations';
314             $template->param( age_low => $low);
315             $template->param( age_high => $high);
316         }
317     }
318   
319     if($newdata{surname} && C4::Context->preference('uppercasesurnames')) {
320         $newdata{'surname'} = uc($newdata{'surname'});
321     }
322
323   if (C4::Context->preference("IndependentBranches")) {
324     unless ( C4::Context->IsSuperLibrarian() ){
325       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
326       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
327         push @errors, "ERROR_branch";
328       }
329     }
330   }
331   # Check if the userid is unique
332   unless (Check_Userid($newdata{'userid'},$borrowernumber)) {
333     push @errors, "ERROR_login_exist";
334   }
335   
336   my $password = $input->param('password');
337   my $password2 = $input->param('password2');
338   push @errors, "ERROR_password_mismatch" if ( $password ne $password2 );
339   push @errors, "ERROR_short_password" if( $password && $minpw && $password ne '****' && (length($password) < $minpw) );
340
341   if (C4::Context->preference('ExtendedPatronAttributes')) {
342     $extended_patron_attributes = parse_extended_patron_attributes($input);
343     foreach my $attr (@$extended_patron_attributes) {
344         unless (C4::Members::Attributes::CheckUniqueness($attr->{code}, $attr->{value}, $borrowernumber)) {
345             my $attr_info = C4::Members::AttributeTypes->fetch($attr->{code});
346             push @errors, "ERROR_extended_unique_id_failed";
347             $template->param(
348                 ERROR_extended_unique_id_failed_code => $attr->{code},
349                 ERROR_extended_unique_id_failed_value => $attr->{value},
350                 ERROR_extended_unique_id_failed_description => $attr_info->description()
351             );
352         }
353     }
354   }
355 }
356
357 if ( ($op eq 'modify' || $op eq 'insert' || $op eq 'save'|| $op eq 'duplicate') and ($step == 0 or $step == 3 )){
358     unless ($newdata{'dateexpiry'}){
359         my $arg2 = $newdata{'dateenrolled'} || C4::Dates->today('iso');
360         $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
361     }
362 }
363
364 if (
365         defined $input->param('SMSnumber')
366     &&  (
367            $input->param('SMSnumber') eq ""
368         or $input->param('SMSnumber') ne $newdata{'mobile'}
369         )
370 ) {
371     $newdata{smsalertnumber} = $input->param('SMSnumber');
372 }
373
374 ###  Error checks should happen before this line.
375 $nok = $nok || scalar(@errors);
376 if ((!$nok) and $nodouble and ($op eq 'insert' or $op eq 'save')){
377         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
378         if ($op eq 'insert'){
379                 # we know it's not a duplicate borrowernumber or there would already be an error
380         $borrowernumber = &AddMember(%newdata);
381         $newdata{'borrowernumber'} = $borrowernumber;
382
383         # If 'AutoEmailOpacUser' syspref is on, email user their account details from the 'notice' that matches the user's branchcode.
384         if ( C4::Context->preference("AutoEmailOpacUser") == 1 && $newdata{'userid'}  && $newdata{'password'}) {
385             #look for defined primary email address, if blank - attempt to use borr.email and borr.emailpro instead
386             my $emailaddr;
387             if  (C4::Context->preference("AutoEmailPrimaryAddress") ne 'OFF'  && 
388                 $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} =~  /\w\@\w/ ) {
389                 $emailaddr =   $newdata{C4::Context->preference("AutoEmailPrimaryAddress")} 
390             } 
391             elsif ($newdata{email} =~ /\w\@\w/) {
392                 $emailaddr = $newdata{email} 
393             }
394             elsif ($newdata{emailpro} =~ /\w\@\w/) {
395                 $emailaddr = $newdata{emailpro} 
396             }
397             elsif ($newdata{B_email} =~ /\w\@\w/) {
398                 $emailaddr = $newdata{B_email} 
399             }
400             # if we manage to find a valid email address, send notice 
401             if ($emailaddr) {
402                 $newdata{emailaddr} = $emailaddr;
403                 my $err;
404                 eval {
405                     $err = SendAlerts ( 'members', \%newdata, "ACCTDETAILS" );
406                 };
407                 if ( $@ ) {
408                     $template->param(error_alert => $@);
409                 } elsif ( ref($err) eq "HASH" && defined $err->{error} and $err->{error} eq "no_email" ) {
410                     $template->{VARS}->{'error_alert'} = "no_email";
411                 } else {
412                     $template->{VARS}->{'info_alert'} = 1;
413                 }
414             }
415         }
416
417         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
418             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
419         }
420         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
421             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template, 1, $newdata{'categorycode'});
422         }
423         # Try to do the live sync with the Norwegian national patron database, if it is enabled
424         if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
425             NLSync({ 'borrowernumber' => $borrowernumber });
426         }
427         } elsif ($op eq 'save'){ 
428                 if ($NoUpdateLogin) {
429                         delete $newdata{'password'};
430                         delete $newdata{'userid'};
431                 }
432         &ModMember(%newdata) unless scalar(keys %newdata) <= 1; # bug 4508 - avoid crash if we're not
433                                                                 # updating any columns in the borrowers table,
434                                                                 # which can happen if we're only editing the
435                                                                 # patron attributes or messaging preferences sections
436         if (C4::Context->preference('ExtendedPatronAttributes') and $input->param('setting_extended_patron_attributes')) {
437             C4::Members::Attributes::SetBorrowerAttributes($borrowernumber, $extended_patron_attributes);
438         }
439         if (C4::Context->preference('EnhancedMessagingPreferences') and $input->param('setting_messaging_prefs')) {
440             C4::Form::MessagingPreferences::handle_form_action($input, { borrowernumber => $borrowernumber }, $template);
441         }
442         }
443         print scalar ($destination eq "circ") ? 
444                 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
445                 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
446         exit;           # You can only send 1 redirect!  After that, content or other headers don't matter.
447 }
448
449 if ($delete){
450         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
451         exit;           # same as above
452 }
453
454 if ($nok or !$nodouble){
455     $op="add" if ($op eq "insert");
456     $op="modify" if ($op eq "save");
457     %data=%newdata; 
458     $template->param( updtype => ($op eq 'add' ?'I':'M'));      # used to check for $op eq "insert"... but we just changed $op!
459     unless ($step){  
460         $template->param( step_1 => 1,step_2 => 1,step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1);
461     }  
462
463 if (C4::Context->preference("IndependentBranches")) {
464     my $userenv = C4::Context->userenv;
465     if ( !C4::Context->IsSuperLibrarian() && $data{'branchcode'} ) {
466         unless ($userenv->{branch} eq $data{'branchcode'}){
467             print $input->redirect("/cgi-bin/koha/members/members-home.pl");
468             exit;
469         }
470     }
471 }
472 if ($op eq 'add'){
473     $template->param( updtype => 'I', step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1);
474 }
475 if ($op eq "modify")  {
476     $template->param( updtype => 'M',modify => 1 );
477     $template->param( step_1=>1, step_2=>1, step_3=>1, step_4=>1, step_5 => 1, step_6 => 1) unless $step;
478     if ( $step == 4 ) {
479         $template->param( categorycode => $borrower_data->{'categorycode'} );
480     }
481     # Add sync data to the user data
482     if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
483         my $sync = NLGetSyncDataFromBorrowernumber( $borrowernumber );
484         if ( $sync ) {
485             $template->param(
486                 sync => $sync->sync,
487             );
488         }
489     }
490 }
491 if ( $op eq "duplicate" ) {
492     $template->param( updtype => 'I' );
493     $template->param( step_1 => 1, step_2 => 1, step_3 => 1, step_4 => 1, step_5 => 1, step_6 => 1 ) unless $step;
494     $data{'cardnumber'} = "";
495 }
496
497 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if ( ( $op eq 'add' ) or ( $op eq 'duplicate' ) );
498 if(!defined($data{'sex'})){
499     $template->param( none => 1);
500 } elsif($data{'sex'} eq 'F'){
501     $template->param( female => 1);
502 } elsif ($data{'sex'} eq 'M'){
503     $template->param(  male => 1);
504 } else {
505     $template->param(  none => 1);
506 }
507
508 ##Now all the data to modify a member.
509 my ($categories,$labels)=ethnicitycategories();
510   
511 my $ethnicitycategoriescount=$#{$categories};
512 my $ethcatpopup;
513 if ($ethnicitycategoriescount>=0) {
514   $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
515         -id => 'ethnicity',
516         -tabindex=>'',
517         -values=>$categories,
518         -default=>$data{'ethnicity'},
519         -labels=>$labels);
520   $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
521 }
522
523 my @typeloop;
524 my $no_categories = 1;
525 my $no_add;
526 foreach (qw(C A S P I X)) {
527     my $action="WHERE category_type=?";
528         ($categories,$labels)=GetborCatFromCatType($_,$action);
529     if(scalar(@$categories) > 0){ $no_categories = 0; }
530         my @categoryloop;
531         foreach my $cat (@$categories){
532                 push @categoryloop,{'categorycode' => $cat,
533                           'categoryname' => $labels->{$cat},
534                           'categorycodeselected' => ((defined($borrower_data->{'categorycode'}) && 
535                                                      $cat eq $borrower_data->{'categorycode'}) 
536                                                      || (defined($categorycode) && $cat eq $categorycode)),
537                 };
538         }
539         my %typehash;
540         $typehash{'typename'}=$_;
541     my $typedescription = "typename_".$typehash{'typename'};
542         $typehash{'categoryloop'}=\@categoryloop;
543         push @typeloop,{'typename' => $_,
544         $typedescription => 1,
545           'categoryloop' => \@categoryloop};
546 }
547 $template->param('typeloop' => \@typeloop,
548         no_categories => $no_categories);
549 if($no_categories){ $no_add = 1; }
550 # test in city
551 if ( $guarantorid ) {
552     $select_city = getidcity($data{city});
553 }
554 ($default_city=$select_city) if ($step eq 0);
555 if (!defined($select_city) or $select_city eq '' ){
556         $default_city = &getidcity($data{'city'});
557 }
558
559 my $city_arrayref = GetCities();
560 if (@{$city_arrayref} ) {
561     $template->param( city_cgipopup => 1);
562
563     if ($default_city) { # flag the current or default val
564         for my $city ( @{$city_arrayref} ) {
565             if ($default_city == $city->{cityid}) {
566                 $city->{selected} = 1;
567                 last;
568             }
569         }
570     }
571 }
572   
573 my $roadtypes = C4::Koha::GetAuthorisedValues( 'ROADTYPE', $data{streettype} );
574 $template->param( roadtypes => $roadtypes);
575
576 my $default_borrowertitle = '';
577 unless ( $op eq 'duplicate' ) { $default_borrowertitle=$data{'title'} }
578 my($borrowertitle)=GetTitles();
579 $template->param( title_cgipopup => 1) if ($borrowertitle);
580 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
581         -id => 'btitle',
582         -values=>$borrowertitle,
583         -override => 1,
584         -default=>$default_borrowertitle
585         );    
586
587 my @relationships = split /,|\|/, C4::Context->preference('borrowerRelationship');
588 my @relshipdata;
589 while (@relationships) {
590   my $relship = shift @relationships || '';
591   my %row = ('relationship' => $relship);
592   if (defined($data{'relationship'}) and $data{'relationship'} eq $relship) {
593     $row{'selected'}=' selected';
594   } else {
595     $row{'selected'}='';
596   }
597   push(@relshipdata, \%row);
598 }
599
600 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
601         'lost'          => ['lost']);
602
603  
604 my @flagdata;
605 foreach (keys(%flags)) {
606         my $key = $_;
607         my %row =  ('key'   => $key,
608                     'name'  => $flags{$key}[0]);
609         if ($data{$key}) {
610                 $row{'yes'}=' checked';
611                 $row{'no'}='';
612     }
613         else {
614                 $row{'yes'}='';
615                 $row{'no'}=' checked';
616         }
617         push @flagdata,\%row;
618 }
619
620 # get Branch Loop
621 # in modify mod: userbranch value for GetBranchesLoop() comes from borrowers table
622 # in add    mod: userbranch value come from branches table (ip correspondence)
623
624 my $userbranch = '';
625 if (C4::Context->userenv && C4::Context->userenv->{'branch'}) {
626     $userbranch = C4::Context->userenv->{'branch'};
627 }
628
629 if (defined ($data{'branchcode'}) and ( $op eq 'modify' || $op eq 'duplicate' || ( $op eq 'add' && $category_type eq 'C' ) )) {
630     $userbranch = $data{'branchcode'};
631 }
632
633 my $branchloop = GetBranchesLoop( $userbranch );
634
635 if( !$branchloop ){
636     $no_add = 1;
637     $template->param(no_branches => 1);
638 }
639 if($no_categories){
640     $no_add = 1;
641     $template->param(no_categories => 1);
642 }
643 $template->param(no_add => $no_add);
644 # --------------------------------------------------------------------------------------------------------
645
646 $template->param( sort1 => $data{'sort1'});
647 $template->param( sort2 => $data{'sort2'});
648
649 if ($nok) {
650     foreach my $error (@errors) {
651         $template->param($error) || $template->param( $error => 1);
652     }
653     $template->param(nok => 1);
654 }
655   
656   #Formatting data for display    
657   
658 if (!defined($data{'dateenrolled'}) or $data{'dateenrolled'} eq ''){
659   $data{'dateenrolled'}=C4::Dates->today('iso');
660 }
661 if ( $op eq 'duplicate' ) {
662     $data{'dateenrolled'} = C4::Dates->today('iso');
663     $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, $data{'dateenrolled'} );
664 }
665 if (C4::Context->preference('uppercasesurnames')) {
666     $data{'surname'} &&= uc( $data{'surname'} );
667     $data{'contactname'} &&= uc( $data{'contactname'} );
668 }
669
670 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
671         $data{$_} = format_date($data{$_});     # back to syspref for display
672         $template->param( $_ => $data{$_});
673 }
674
675 if (C4::Context->preference('ExtendedPatronAttributes')) {
676     $template->param(ExtendedPatronAttributes => 1);
677     patron_attributes_form($template, $borrowernumber);
678 }
679
680 if (C4::Context->preference('EnhancedMessagingPreferences')) {
681     if ($op eq 'add') {
682         C4::Form::MessagingPreferences::set_form_values({ categorycode => $categorycode }, $template);
683     } else {
684         C4::Form::MessagingPreferences::set_form_values({ borrowernumber => $borrowernumber }, $template);
685     }
686     $template->param(SMSSendDriver => C4::Context->preference("SMSSendDriver"));
687     $template->param(SMSnumber     => defined $data{'smsalertnumber'} ? $data{'smsalertnumber'} : $data{'mobile'});
688     $template->param(TalkingTechItivaPhone => C4::Context->preference("TalkingTechItivaPhoneNotification"));
689 }
690
691 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
692 $debug and warn "memberentry step: $step";
693 $template->param(%data);
694 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
695 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
696
697 $template->param(
698   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
699   category_type => $category_type,#to know the category type of the borrower
700   select_city => $select_city,
701   "$category_type"  => 1,# associate with step to know where u are
702   destination   => $destination,#to know wher u come from and wher u must go in redirect
703   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
704   "op$op"   => 1);
705
706 $template->param( branchloop => $branchloop ) if ( $branchloop );
707 $template->param(
708   nodouble  => $nodouble,
709   borrowernumber  => $borrowernumber, #register number
710   guarantorid => ($borrower_data->{'guarantorid'} || $guarantorid),
711   ethcatpopup => $ethcatpopup,
712   relshiploop => \@relshipdata,
713   city_loop => $city_arrayref,
714   borrotitlepopup => $borrotitlepopup,
715   guarantorinfo   => $guarantorinfo,
716   flagloop  => \@flagdata,
717   check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
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: