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