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