#1475
[koha-ffzg.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 $step=$input->param('step') || 0;
48 my ($template, $loggedinuser, $cookie)
49     = get_template_and_user({template_name => "members/memberentrygen.tmpl",
50            query => $input,
51            type => "intranet",
52            authnotrequired => 0,
53            flagsrequired => {borrowers => 1},
54            debug => 1,
55            });
56 my $guarantorid=$input->param('guarantorid');
57 my $borrowernumber=$input->param('borrowernumber');
58 my $actionType=$input->param('actionType') || '';
59 my $modify=$input->param('modify');
60 my $delete=$input->param('delete');
61 my $op=$input->param('op');
62 my $destination=$input->param('destination');
63 my $cardnumber=$input->param('cardnumber');
64 my $check_member=$input->param('check_member');
65 my $name_city=$input->param('name_city');
66 my $nodouble=$input->param('nodouble');
67 my $select_city=$input->param('select_city');
68 my $nok=$input->param('nok');
69 my $guarantorinfo=$input->param('guarantorinfo');
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     
105     my @names= $borrower_data && $op ne 'save' ? keys %$borrower_data : $input->param();
106     foreach my $key (@names) {
107         $newdata{$key} = $input->param($key) || '';
108         $newdata{$key} =~ s/\"/"/gg unless $key eq 'borrowernotes' or $key eq 'opacnote';
109     }
110
111
112   # WARN : some tests must be done whatever the step, because the librarian can click on any tab.
113   #############test for member being unique #############
114   if ($op eq 'insert'){
115           my $category_type_send=$category_type if ($category_type eq 'I'); 
116           my $check_category; # recover the category code of the doublon suspect borrowers
117           ($check_member,$check_category)= checkuniquemember($category_type_send,($newdata{'surname'}?$newdata{'surname'}:$data{'surname'}),($newdata{'firstname'}?$newdata{'firstname'}:$data{'firstname'}),($newdata{'dateofbirth'}?format_date_in_iso($newdata{'dateofbirth'}):$data{'dateofbirth'}));
118           
119   #   recover the category type if the borrowers is a doublon 
120           my $tmpborrowercategory=GetBorrowercategory($check_category);
121           $check_categorytype=$tmpborrowercategory->{'category_type'};
122   }
123
124   #recover all data from guarantor address phone ,fax... 
125   if ($category_type eq 'C' and $guarantorid ne '' ){
126     my $guarantordata=GetMember($guarantorid);
127     $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
128     if (($data{'contactname'} eq '' or $data{'contactname'} ne $guarantordata->{'surname'})) {
129       $newdata{'contactfirstname'}=$guarantordata->{'firstname'}; 
130       $newdata{'contactname'}=$guarantordata->{'surname'};
131       $newdata{'contacttitle'}=$guarantordata->{'title'};  
132       map {$newdata{$_}=$guarantordata->{$_}}('streetnumber','address','streettype','address2','zipcode','city','phone','phonepro','mobile','fax','email','emailpro');
133     }
134   }
135
136   # CHECKS step by step
137 # STEP 1
138     if ($op eq 'insert' && checkcardnumber($cardnumber)){ 
139       push @errors, 'ERROR_cardnumber';
140       $nok = 1;
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     my $dateofbirthmandatory=0;
151     map {$dateofbirthmandatory=1 if $_ eq "dateofbirth"} @field_check;
152     if ($category_type ne 'I' && $newdata{dateofbirth} && $dateofbirthmandatory) {
153       my $age = GetAge(format_date_in_iso($data{dateofbirth}));
154       my $borrowercategory=GetBorrowercategory($data{'categorycode'});   
155       if (($age > $borrowercategory->{'upperagelimit'}) or ($age < $borrowercategory->{'dateofbirthrequired'})) {
156         push @errors, 'ERROR_age_limitations';
157         $nok = 1;
158       }
159     }
160
161 # STEP 2
162     if ( ($newdata{'userid'} eq '')){
163       my $onefirstnameletter=substr($data{'firstname'},0,1);
164       my $fivesurnameletter=substr($data{'surname'},0,5);
165       $newdata{'userid'}=lc($onefirstnameletter.$fivesurnameletter);
166     }
167 #   }
168 # STEP 3
169   if ($op eq 'insert'){
170           my $loginexist;
171           # Check if the userid is unique
172           if ( !Check_Userid($data{'userid'},$borrowernumber)) {
173                   push @errors, "ERROR_login_exist";
174                   $loginexist = 1;
175                   $nok=1;
176     } else {
177       $borrowernumber = &AddMember(%newdata);
178         if ($data{'organisations'}){            
179           # need to add the members organisations
180           my @orgs=split(/\|/,$data{'organisations'});
181           add_member_orgs($borrowernumber,\@orgs);
182         }
183     }
184
185     unless ($nok) {
186       if($destination eq "circ"){
187         print $input->redirect("/cgi-bin/koha/circ/circulation.pl?findborrower=$data{'cardnumber'}");
188       } else {
189         if ($loginexist == 0) {
190         print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
191         }
192       }
193     }
194   }
195
196   if (C4::Context->preference("IndependantBranches")) {
197     my $userenv = C4::Context->userenv;
198     if ($userenv->{flags} != 1){
199       unless ($userenv->{branch} eq $data{'branchcode'}){
200         push @errors, "ERROR_branch";
201         $nok=1;
202       }
203     }
204   }
205   if ($op eq 'modify' ){
206     unless ($data{'dateexpiry'}){
207       my $today= sprintf('%04d-%02d-%02d', Today());
208       $data{'dateexpiry'} = GetExpiryDate($data{'categorycode'},$today);
209     }
210   }
211 # }
212
213 if ($op eq 'save'){
214         # test to know if another user have the same password and same login    
215         my $loginexist;                                                                                                                                      
216         # Check if the userid is unique                                                                                                                      
217         if ( !Check_Userid($data{'userid'},$borrowernumber)) {
218                 push @errors, "ERROR_login_exist";
219                 $loginexist = 1;
220                 $nok=1;
221         }
222         if (!$loginexist){
223                 &ModMember(%newdata);    
224                 print $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber");
225         }
226 }
227
228 if ($delete){
229         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
230 }
231 if ($nok){
232   $op="add" if ($op eq "insert");
233   $op="modify" if ($op eq "save");
234   %data=%newdata; 
235   $template->param( updtype => ($op eq "insert"?'I':'M'),step_1=>1,step_2=>1,step_3=>1,allsteps=>1);
236
237 #  else {  # this else goes down the whole script
238   # retrieve previous values : either in DB or in CGI, in case of errors in values
239 #   my $data;
240 # # test to now if u add or modify a borrower (modify =>to take all carateristic of the borrowers)
241 #   if (!$op and !$data{'surname'}) {
242 #     $data=GetMember($borrowernumber,'borrowernumber');
243 #     %data=%$data;
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,allsteps=>1);
255   } 
256   if ($op eq "modify")  {
257     $template->param( updtype => 'M');
258     $template->param( step_1=>1,step_2=>1,step_3=>1,allsteps=>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   my ($categories,$labels)=ethnicitycategories();
270     
271   my $ethnicitycategoriescount=$#{$categories};
272   my $ethcatpopup;
273   if ($ethnicitycategoriescount>=0) {
274     $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
275           -id => 'ethnicity',
276           -tabindex=>'',
277           -values=>$categories,
278           -default=>$data{'ethnicity'},
279           -labels=>$labels);
280     $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
281   }
282   
283   
284   my $action="WHERE category_type=?";
285   ($categories,$labels)=GetborCatFromCatType($category_type,$action);
286   
287   if(scalar(@$categories)){
288       #if you modify the borrowers you must have the right value for his category code
289   (my $default_category=$data{'categorycode'}) if ($op  eq 'modify');
290       my $catcodepopup = CGI::popup_menu(
291           -name=>'categorycode',
292       -id => 'categorycode',
293       -values=>$categories,
294         -labels=>$labels,
295       -default=>$default_category
296       );
297       $template->param(catcodepopup=>$catcodepopup);
298   }
299   #test in city
300   $select_city=getidcity($data{'city'}) if ($guarantorid ne '0');
301   ($default_city=$select_city) if ($step eq 0);
302   if ($select_city eq '' ){
303   my $selectcity=&getidcity($data{'city'});
304   $default_city=$selectcity;
305   }
306   my($cityid,$name_city)=GetCities();
307   $template->param( city_cgipopup => 1) if ($cityid );
308   my $citypopup = CGI::popup_menu(-name=>'select_city',
309           -id => 'select_city',
310           -values=>$cityid,
311           -labels=>$name_city,
312 #             -override => 1,
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   if ($modify){
372   $template->param( modify => 1 );
373   }
374
375   #Convert dateofbirth to correct format
376   my @branches;
377   my @select_branch;
378   my %select_branches;
379   my $branches=GetBranches();
380   my $default;
381   # -----------------------------------------------------
382   #  the value of ip from the branches hash table
383 #     my $select_ip;
384   # $ip is the ip of user when is connect to koha 
385 #     my $ip = $ENV{'REMOTE_ADDR'};
386   
387   # -----------------------------------------------------
388   foreach my $branch (keys %$branches) {
389     if ((not C4::Context->preference("IndependantBranches")) || (C4::Context->userenv->{'flags'} == 1)) {
390       push @select_branch, $branch;
391       $select_branches{$branch} = $branches->{$branch}->{'branchname'};
392       $default=C4::Context->userenv->{'branch'};
393     } else {
394       push @select_branch,$branch if ($branch eq C4::Context->userenv->{'branch'});
395       $select_branches{$branch} = $branches->{$branch}->{'branchname'} if ($branch eq C4::Context->userenv->{'branch'});
396       $default = C4::Context->userenv->{'branch'};
397     }
398   }
399 # --------------------------------------------------------------------------------------------------------
400   #in modify mod :default value from $CGIbranch comes from borrowers table
401   #in add mod: default value come from branches table (ip correspendence)
402   $default=$data{'branchcode'}  if ($op eq 'modify');
403   my $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
404              -name   => 'branchcode',
405              -values => \@select_branch,
406              -labels => \%select_branches,
407              -size   => 1,
408              -override => 1,  
409                    -multiple =>0,
410              -default => $default,
411           );
412   my $CGIorganisations;
413   my $member_of_institution;
414   if (C4::Context->preference("memberofinstitution")){
415      my $organisations=get_institutions();
416      my @orgs;
417      my %org_labels;
418      foreach my $organisation (keys %$organisations) {
419          push @orgs,$organisation;
420          $org_labels{$organisation}=$organisations->{$organisation}->{'surname'};
421      }
422      $member_of_institution=1;
423      
424      $CGIorganisations = CGI::scrolling_list( -id => 'organisations',
425          -name     => 'organisations',
426          -labels   => \%org_labels,
427          -values   => \@orgs,
428          -size     => 5,
429          -multiple => 'true'
430
431          
432      );
433   }
434
435
436 # --------------------------------------------------------------------------------------------------------
437
438   my $CGIsort1 = buildCGIsort("Bsort1","sort1",$data{'sort1'});
439   if ($CGIsort1) {
440     $template->param(CGIsort1 => $CGIsort1);
441     $template->param( sort1 => $data{'sort1'});
442   } else {
443     $template->param( sort1 => $data{'sort1'});
444   }
445   
446   my $CGIsort2 = buildCGIsort("Bsort2","sort2",$data{'sort2'});
447   if ($CGIsort2) {
448     $template->param(CGIsort2 =>$CGIsort2);
449   } else {
450     $template->param( sort2 => $data{'sort2'});
451   }
452   # increase step to see next page
453   if ($nok) {
454       foreach my $error (@errors) {
455           $template->param( $error => 1);
456       }
457         $template->param(nok => 1);
458   }
459 #   else {
460 #       $step++ if $op eq 'add';
461 #   }
462   #Formatting data for display    
463   
464   if ($data{'dateenrolled'} eq ''){
465     my $today= sprintf('%04d-%02d-%02d', Today());
466     #insert ,in field "dateenrolled" , the current date
467     $data{'dateenrolled'}=$today;
468     $data{'dateexpiry'} = GetExpiryDate($data{'categorycode'},$today);
469   }
470   
471   $data{'surname'}=uc($data{'surname'});
472   $data{'firstname'}=ucfirst(lc $data{'firstname'});
473   $data{'dateenrolled'}=format_date($data{'dateenrolled'});
474   $data{'dateexpiry'}=format_date($data{'dateexpiry'});
475   $data{'contactname'}=uc($data{'contactname'});
476   $data{'contactfirstname'}= ucfirst( lc $data{'contactfirstname'});
477   $data{'dateofbirth'} = format_date($data{'dateofbirth'});
478
479 #   warn "$step";
480   $template->param(%data);
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 => get_date_format_string_for_DHTMLcalendar(),
485     select_city => $select_city,
486     "step_$step"  => 1,# associate with step to know where u are
487     "$category_type"  => 1,# associate with step to know where u are
488     step    => $step,
489     destination   => $destination,#to know wher u come from and wher u must go in redirect
490     check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
491     flags   =>$data{'flags'},   
492     "op$op"   => 1,
493     nodouble  => $nodouble,
494     borrowernumber  => $borrowernumber,#register number
495     "contacttitle_".$data{'contacttitle'} => "SELECTED" ,
496     guarantorid => $guarantorid,
497     ethcatpopup => $ethcatpopup,
498     relshiploop => \@relshipdata,
499     citypopup => $citypopup,
500     roadpopup => $roadpopup,  
501     borrotitlepopup => $borrotitlepopup,
502     guarantorinfo   => $guarantorinfo,
503     flagloop  => \@flagdata,
504     dateformat      => display_date_format(),
505     check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
506     modify          => $modify,
507     nok     => $nok,#flag to konw if an error 
508     CGIbranch => $CGIbranch,
509           memberofinstution => $member_of_institution,
510           CGIorganisations => $CGIorganisations,
511     
512     );
513   
514   output_html_with_http_headers $input, $cookie, $template->output;
515 # }
516
517 # Local Variables:
518 # tab-width: 8
519 # End: