memberentry.pl - fixes inappropriate use of map in void context, tweaks debug for CGI
[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 unvalided 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 automatic setup the mandatory  fields (visual 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;
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 $regexp = $dateobject->regexp();             # same format for all 3 dates
114         foreach (qw(dateenrolled dateexpiry dateofbirth)) {
115                 my $userdate = $newdata{$_} or next;
116                 if ($userdate =~ /$regexp/) {
117                         $newdata{$_} = format_date_in_iso($userdate);
118                 } else {
119                         $template->param( "ERROR_$_" => $userdate );
120                         push(@errors,"ERROR_$_");
121                         $nok++;
122                 }
123         }
124   # check permission to modify login info.
125     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($dbh,$userenv->{'id'},{'staffaccess'=>1})) )  {
126                 $NoUpdateLogin =1;
127         }
128 }
129
130 #############test for member being unique #############
131 if ($op eq 'insert'){
132         my $category_type_send=$category_type if ($category_type eq 'I'); 
133         my $check_category; # recover the category code of the doublon suspect borrowers
134         ($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'}));
135           
136   #   recover the category type if the borrowers is a doublon 
137         my $tmpborrowercategory=GetBorrowercategory($check_category);
138         $check_categorytype=$tmpborrowercategory->{'category_type'};
139 }
140
141   #recover all data from guarantor address phone ,fax... 
142 if (($category_type eq 'C' || $category_type eq 'P') and $guarantorid ne '' ){
143   my $guarantordata=GetMember($guarantorid);
144   $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
145   if (($data{'contactname'} eq '' or $data{'contactname'} ne $guarantordata->{'surname'})) {
146     $data{'contactfirstname'}= $guarantordata->{'firstname'}; 
147     $data{'contactname'}     = $guarantordata->{'surname'};
148     $data{'contacttitle'}    = $guarantordata->{'title'};  
149         foreach (qw(streetnumber address streettype address2 zipcode city phonephonepro mobile fax email emailpro)) {
150                 $data{$_} = $guarantordata->{$_};
151         }
152   }
153 }
154
155 ###############test to take the right zipcode and city name ##############
156 if ( $guarantorid eq ''){
157   if ($select_city){
158     my ($borrower_city,$borrower_zipcode)=&getzipnamecity($select_city);
159     $newdata{'city'}= $borrower_city;
160     $newdata{'zipcode'}=$borrower_zipcode;
161     }
162 }
163 #builds default userid
164 if ( (defined $newdata{'userid'}) && ($newdata{'userid'} eq '')){
165   my $onefirstnameletter = substr($data{'firstname'},0,1);
166   my  $fivesurnameletter = substr($data{'surname'},0,9);
167   $newdata{'userid'}=lc($onefirstnameletter.$fivesurnameletter);
168 }
169   
170 my $loginexist=0;
171 if ($op eq 'save' || $op eq 'insert'){
172   if (checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){ 
173     push @errors, 'ERROR_cardnumber';
174     $nok = 1;
175   } 
176   my $dateofbirthmandatory = (scalar grep {$_ eq "dateofbirth"} @field_check) ? 1 : 0;
177   if ($newdata{dateofbirth} && $dateofbirthmandatory) {
178     my $age = GetAge($newdata{dateofbirth});
179     my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});   
180     if (($age > $borrowercategory->{'upperagelimit'}) or ($age < $borrowercategory->{'dateofbirthrequired'})) {
181       push @errors, 'ERROR_age_limitations';
182       $nok = 1;
183     }
184   }
185         $debug and warn "dateofbirth: " . $newdata{'dateofbirth'};
186     
187   if (C4::Context->preference("IndependantBranches")) {
188     if ($userenv && $userenv->{flags} != 1){
189       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
190       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
191         push @errors, "ERROR_branch";
192         $nok=1;
193       }
194     }
195   }
196   # Check if the userid is unique
197   if (($op eq 'insert' || $op eq 'save') && !Check_Userid($newdata{'userid'},$borrowernumber)) {
198     push @errors, "ERROR_login_exist";
199     $nok=1;
200     $loginexist=1; 
201   }
202 }
203
204 if ($op eq 'modify' || $op eq 'insert'){
205   unless ($newdata{'dateexpiry'}){
206         my $arg2 = $newdata{'dateenrolled'} || sprintf('%04d-%02d-%02d', Today());
207     $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
208   }
209 }
210
211 if ($op eq 'insert'){
212   # Check if the userid is unique
213   unless ($nok){
214     $borrowernumber = &AddMember(%newdata);
215     if ($data{'organisations'}){            
216       # need to add the members organisations
217       my @orgs=split(/\|/,$data{'organisations'});
218       add_member_orgs($borrowernumber,\@orgs);
219     }
220     if ($destination eq "circ") {
221     } else {
222                 print $input->redirect("/cgi-bin/koha/circ/circulation.pl?findborrower=$data{'cardnumber'}");
223         if ($loginexist == 0) {
224             print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
225         }
226     }
227   }
228 }
229 if ($op eq 'save'){
230         # test to know if another user have the same password and same login                                
231         unless ($nok){
232             if($NoUpdateLogin) {
233                         delete $newdata{'password'};
234                         delete $newdata{'userid'};
235                 }
236                 $debug and warn "dateofbirth: " . $newdata{'dateofbirth'};
237                 &ModMember(%newdata);    
238             if ($destination eq "circ") {
239                 print $input->redirect("/cgi-bin/koha/circ/circulation.pl?findborrower=$data{'cardnumber'}");
240             } else {
241                 print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
242             }
243         }
244 }
245
246 if ($delete){
247         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
248 }
249
250 if ($nok){
251   $op="add" if ($op eq "insert");
252   $op="modify" if ($op eq "save");
253   %data=%newdata; 
254   $template->param( updtype => ($op eq "insert"?'I':'M'));
255   unless ($step){  
256     $template->param( step_1 => 1,step_2 => 1,step_3 => 1);
257   }  
258
259 if (C4::Context->preference("IndependantBranches")) {
260   my $userenv = C4::Context->userenv;
261   if ($userenv->{flags} != 1 && $data{branchcode}){
262     unless ($userenv->{branch} eq $data{'branchcode'}){
263       print $input->redirect("/cgi-bin/koha/members/members-home.pl");
264     }
265   }
266 }
267 if ($op eq 'add'){
268   $template->param( updtype => 'I',step_1=>1,step_2=>1,step_3=>1);
269
270 if ($op eq "modify")  {
271   $template->param( updtype => 'M',modify => 1 );
272   $template->param( step_1=>1,step_2=>1,step_3=>1) unless $step;
273 }
274 # my $cardnumber=$data{'cardnumber'};
275 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if $op eq 'add';
276 if ($data{'sex'} eq 'F'){
277   $template->param(female => 1);
278 } elsif ($data{'sex'} eq 'M'){
279     $template->param(male => 1);
280 } else {
281     $template->param(none => 1);
282 }
283
284 ##Now all the data to modify a member.
285 my ($categories,$labels)=ethnicitycategories();
286   
287 my $ethnicitycategoriescount=$#{$categories};
288 my $ethcatpopup;
289 if ($ethnicitycategoriescount>=0) {
290   $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
291         -id => 'ethnicity',
292         -tabindex=>'',
293         -values=>$categories,
294         -default=>$data{'ethnicity'},
295         -labels=>$labels);
296   $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
297 }
298   
299   
300 my $action="WHERE category_type=?";
301 ($categories,$labels)=GetborCatFromCatType($category_type,$action);
302   
303 if(scalar(@$categories)){
304       #if you modify the borrowers you must have the right value for his category code
305   my $default_category=$newdata{'categorycode'} if ($op  eq 'modify');
306   my $catcodepopup = CGI::popup_menu(
307       -name=>'categorycode',
308   -id => 'categorycode',
309   -values=>$categories,
310     -labels=>$labels,
311   -default=>$default_category
312   );
313   $template->param(catcodepopup=>$catcodepopup);
314 }
315   #test in city
316 $select_city=getidcity($data{'city'}) if ($guarantorid ne '0');
317 ($default_city=$select_city) if ($step eq 0);
318 if ($select_city eq '' ){
319         $default_city = &getidcity($data{'city'});
320 }
321 my($cityid);
322 ($cityid,$name_city)=GetCities();
323 $template->param( city_cgipopup => 1) if ($cityid );
324 my $citypopup = CGI::popup_menu(-name=>'select_city',
325         -id => 'select_city',
326         -values=>$name_city,
327         -labels=>$name_city,
328         -default=>$default_city,
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 my @relationships = split /,|\|/,C4::Context->preference('BorrowerRelationship');
354 my @relshipdata;
355 while (@relationships) {
356   my $relship = shift @relationships || '';
357   my %row = ('relationship' => $relship);
358   if ($data{'relationship'} eq $relship) {
359     $row{'selected'}=' selected';
360   } else {
361     $row{'selected'}='';
362   }
363   push(@relshipdata, \%row);
364 }
365 my %flags = ( 'gonenoaddress' => ['gonenoaddress', 'Gone no address '],
366         'lost'          => ['lost', 'Lost'],
367         'debarred'      => ['debarred', 'Debarred']);
368
369 my @flagdata;
370 foreach (keys(%flags)) {
371 my $key = $_;
372 my %row =  ('key'   => $key,
373     'name'  => $flags{$key}[0],
374     'html'  => $flags{$key}[1]);
375 if ($data{$key}) {
376   $row{'yes'}=' checked';
377   $row{'no'}='';
378 } else {
379   $row{'yes'}='';
380   $row{'no'}=' checked';
381 }
382 push(@flagdata, \%row);
383 }
384
385
386 #get Branches
387 my @branches;
388 my @select_branch;
389 my %select_branches;
390
391 my $onlymine=(C4::Context->preference('IndependantBranches') && 
392               C4::Context->userenv && 
393               C4::Context->userenv->{flags} !=1  && 
394               C4::Context->userenv->{branch}?1:0);
395               
396 my $branches=GetBranches($onlymine);
397 my $default;
398
399 foreach my $branch (sort keys %$branches) {
400     push @select_branch,$branch;
401     $select_branches{$branch} = $branches->{$branch}->{'branchname'};
402     $default = C4::Context->userenv->{'branch'} if (C4::Context->userenv && C4::Context->userenv->{'branch'});
403 }
404 # --------------------------------------------------------------------------------------------------------
405   #in modify mod :default value from $CGIbranch comes from borrowers table
406   #in add mod: default value come from branches table (ip correspendence)
407 $default=$data{'branchcode'}  if ($op eq 'modify');
408 my $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
409             -name   => 'branchcode',
410             -values => \@select_branch,
411             -labels => \%select_branches,
412             -size   => 1,
413             -override => 1,  
414             -multiple =>0,
415             -default => $default,
416         );
417 my $CGIorganisations;
418 my $member_of_institution;
419 if (C4::Context->preference("memberofinstitution")){
420     my $organisations=get_institutions();
421     my @orgs;
422     my %org_labels;
423     foreach my $organisation (keys %$organisations) {
424         push @orgs,$organisation;
425         $org_labels{$organisation}=$organisations->{$organisation}->{'surname'};
426     }
427     $member_of_institution=1;
428     
429     $CGIorganisations = CGI::scrolling_list( -id => 'organisations',
430         -name     => 'organisations',
431         -labels   => \%org_labels,
432         -values   => \@orgs,
433         -size     => 5,
434         -multiple => 'true'
435
436     );
437 }
438
439
440 # --------------------------------------------------------------------------------------------------------
441
442 my $CGIsort1 = buildCGIsort("Bsort1","sort1",$data{'sort1'});
443 if ($CGIsort1) {
444   $template->param(CGIsort1 => $CGIsort1);
445 }
446 $template->param( sort1 => $data{'sort1'});
447
448 my $CGIsort2 = buildCGIsort("Bsort2","sort2",$data{'sort2'});
449 if ($CGIsort2) {
450   $template->param(CGIsort2 =>$CGIsort2);
451 } else {
452   $template->param( sort2 => $data{'sort2'});
453 }
454
455 if ($nok or scalar(@errors)) {
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: