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