Fix for bug 1666
[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 branchcode)) {
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 if ($cityid) {
326         warn "hey hey waht the?";
327         }
328 $template->param( city_cgipopup => 1) if ($cityid );
329 my $citypopup = CGI::popup_menu(-name=>'select_city',
330         -id => 'select_city',
331         -values=>$name_city,
332         -labels=>$name_city,
333         -default=>$default_city,
334         );  
335   
336 my $default_roadtype;
337 $default_roadtype=$data{'streettype'} ;
338 my($roadtypeid,$road_type)=GetRoadTypes();
339   $template->param( road_cgipopup => 1) if ($roadtypeid );
340 my $roadpopup = CGI::popup_menu(-name=>'streettype',
341         -id => 'streettype',
342         -values=>$roadtypeid,
343         -labels=>$road_type,
344         -override => 1,
345         -default=>$default_roadtype
346         );  
347
348 my $default_borrowertitle;
349 $default_borrowertitle=$data{'title'} ;
350 my($borrowertitle)=GetTitles();
351 $template->param( title_cgipopup => 1) if ($borrowertitle);
352 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
353         -id => 'btitle',
354         -values=>$borrowertitle,
355         -override => 1,
356         -default=>$default_borrowertitle
357         );    
358
359 my @relationships = split /,|\|/,C4::Context->preference('BorrowerRelationship');
360 my @relshipdata;
361 while (@relationships) {
362   my $relship = shift @relationships || '';
363   my %row = ('relationship' => $relship);
364   if ($data{'relationship'} eq $relship) {
365     $row{'selected'}=' selected';
366   } else {
367     $row{'selected'}='';
368   }
369   push(@relshipdata, \%row);
370 }
371
372 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
373         'lost'          => ['lost'],
374         'debarred'      => ['debarred']);
375
376  
377 my @flagdata;
378 foreach (keys(%flags)) {
379         my $key = $_;
380         my %row =  ('key'   => $key,
381                     'name'  => $flags{$key}[0]);
382         if ($data{$key}) {
383                 $row{'yes'}=' checked';
384                 $row{'no'}='';
385     }
386         else {
387                 $row{'yes'}='';
388                 $row{'no'}=' checked';
389         }
390         push @flagdata,\%row;
391 }
392
393 #get Branches
394 my @branches;
395 my @select_branch;
396 my %select_branches;
397
398 my $onlymine=(C4::Context->preference('IndependantBranches') && 
399               C4::Context->userenv && 
400               C4::Context->userenv->{flags} !=1  && 
401               C4::Context->userenv->{branch}?1:0);
402               
403 my $branches=GetBranches($onlymine);
404 my $default;
405
406 foreach my $branch (sort keys %$branches) {
407     push @select_branch,$branch;
408     $select_branches{$branch} = $branches->{$branch}->{'branchname'};
409     $default = C4::Context->userenv->{'branch'} if (C4::Context->userenv && C4::Context->userenv->{'branch'});
410 }
411 # --------------------------------------------------------------------------------------------------------
412   #in modify mod :default value from $CGIbranch comes from borrowers table
413   #in add mod: default value come from branches table (ip correspendence)
414 $default=$data{'branchcode'}  if ($op eq 'modify' || ($op eq 'add' && $category_type eq 'C'));
415 my $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
416             -name   => 'branchcode',
417             -values => \@select_branch,
418             -labels => \%select_branches,
419             -size   => 1,
420             -override => 1,  
421             -multiple =>0,
422             -default => $default,
423         );
424 my $CGIorganisations;
425 my $member_of_institution;
426 if (C4::Context->preference("memberofinstitution")){
427     my $organisations=get_institutions();
428     my @orgs;
429     my %org_labels;
430     foreach my $organisation (keys %$organisations) {
431         push @orgs,$organisation;
432         $org_labels{$organisation}=$organisations->{$organisation}->{'surname'};
433     }
434     $member_of_institution=1;
435     
436     $CGIorganisations = CGI::scrolling_list( -id => 'organisations',
437         -name     => 'organisations',
438         -labels   => \%org_labels,
439         -values   => \@orgs,
440         -size     => 5,
441         -multiple => 'true'
442
443     );
444 }
445
446
447 # --------------------------------------------------------------------------------------------------------
448
449 my $CGIsort = buildCGIsort("Bsort1","sort1",$data{'sort1'});
450 if ($CGIsort) {
451   $template->param(CGIsort1 => $CGIsort);
452 }
453 $template->param( sort1 => $data{'sort1'});             # shouldn't this be in an "else" statement like the 2nd one?
454
455 $CGIsort = buildCGIsort("Bsort2","sort2",$data{'sort2'});
456 if ($CGIsort) {
457   $template->param(CGIsort2 => $CGIsort);
458 } else {
459   $template->param( sort2 => $data{'sort2'});
460 }
461
462 if ($nok) {
463     foreach my $error (@errors) {
464         $template->param($error) || $template->param( $error => 1);
465     }
466     $template->param(nok => 1);
467 }
468   
469   #Formatting data for display    
470   
471 if ($data{'dateenrolled'} eq ''){
472   my $today = sprintf('%04d-%02d-%02d', Today());       # ISO format
473   $data{'dateenrolled'}=$today;
474 }
475 if (C4::Context->preference('uppercasesurnames')) {
476         $data{'surname'}    =uc($data{'surname'}    );
477         $data{'contactname'}=uc($data{'contactname'});
478 }
479 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
480         $data{$_} = format_date($data{$_});     # back to syspref for display
481         $template->param( $_ => $data{$_});
482 }
483
484 $template->param( "showguarantor"  => ($category_type=~/A|I|S/) ? 0 : 1); # associate with step to know where you are
485 $debug and warn "memberentry step: $step";
486 $template->param(%data);
487 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
488 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
489 $template->param( debug  => $debug  ) if $debug;
490 $template->param(
491   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
492   category_type => $category_type,#to know the category type of the borrower
493   DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
494   select_city => $select_city,
495   "$category_type"  => 1,# associate with step to know where u are
496   destination   => $destination,#to know wher u come from and wher u must go in redirect
497   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
498   flags   =>$data{'flags'},   
499   "op$op"   => 1,
500   nodouble  => $nodouble,
501   borrowernumber  => $borrowernumber,#register number
502   "contacttitle_".$data{'contacttitle'} => "SELECTED" ,
503   guarantorid => $guarantorid,
504   ethcatpopup => $ethcatpopup,
505   relshiploop => \@relshipdata,
506   citypopup => $citypopup,
507   roadpopup => $roadpopup,  
508   borrotitlepopup => $borrotitlepopup,
509   guarantorinfo   => $guarantorinfo,
510   flagloop  => \@flagdata,
511   dateformat      => C4::Dates->new()->visual(),
512   C4::Context->preference('dateformat') => 1,
513   check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
514   modify          => $modify,
515   nok     => $nok,#flag to konw if an error 
516   CGIbranch => $CGIbranch,
517   memberofinstution => $member_of_institution,
518   CGIorganisations => $CGIorganisations,
519   NoUpdateLogin =>  $NoUpdateLogin
520   );
521   
522 output_html_with_http_headers $input, $cookie, $template->output;
523
524 # Local Variables:
525 # tab-width: 8
526 # End: