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