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