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