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