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