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