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