Fix for 1699, cant change category type
[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 with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 # pragma
21 use strict;
22
23 # external modules
24 use Date::Calc qw/Today/;
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::Koha;
34 use C4::Dates qw/format_date format_date_in_iso/;
35 use C4::Input;
36 use C4::Log;
37 use C4::Branch; # GetBranches
38
39 use vars qw($debug);
40
41 BEGIN {
42         $debug = $ENV{DEBUG} || 0;
43 }
44         
45 my $input = new CGI;
46 ($debug) or $debug = $input->param('debug') || 0;
47 my %data;
48
49 my $dbh = C4::Context->dbh;
50
51 my ($template, $loggedinuser, $cookie)
52     = get_template_and_user({template_name => "members/memberentrygen.tmpl",
53            query => $input,
54            type => "intranet",
55            authnotrequired => 0,
56            flagsrequired => {borrowers => 1},
57            debug => ($debug) ? 1 : 0,
58            });
59 my $guarantorid=$input->param('guarantorid');
60 my $borrowernumber=$input->param('borrowernumber');
61 my $actionType=$input->param('actionType') || '';
62 my $modify=$input->param('modify');
63 my $delete=$input->param('delete');
64 my $op=$input->param('op');
65 my $destination=$input->param('destination');
66 my $cardnumber=$input->param('cardnumber');
67 my $check_member=$input->param('check_member');
68 my $name_city=$input->param('name_city');
69 my $nodouble=$input->param('nodouble');
70 my $select_city=$input->param('select_city');
71 my $nok=$input->param('nok');
72 my $guarantorinfo=$input->param('guarantorinfo');
73 my $step=$input->param('step') || 0;
74 my @errors;
75 my $default_city;
76 # $check_categorytype contains the value of duplicate borrowers category type to redirect in good template in step =2
77 my $check_categorytype=$input->param('check_categorytype');
78 # NOTE: Alert for ethnicity and ethnotes fields, they are invalid in all borrowers form
79 my $borrower_data;
80 my $NoUpdateLogin;
81 my $userenv = C4::Context->userenv;
82
83 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
84
85 # function to designate mandatory fields (visually with css)
86 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
87 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
88 foreach (@field_check) {
89         $template->param( "mandatory$_" => 1);    
90 }
91 $template->param("add"=>1) if ($op eq 'add');
92 $template->param("checked" => 1) if ($nodouble eq 1);
93 ($borrower_data = GetMember($borrowernumber,'borrowernumber')) if ($op eq 'modify' or $op eq 'save');
94 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
95 my $category_type = $input->param('category_type');
96 unless ($category_type or !($categorycode)){
97   my $borrowercategory= GetBorrowercategory($categorycode);
98   $category_type = $borrowercategory->{'category_type'};
99 }
100 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
101
102 # if a add or modify is requested => check validity of data.
103 %data = %$borrower_data if ($borrower_data);
104
105 my %newdata;    # comes from $input->param()
106 if ($op eq 'insert' || $op eq 'modify' || $op eq 'save') {
107     my @names= ($borrower_data && $op ne 'save') ? keys %$borrower_data : $input->param();
108     foreach my $key (@names) {
109         $newdata{$key} = $input->param($key) if (defined $input->param($key));
110         $newdata{$key} =~ s/\"/"/gg unless $key eq 'borrowernotes' or $key eq 'opacnote';
111     }
112         my $dateobject = C4::Dates->new();
113         my $syspref = $dateobject->regexp();            # same syspref format for all 3 dates
114         my $iso     = $dateobject->regexp('iso');       # 
115         foreach (qw(dateenrolled dateexpiry dateofbirth)) {
116                 my $userdate = $newdata{$_} or next;
117                 if ($userdate =~ /$syspref/) {
118                         $newdata{$_} = format_date_in_iso($userdate);   # if they match syspref format, then convert to ISO
119                 } elsif ($userdate =~ /$iso/) {
120                         warn "Date $_ ($userdate) is already in ISO format";
121                 } else {
122                         ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
123                         $template->param( "ERROR_$_" => 1 );    # else ERROR!
124                         push(@errors,"ERROR_$_");
125                 }
126         }
127   # check permission to modify login info.
128     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($dbh,$userenv->{'id'},{'staffaccess'=>1})) )  {
129                 $NoUpdateLogin =1;
130         }
131 }
132
133 #############test for member being unique #############
134 if ($op eq 'insert'){
135         my $category_type_send=$category_type if ($category_type eq 'I'); 
136         my $check_category; # recover the category code of the doublon suspect borrowers
137                         #   ($result,$categorycode) = checkuniquemember($collectivity,$surname,$firstname,$dateofbirth)
138         ($check_member,$check_category) = checkuniquemember(
139                         $category_type_send, 
140                         ($newdata{surname}     ? $newdata{surname}     : $data{surname}    ),
141                         ($newdata{firstname}   ? $newdata{firstname}   : $data{firstname}  ),
142                         ($newdata{dateofbirth} ? $newdata{dateofbirth} : $data{dateofbirth})
143                 );
144           
145   #   recover the category type if the borrowers is a doublon 
146         my $tmpborrowercategory=GetBorrowercategory($check_category);
147         $check_categorytype=$tmpborrowercategory->{'category_type'};
148 }
149
150   #recover all data from guarantor address phone ,fax... 
151 if (($category_type eq 'C' || $category_type eq 'P') and $guarantorid ne '' ){
152   my $guarantordata=GetMember($guarantorid);
153   $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
154   if (($data{'contactname'} eq '' or $data{'contactname'} ne $guarantordata->{'surname'})) {
155     $data{'contactfirstname'}= $guarantordata->{'firstname'}; 
156     $data{'contactname'}     = $guarantordata->{'surname'};
157     $data{'contacttitle'}    = $guarantordata->{'title'};  
158         foreach (qw(streetnumber address streettype address2 zipcode city phone phonepro mobile fax email emailpro)) {
159                 $data{$_} = $guarantordata->{$_};
160         }
161   }
162 }
163
164 ###############test to take the right zipcode and city name ##############
165 if ( $guarantorid eq ''){
166   if ($select_city){
167     my ($borrower_city,$borrower_zipcode)=&getzipnamecity($select_city);
168     $newdata{'city'}= $borrower_city;
169     $newdata{'zipcode'}=$borrower_zipcode;
170     }
171 }
172 #builds default userid
173 if ( (defined $newdata{'userid'}) && ($newdata{'userid'} eq '')){
174   my $onefirstnameletter = substr($data{'firstname'},0,1);
175   my  $fivesurnameletter = substr($data{'surname'},0,9);
176   $newdata{'userid'}=lc($onefirstnameletter.$fivesurnameletter);
177 }
178   
179 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
180 my $loginexist=0;
181 if ($op eq 'save' || $op eq 'insert'){
182   if (checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){ 
183     push @errors, 'ERROR_cardnumber';
184   } 
185   my $dateofbirthmandatory = (scalar grep {$_ eq "dateofbirth"} @field_check) ? 1 : 0;
186   if ($newdata{dateofbirth} && $dateofbirthmandatory) {
187     my $age = GetAge($newdata{dateofbirth});
188     my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});   
189         my ($low,$high) = ($borrowercategory->{'dateofbirthrequired'}, $borrowercategory->{'upperagelimit'});
190     if (($age > $high) or ($age < $low)) {
191       push @errors, 'ERROR_age_limitations';
192           $template->param('ERROR_age_limitations' => "$low to $high");
193     }
194   }
195   if (C4::Context->preference("IndependantBranches")) {
196     if ($userenv && $userenv->{flags} != 1){
197       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
198       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
199         push @errors, "ERROR_branch";
200       }
201     }
202   }
203   # Check if the userid is unique
204   unless (Check_Userid($newdata{'userid'},$borrowernumber)) {
205     push @errors, "ERROR_login_exist";
206     $loginexist=1; 
207   }
208 }
209
210 if ($op eq 'modify' || $op eq 'insert'){
211   unless ($newdata{'dateexpiry'}){
212         my $arg2 = $newdata{'dateenrolled'} || sprintf('%04d-%02d-%02d', Today());
213     $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
214   }
215 }
216
217 ###  Error checks should happen before this line.
218
219 $nok = $nok || scalar(@errors);
220 if ((!$nok) and ($op eq 'insert' or $op eq 'save')){
221         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
222         if ($op eq 'insert'){
223                 # we know it's not a duplicate borrowernumber or there would already be an error
224                 $borrowernumber = &AddMember(%newdata);
225                 if ($data{'organisations'}){            
226                         # need to add the members organisations
227                         my @orgs=split(/\|/,$data{'organisations'});
228                         add_member_orgs($borrowernumber,\@orgs);
229                 }
230         } elsif ($op eq 'save'){ 
231                 if ($NoUpdateLogin) {
232                         delete $newdata{'password'};
233                         delete $newdata{'userid'};
234                 }
235                 &ModMember(%newdata);   # this is the last server-changing line.  the rest is "presentation"
236         }
237         print scalar ($destination eq "circ") ? 
238                 $input->redirect("/cgi-bin/koha/circ/circulation.pl?findborrower=$data{'cardnumber'}") :
239                 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
240         exit;           # You can only send 1 redirect!  After that, content or other headers don't matter.
241 }
242
243 if ($delete){
244         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
245         exit;           # same as above
246 }
247
248 if ($nok){
249   $op="add" if ($op eq "insert");
250   $op="modify" if ($op eq "save");
251   %data=%newdata; 
252   $template->param( updtype => ($op eq 'add' ?'I':'M'));        # used to check for $op eq "insert"... but we just changed $op!
253   unless ($step){  
254     $template->param( step_1 => 1,step_2 => 1,step_3 => 1);
255   }  
256
257 if (C4::Context->preference("IndependantBranches")) {
258   my $userenv = C4::Context->userenv;
259   if ($userenv->{flags} != 1 && $data{branchcode}){
260     unless ($userenv->{branch} eq $data{'branchcode'}){
261       print $input->redirect("/cgi-bin/koha/members/members-home.pl");
262           exit;
263     }
264   }
265 }
266 if ($op eq 'add'){
267   $template->param( updtype => 'I',step_1=>1,step_2=>1,step_3=>1);
268
269 if ($op eq "modify")  {
270   $template->param( updtype => 'M',modify => 1 );
271   $template->param( step_1=>1,step_2=>1,step_3=>1) unless $step;
272 }
273 # my $cardnumber=$data{'cardnumber'};
274 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if $op eq 'add';
275 if ($data{'sex'} eq 'F'){
276   $template->param(female => 1);
277 } elsif ($data{'sex'} eq 'M'){
278     $template->param(male => 1);
279 } else {
280     $template->param(none => 1);
281 }
282
283 ##Now all the data to modify a member.
284 my ($categories,$labels)=ethnicitycategories();
285   
286 my $ethnicitycategoriescount=$#{$categories};
287 my $ethcatpopup;
288 if ($ethnicitycategoriescount>=0) {
289   $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
290         -id => 'ethnicity',
291         -tabindex=>'',
292         -values=>$categories,
293         -default=>$data{'ethnicity'},
294         -labels=>$labels);
295   $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
296 }
297
298 my @typeloop;
299 foreach (qw(C A S P I)){
300         my $action="WHERE category_type=?";
301         ($categories,$labels)=GetborCatFromCatType($_,$action);
302         my @categoryloop;
303         foreach my $cat (@$categories){
304                 push @categoryloop,{'categorycode' => $cat,
305                           'categoryname' => $labels->{$cat},
306                           'categorycodeselected' => ($cat eq $borrower_data->{'categorycode'}),
307                 };
308         }
309         my %typehash;
310         $typehash{'typename'}=$_;
311         $typehash{'categoryloop'}=\@categoryloop;
312         push @typeloop,{'typename' => $_,
313           'categoryloop' => \@categoryloop};
314 }  
315 $template->param('typeloop' => \@typeloop);
316
317 # test in city
318 $select_city=getidcity($data{'city'}) if ($guarantorid ne '0');
319 ($default_city=$select_city) if ($step eq 0);
320 if ($select_city eq '' ){
321         $default_city = &getidcity($data{'city'});
322 }
323 my($cityid);
324 ($cityid,$name_city)=GetCities();
325 $template->param( city_cgipopup => 1) if ($cityid );
326 my $citypopup = CGI::popup_menu(-name=>'select_city',
327         -id => 'select_city',
328         -values=>$name_city,
329         -labels=>$name_city,
330         -default=>$default_city,
331         );  
332   
333 my $default_roadtype;
334 $default_roadtype=$data{'streettype'} ;
335 my($roadtypeid,$road_type)=GetRoadTypes();
336   $template->param( road_cgipopup => 1) if ($roadtypeid );
337 my $roadpopup = CGI::popup_menu(-name=>'streettype',
338         -id => 'streettype',
339         -values=>$roadtypeid,
340         -labels=>$road_type,
341         -override => 1,
342         -default=>$default_roadtype
343         );  
344
345 my $default_borrowertitle;
346 $default_borrowertitle=$data{'title'} ;
347 my($borrowertitle)=GetTitles();
348 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
349         -id => 'btitle',
350         -values=>$borrowertitle,
351         -override => 1,
352         -default=>$default_borrowertitle
353         );    
354
355 my @relationships = split /,|\|/,C4::Context->preference('BorrowerRelationship');
356 my @relshipdata;
357 while (@relationships) {
358   my $relship = shift @relationships || '';
359   my %row = ('relationship' => $relship);
360   if ($data{'relationship'} eq $relship) {
361     $row{'selected'}=' selected';
362   } else {
363     $row{'selected'}='';
364   }
365   push(@relshipdata, \%row);
366 }
367 my %flags = ( 'gonenoaddress' => ['gonenoaddress', 'Gone no address '],
368         'lost'          => ['lost', 'Lost'],
369         'debarred'      => ['debarred', 'Debarred']);
370
371 my @flagdata;
372 foreach (keys(%flags)) {
373 my $key = $_;
374 my %row =  ('key'   => $key,
375     'name'  => $flags{$key}[0],
376     'html'  => $flags{$key}[1]);
377 if ($data{$key}) {
378   $row{'yes'}=' checked';
379   $row{'no'}='';
380 } else {
381   $row{'yes'}='';
382   $row{'no'}=' checked';
383 }
384 push(@flagdata, \%row);
385 }
386
387
388 #get Branches
389 my @branches;
390 my @select_branch;
391 my %select_branches;
392
393 my $onlymine=(C4::Context->preference('IndependantBranches') && 
394               C4::Context->userenv && 
395               C4::Context->userenv->{flags} !=1  && 
396               C4::Context->userenv->{branch}?1:0);
397               
398 my $branches=GetBranches($onlymine);
399 my $default;
400
401 foreach my $branch (sort keys %$branches) {
402     push @select_branch,$branch;
403     $select_branches{$branch} = $branches->{$branch}->{'branchname'};
404     $default = C4::Context->userenv->{'branch'} if (C4::Context->userenv && C4::Context->userenv->{'branch'});
405 }
406 # --------------------------------------------------------------------------------------------------------
407   #in modify mod :default value from $CGIbranch comes from borrowers table
408   #in add mod: default value come from branches table (ip correspendence)
409 $default=$data{'branchcode'}  if ($op eq 'modify');
410 my $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
411             -name   => 'branchcode',
412             -values => \@select_branch,
413             -labels => \%select_branches,
414             -size   => 1,
415             -override => 1,  
416             -multiple =>0,
417             -default => $default,
418         );
419 my $CGIorganisations;
420 my $member_of_institution;
421 if (C4::Context->preference("memberofinstitution")){
422     my $organisations=get_institutions();
423     my @orgs;
424     my %org_labels;
425     foreach my $organisation (keys %$organisations) {
426         push @orgs,$organisation;
427         $org_labels{$organisation}=$organisations->{$organisation}->{'surname'};
428     }
429     $member_of_institution=1;
430     
431     $CGIorganisations = CGI::scrolling_list( -id => 'organisations',
432         -name     => 'organisations',
433         -labels   => \%org_labels,
434         -values   => \@orgs,
435         -size     => 5,
436         -multiple => 'true'
437
438     );
439 }
440
441
442 # --------------------------------------------------------------------------------------------------------
443
444 my $CGIsort = buildCGIsort("Bsort1","sort1",$data{'sort1'});
445 if ($CGIsort) {
446   $template->param(CGIsort1 => $CGIsort);
447 }
448 $template->param( sort1 => $data{'sort1'});             # shouldn't this be in an "else" statement like the 2nd one?
449
450 $CGIsort = buildCGIsort("Bsort2","sort2",$data{'sort2'});
451 if ($CGIsort) {
452   $template->param(CGIsort2 => $CGIsort);
453 } else {
454   $template->param( sort2 => $data{'sort2'});
455 }
456
457 if ($nok) {
458     foreach my $error (@errors) {
459         $template->param($error) || $template->param( $error => 1);
460     }
461     $template->param(nok => 1);
462 }
463   
464   #Formatting data for display    
465   
466 if ($data{'dateenrolled'} eq ''){
467   my $today = sprintf('%04d-%02d-%02d', Today());       # ISO format
468   $data{'dateenrolled'}=$today;
469 }
470 if (C4::Context->preference('uppercasesurnames')) {
471         $data{'surname'}    =uc($data{'surname'}    );
472         $data{'contactname'}=uc($data{'contactname'});
473 }
474 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
475         $data{$_} = format_date($data{$_});     # back to syspref for display
476         $template->param( $_ => $data{$_});
477 }
478
479 $template->param( "showguarantor"  => ($category_type=~/A|I|S/) ? 0 : 1); # associate with step to know where you are
480 $debug and warn "memberentry step: $step";
481 $template->param(%data);
482 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
483 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
484 $template->param( debug  => $debug  ) if $debug;
485 $template->param(
486   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
487   category_type => $category_type,#to know the category type of the borrower
488   DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
489   select_city => $select_city,
490   "$category_type"  => 1,# associate with step to know where u are
491   destination   => $destination,#to know wher u come from and wher u must go in redirect
492   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
493   flags   =>$data{'flags'},   
494   "op$op"   => 1,
495   nodouble  => $nodouble,
496   borrowernumber  => $borrowernumber,#register number
497   "contacttitle_".$data{'contacttitle'} => "SELECTED" ,
498   guarantorid => $guarantorid,
499   ethcatpopup => $ethcatpopup,
500   relshiploop => \@relshipdata,
501   citypopup => $citypopup,
502   roadpopup => $roadpopup,  
503   borrotitlepopup => $borrotitlepopup,
504   guarantorinfo   => $guarantorinfo,
505   flagloop  => \@flagdata,
506   dateformat      => C4::Dates->new()->visual(),
507   C4::Context->preference('dateformat') => 1,
508   check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
509   modify          => $modify,
510   nok     => $nok,#flag to konw if an error 
511   CGIbranch => $CGIbranch,
512   memberofinstution => $member_of_institution,
513   CGIorganisations => $CGIorganisations,
514   NoUpdateLogin =>  $NoUpdateLogin
515   );
516   
517 output_html_with_http_headers $input, $cookie, $template->output;
518
519 # Local Variables:
520 # tab-width: 8
521 # End: