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