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