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