adding support for M and N sex
[koha.git] / members / memberentry.pl
1 #!/usr/bin/perl
2 # $Id$
3
4 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA  02111-1307 USA
20
21 # pragma
22 use strict;
23
24 # external modules
25 use Date::Calc qw/Today/;
26 use CGI;
27 use Digest::MD5 qw(md5_base64);
28
29 # internal modules
30 use C4::Auth;
31 use C4::Context;
32 use C4::Output;
33 use C4::Members;
34 use C4::Koha;
35 use C4::Date;
36 use C4::Input;
37 use C4::Log;
38 use C4::Branch; # GetBranches
39
40 my $input = new CGI;
41 my %data;
42
43 my $dbh = C4::Context->dbh;
44
45
46
47 my $step=$input->param('step') || 0;
48 my ($template, $loggedinuser, $cookie)
49     = get_template_and_user({template_name => "members/memberentrygen.tmpl",
50            query => $input,
51            type => "intranet",
52            authnotrequired => 0,
53            flagsrequired => {borrowers => 1},
54            debug => 1,
55            });
56 my $guarantorid=$input->param('guarantorid');
57 my $borrowernumber=$input->param('borrowernumber');
58 my $actionType=$input->param('actionType') || '';
59 my $modify=$input->param('modify');
60 my $delete=$input->param('delete');
61 my $op=$input->param('op');
62 my $destination=$input->param('destination');
63 my $cardnumber=$input->param('cardnumber');
64 my $check_member=$input->param('check_member');
65 my $name_city=$input->param('name_city');
66 my $nodouble=$input->param('nodouble');
67 my $select_city=$input->param('select_city');
68 my $nok=$input->param('nok');
69 my $guarantorinfo=$input->param('guarantorinfo');
70 my @errors;
71 my $default_city;
72 # $check_categorytype contains the value of duplicate borrowers category type to redirect in good template in step =2
73 my $check_categorytype=$input->param('check_categorytype');
74 # NOTE: Alert for ethnicity and ethnotes fields, they are unvalided in all borrowers form
75 my $borrower_data;
76
77
78 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
79
80 #function  to automatic setup the mandatory  fields (visual with css)
81 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
82 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
83 foreach (@field_check) {
84 $template->param( "mandatory$_" => 1);    
85 }
86 $template->param("add"=>1) if ($op eq 'add');
87 $template->param("checked" => 1) if ($nodouble eq 1);
88 my $categorycode=$input->param('categorycode');
89 ($borrower_data=GetMember($borrowernumber,'borrowernumber')) if ($op eq 'modify' or $op eq 'save');
90 $categorycode=$borrower_data->{'categorycode'} unless $categorycode;
91 my $category_type;
92 $category_type = $input->param('category_type');
93 unless ($category_type or !($categorycode)){
94   my $borrowercategory= GetBorrowercategory($categorycode);
95   $category_type = $borrowercategory->{'category_type'};
96 }
97 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
98
99 # if a add or modify is requested => check validity of data.
100 %data= %$borrower_data if ($borrower_data);
101
102 my %newdata;
103 if ($op eq 'insert' || $op eq 'modify' || $op eq 'save') {
104   my @names=($borrower_data?keys %$borrower_data:$input->param());
105   foreach my $key (@names){
106     $newdata{$key}=$input->param($key)||'';
107     $newdata{$key}=~ s/\"/"/gg unless $key eq 'borrowernotes' or $key eq 'opacnote';
108   }
109
110
111   # WARN : some tests must be done whatever the step, because the librarian can click on any tab.
112   #############test for member being unique #############
113   if ($op eq 'insert'){
114           my $category_type_send=$category_type if ($category_type eq 'I'); 
115           my $check_category; # recover the category code of the doublon suspect borrowers
116           ($check_member,$check_category)= checkuniquemember($category_type_send,($newdata{'surname'}?$newdata{'surname'}:$data{'surname'}),($newdata{'firstname'}?$newdata{'firstname'}:$data{'firstname'}),($newdata{'dateofbirth'}?format_date_in_iso($newdata{'dateofbirth'}):$data{'dateofbirth'}));
117           
118   #   recover the category type if the borrowers is a doublon 
119           my $tmpborrowercategory=GetBorrowercategory($check_category);
120           $check_categorytype=$tmpborrowercategory->{'category_type'};
121   }
122
123   #recover all data from guarantor address phone ,fax... 
124   if ($category_type eq 'C' and $guarantorid ne '' ){
125     my $guarantordata=GetMember($guarantorid);
126     $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
127     if (($data{'contactname'} eq '' or $data{'contactname'} ne $guarantordata->{'surname'})) {
128       $newdata{'contactfirstname'}=$guarantordata->{'firstname'}; 
129       $newdata{'contactname'}=$guarantordata->{'surname'};
130       $newdata{'contacttitle'}=$guarantordata->{'title'};  
131       map {$newdata{$_}=$guarantordata->{$_}}('streetnumber','address','streettype','address2','zipcode','city','phone','phonepro','mobile','fax','email','emailpro');
132     }
133   }
134
135   # CHECKS step by step
136 # STEP 1
137     if ($op eq 'insert' && checkcardnumber($cardnumber)){ 
138       push @errors, 'ERROR_cardnumber';
139       $nok = 1;
140     } 
141     ###############test to take the right zipcode and city name ##############
142     if ( $guarantorid eq ''){
143       if ($select_city){
144         my ($borrower_city,$borrower_zipcode)=&getzipnamecity($select_city);
145         $newdata{'city'}= $borrower_city;
146         $newdata{'zipcode'}=$borrower_zipcode;
147         }
148     }
149     my $dateofbirthmandatory=0;
150     map {$dateofbirthmandatory=1 if $_ eq "dateofbirth"} @field_check;
151     if ($category_type ne 'I' && $newdata{dateofbirth} && $dateofbirthmandatory) {
152       my $age = GetAge(format_date_in_iso($data{dateofbirth}));
153       my $borrowercategory=GetBorrowercategory($data{'categorycode'});   
154       if (($age > $borrowercategory->{'upperagelimit'}) or ($age < $borrowercategory->{'dateofbirthrequired'})) {
155         push @errors, 'ERROR_age_limitations';
156         $nok = 1;
157       }
158     }
159
160 # STEP 2
161     if ( ($newdata{'userid'} eq '')){
162       my $onefirstnameletter=substr($data{'firstname'},0,1);
163       my $fivesurnameletter=substr($data{'surname'},0,5);
164       $newdata{'userid'}=lc($onefirstnameletter.$fivesurnameletter);
165     }
166 #   }
167 # STEP 3
168   if ($op eq 'insert'){
169           my $loginexist;
170           # Check if the userid is unique
171           if ( !Check_Userid($data{'userid'},$borrowernumber)) {
172                   push @errors, "ERROR_login_exist";
173                   $loginexist = 1;
174                   $nok=1;
175     } else {
176       $borrowernumber = &AddMember(%newdata);
177         if ($data{'organisations'}){            
178           # need to add the members organisations
179           my @orgs=split(/\|/,$data{'organisations'});
180           add_member_orgs($borrowernumber,\@orgs);
181         }
182     }
183
184     unless ($nok) {
185       if($destination eq "circ"){
186         print $input->redirect("/cgi-bin/koha/circ/circulation.pl?findborrower=$data{'cardnumber'}");
187       } else {
188         if ($loginexist == 0) {
189         print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
190         }
191       }
192     }
193   }
194
195   if (C4::Context->preference("IndependantBranches")) {
196     my $userenv = C4::Context->userenv;
197     if ($userenv->{flags} != 1){
198       unless ($userenv->{branch} eq $data{'branchcode'}){
199         push @errors, "ERROR_branch";
200         $nok=1;
201       }
202     }
203   }
204   if ($op eq 'modify' ){
205     unless ($data{'dateexpiry'}){
206       my $today= sprintf('%04d-%02d-%02d', Today());
207       $data{'dateexpiry'} = GetExpiryDate($data{'categorycode'},$today);
208     }
209   }
210 # }
211
212 if ($op eq 'save'){
213         # test to know if another user have the same password and same login    
214         my $loginexist;                                                                                                                                      
215         # Check if the userid is unique                                                                                                                      
216         if ( !Check_Userid($data{'userid'},$borrowernumber)) {
217                 push @errors, "ERROR_login_exist";
218                 $loginexist = 1;
219                 $nok=1;
220         }
221         if (!$loginexist){
222                 &ModMember(%newdata);    
223                 print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
224         }
225 }
226
227 if ($delete){
228         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
229 }
230 if ($nok){
231   $op="add" if ($op eq "insert");
232   $op="modify" if ($op eq "save");
233   %data=%newdata; 
234   $template->param( updtype => ($op eq "insert"?'I':'M'),step_1=>1,step_2=>1,step_3=>1,allsteps=>1);
235
236 #  else {  # this else goes down the whole script
237   # retrieve previous values : either in DB or in CGI, in case of errors in values
238 #   my $data;
239 # # test to now if u add or modify a borrower (modify =>to take all carateristic of the borrowers)
240 #   if (!$op and !$data{'surname'}) {
241 #     $data=GetMember($borrowernumber,'borrowernumber');
242 #     %data=%$data;
243 #   }
244   if (C4::Context->preference("IndependantBranches")) {
245     my $userenv = C4::Context->userenv;
246     if ($userenv->{flags} != 1 && $data{branchcode}){
247       unless ($userenv->{branch} eq $data{'branchcode'}){
248         print $input->redirect("/cgi-bin/koha/members/members-home.pl");
249       }
250     }
251   }
252   if ($op eq 'add'){
253     $template->param( updtype => 'I',step_1=>1,step_2=>1,step_3=>1,allsteps=>1);
254   } 
255   if ($op eq "modify")  {
256     $template->param( updtype => 'M');
257     $template->param( step_1=>1,step_2=>1,step_3=>1,allsteps=>1) unless $step;
258   }
259 # my $cardnumber=$data{'cardnumber'};
260   $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if $op eq 'add';
261   if ($data{'sex'} eq 'F'){
262     $template->param(female => 1);
263   } elsif ($data{'sex'} eq 'M'){
264      $template->param(mail => 1);
265   } else ($data{'sex'} eq 'N'){
266      $template->param(none => 1);
267   }
268   my ($categories,$labels)=ethnicitycategories();
269     
270   my $ethnicitycategoriescount=$#{$categories};
271   my $ethcatpopup;
272   if ($ethnicitycategoriescount>=0) {
273     $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
274           -id => 'ethnicity',
275           -tabindex=>'',
276           -values=>$categories,
277           -default=>$data{'ethnicity'},
278           -labels=>$labels);
279     $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
280   }
281   
282   
283   my $action="WHERE category_type=?";
284   ($categories,$labels)=GetborCatFromCatType($category_type,$action);
285   
286   if(scalar(@$categories)){
287       #if you modify the borrowers you must have the right value for his category code
288   (my $default_category=$data{'categorycode'}) if ($op  eq 'modify');
289       my $catcodepopup = CGI::popup_menu(
290           -name=>'categorycode',
291       -id => 'categorycode',
292       -values=>$categories,
293         -labels=>$labels,
294       -default=>$default_category
295       );
296       $template->param(catcodepopup=>$catcodepopup);
297   }
298   #test in city
299   $select_city=getidcity($data{'city'}) if ($guarantorid ne '0');
300   ($default_city=$select_city) if ($step eq 0);
301   if ($select_city eq '' ){
302   my $selectcity=&getidcity($data{'city'});
303   $default_city=$selectcity;
304   }
305   my($cityid,$name_city)=GetCities();
306   $template->param( city_cgipopup => 1) if ($cityid );
307   my $citypopup = CGI::popup_menu(-name=>'select_city',
308           -id => 'select_city',
309           -values=>$cityid,
310           -labels=>$name_city,
311 #             -override => 1,
312           -default=>$default_city
313           );  
314   
315   my $default_roadtype;
316   $default_roadtype=$data{'streettype'} ;
317   my($roadtypeid,$road_type)=GetRoadTypes();
318     $template->param( road_cgipopup => 1) if ($roadtypeid );
319   my $roadpopup = CGI::popup_menu(-name=>'streettype',
320           -id => 'streettype',
321           -values=>$roadtypeid,
322             -labels=>$road_type,
323             -override => 1,
324           -default=>$default_roadtype
325           );  
326
327   my $default_borrowertitle;
328   $default_borrowertitle=$data{'title'} ;
329   my($borrowertitle)=GetTitles();
330   my $borrotitlepopup = CGI::popup_menu(-name=>'title',
331                 -id => 'btitle',
332                 -values=>$borrowertitle,
333                 -override => 1,
334                 -default=>$default_borrowertitle
335           );    
336
337
338   my @relationships = split /,|\|/,C4::Context->preference('BorrowerRelationship');
339   my @relshipdata;
340   while (@relationships) {
341     my $relship = shift @relationships || '';
342     my %row = ('relationship' => $relship);
343     if ($data{'relationship'} eq $relship) {
344       $row{'selected'}=' selected';
345     } else {
346       $row{'selected'}='';
347     }
348     push(@relshipdata, \%row);
349   }
350   my %flags = ( 'gonenoaddress' => ['gonenoaddress', 'Gone no address '],
351           'lost'          => ['lost', 'Lost'],
352           'debarred'      => ['debarred', 'Debarred']);
353
354   my @flagdata;
355   foreach (keys(%flags)) {
356   my $key = $_;
357   my %row =  ('key'   => $key,
358       'name'  => $flags{$key}[0],
359       'html'  => $flags{$key}[1]);
360   if ($data{$key}) {
361     $row{'yes'}=' checked';
362     $row{'no'}='';
363   } else {
364     $row{'yes'}='';
365     $row{'no'}=' checked';
366   }
367   push(@flagdata, \%row);
368   }
369
370   if ($modify){
371   $template->param( modify => 1 );
372   }
373
374   #Convert dateofbirth to correct format
375   my @branches;
376   my @select_branch;
377   my %select_branches;
378   my $branches=GetBranches();
379   my $default;
380   # -----------------------------------------------------
381   #  the value of ip from the branches hash table
382 #     my $select_ip;
383   # $ip is the ip of user when is connect to koha 
384 #     my $ip = $ENV{'REMOTE_ADDR'};
385   
386   # -----------------------------------------------------
387   foreach my $branch (keys %$branches) {
388     if ((not C4::Context->preference("IndependantBranches")) || (C4::Context->userenv->{'flags'} == 1)) {
389       push @select_branch, $branch;
390       $select_branches{$branch} = $branches->{$branch}->{'branchname'};
391       $default=C4::Context->userenv->{'branch'};
392     } else {
393       push @select_branch,$branch if ($branch eq C4::Context->userenv->{'branch'});
394       $select_branches{$branch} = $branches->{$branch}->{'branchname'} if ($branch eq C4::Context->userenv->{'branch'});
395       $default = C4::Context->userenv->{'branch'};
396     }
397   }
398 # --------------------------------------------------------------------------------------------------------
399   #in modify mod :default value from $CGIbranch comes from borrowers table
400   #in add mod: default value come from branches table (ip correspendence)
401   $default=$data{'branchcode'}  if ($op eq 'modify');
402   my $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
403              -name   => 'branchcode',
404              -values => \@select_branch,
405              -labels => \%select_branches,
406              -size   => 1,
407              -override => 1,  
408                    -multiple =>0,
409              -default => $default,
410           );
411   my $CGIorganisations;
412   my $member_of_institution;
413   if (C4::Context->preference("memberofinstitution")){
414      my $organisations=get_institutions();
415      my @orgs;
416      my %org_labels;
417      foreach my $organisation (keys %$organisations) {
418          push @orgs,$organisation;
419          $org_labels{$organisation}=$organisations->{$organisation}->{'surname'};
420      }
421      $member_of_institution=1;
422      
423      $CGIorganisations = CGI::scrolling_list( -id => 'organisations',
424          -name     => 'organisations',
425          -labels   => \%org_labels,
426          -values   => \@orgs,
427          -size     => 5,
428          -multiple => 'true'
429
430          
431      );
432   }
433
434
435 # --------------------------------------------------------------------------------------------------------
436
437   my $CGIsort1 = buildCGIsort("Bsort1","sort1",$data{'sort1'});
438   if ($CGIsort1) {
439     $template->param(CGIsort1 => $CGIsort1);
440     $template->param( sort1 => $data{'sort1'});
441   } else {
442     $template->param( sort1 => $data{'sort1'});
443   }
444   
445   my $CGIsort2 = buildCGIsort("Bsort2","sort2",$data{'sort2'});
446   if ($CGIsort2) {
447     $template->param(CGIsort2 =>$CGIsort2);
448   } else {
449     $template->param( sort2 => $data{'sort2'});
450   }
451   # increase step to see next page
452   if ($nok) {
453       foreach my $error (@errors) {
454           $template->param( $error => 1);
455       }
456         $template->param(nok => 1);
457   }
458 #   else {
459 #       $step++ if $op eq 'add';
460 #   }
461   #Formatting data for display    
462   
463   if ($data{'dateenrolled'} eq ''){
464     my $today= sprintf('%04d-%02d-%02d', Today());
465     #insert ,in field "dateenrolled" , the current date
466     $data{'dateenrolled'}=$today;
467     $data{'dateexpiry'} = GetExpiryDate($data{'categorycode'},$today);
468   }
469   
470   $data{'surname'}=uc($data{'surname'});
471   $data{'firstname'}=ucfirst(lc $data{'firstname'});
472   $data{'dateenrolled'}=format_date($data{'dateenrolled'});
473   $data{'dateexpiry'}=format_date($data{'dateexpiry'});
474   $data{'contactname'}=uc($data{'contactname'});
475   $data{'contactfirstname'}= ucfirst( lc $data{'contactfirstname'});
476   $data{'dateofbirth'} = format_date($data{'dateofbirth'});
477
478 #   warn "$step";
479   $template->param(%data);
480   $template->param(
481     BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
482     category_type => $category_type,#to know the category type of the borrower
483         DHTMLcalendar_dateformat => get_date_format_string_for_DHTMLcalendar(),
484     select_city => $select_city,
485     "step_$step"  => 1,# associate with step to know where u are
486     "$category_type"  => 1,# associate with step to know where u are
487     step    => $step,
488     destination   => $destination,#to know wher u come from and wher u must go in redirect
489     check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
490     flags   =>$data{'flags'},   
491     "op$op"   => 1,
492     nodouble  => $nodouble,
493     borrowernumber  => $borrowernumber,#register number
494     "contacttitle_".$data{'contacttitle'} => "SELECTED" ,
495     guarantorid => $guarantorid,
496     ethcatpopup => $ethcatpopup,
497     relshiploop => \@relshipdata,
498     citypopup => $citypopup,
499     roadpopup => $roadpopup,  
500     borrotitlepopup => $borrotitlepopup,
501     guarantorinfo   => $guarantorinfo,
502     flagloop  => \@flagdata,
503     dateformat      => display_date_format(),
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     
511     );
512   
513   output_html_with_http_headers $input, $cookie, $template->output;
514 # }
515
516 # Local Variables:
517 # tab-width: 8
518 # End: