add borrowers_details.pl and borrowers_details.tmpl:
[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                     my $age = get_age(format_date_in_iso($data{dateofbirth}));
163                     if ($age > $category_info->{upperagelimit}
164                             or $age < $category_info->{dateofbirthrequired}
165                         ) {
166                         push @errors, 'ERROR_age_limitations';
167                         $nok = 1;
168                     }
169                 }
170         }
171 # STEP 2
172         if ($step eq 2) {
173                         if ( ($data{'userid'} eq '')){
174                                 my $onefirstnameletter=substr($data{'firstname'},0,1);
175                                 my $fivesurnameletter=substr($data{'surname'},0,5);
176                                 $data{'userid'}=lc($onefirstnameletter.$fivesurnameletter);
177                         }
178                         if ($op eq 'add' and $data{'dateenrolled'} eq ''){
179                                 my $today= sprintf('%04d-%02d-%02d', Today());
180                                 #insert ,in field "dateenrolled" , the current date
181                                 $data{'dateenrolled'}=$today;
182                                 #if date expiry is null u must calculate the value only in this case
183                                 $data{'dateexpiry'} = calcexpirydate($data{'categorycode'},$today);
184                         }
185                         if ($op eq 'modify' ){
186                         my $today= sprintf('%04d-%02d-%02d', Today());
187 #                       if date expiry is null u must calculate the value only in this case
188                         if ($data{'dateexpiry'} eq ''){
189                         $data{'dateexpiry'} = calcexpirydate($data{'categorycode'},$today);
190                         }
191                 }
192         }
193 # STEP 3
194         if ($step eq 3) {
195                 # this value show if the login and password are been used
196                 my $loginexist=checkuserpassword($borrowernumber,$data{'userid'},$data{'password'});
197                 # test to know if u must save or create the borrowers
198                 if ($op eq 'modify'){
199                         # test to know if another user have the same password and same login            
200                         if ($loginexist eq 0) {
201                                 &modmember(%data);              
202                                 logaction($loggedinuser,"MEMBERS","modify member", $borrowernumber, "");
203                         }
204                         else {
205                                 push @errors, "ERROR_login_exist";
206                                 $nok=1;
207                         }
208                 }else{
209                         # test to know if another user have the same password and same login     
210                         if ($loginexist) {
211                                 push @errors, "ERROR_login_exist";
212                                 $nok=1;
213                         } else {
214                                 $borrowerid = &newmember(%data);
215                                 if ($data{'organisations'}){                                
216                                     # need to add the members organisations
217                                     my @orgs=split(/\|/,$data{'organisations'});
218                                     add_member_orgs($borrowerid,\@orgs);
219                                  }
220                                 logaction($loggedinuser,"MEMBERS","add member", $borrowerid, "");
221                         }
222                 }
223
224                 unless ($nok) {
225                         if($destination eq "circ"){
226                                 print $input->redirect("/cgi-bin/koha/circ/circulation.pl?findborrower=$data{'cardnumber'}");
227                         } else {
228                                 if ($loginexist == 0) {
229                                 print $input->redirect("/cgi-bin/koha/members/moremember.pl?bornum=$borrowernumber");
230                                 }
231                         }
232                 }
233         }
234         if (C4::Context->preference("IndependantBranches")) {
235                 my $userenv = C4::Context->userenv;
236                 if ($userenv->{flags} != 1){
237                         unless ($userenv->{branch} eq $data{'branchcode'}){
238                                 push @errors, "ERROR_branch";
239                                 $nok=1;
240                         }
241                 }
242         }
243 }
244
245 if ($delete){
246         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
247 } else {  # this else goes down the whole script
248         # retrieve previous values : either in DB or in CGI, in case of errors in values
249         my $data;
250 # test to now if u add or modify a borrower (modify =>to take all carateristic of the borrowers)
251         if (!$op and !$data{'surname'}) {
252                 $data=borrdata('',$borrowerid);
253                 %data=%$data;
254         }
255         if (C4::Context->preference("IndependantBranches")) {
256                 my $userenv = C4::Context->userenv;
257                 if ($userenv->{flags} != 1 && $data{branchcode}){
258                         unless ($userenv->{branch} eq $data{'branchcode'}){
259                                 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
260                         }
261                 }
262         }
263         if ($op eq 'add'){
264                 $template->param( updtype => 'I');
265         } else {
266                 $template->param( updtype => 'M');
267         }
268         my $cardnumber=$data{'cardnumber'};
269         $cardnumber=fixup_cardnumber($data{'cardnumber'}) if $op eq 'add';
270         if ($data{'sex'} eq 'F'){
271                 $template->param(female => 1);
272         }
273         my ($categories,$labels)=ethnicitycategories();
274         my $ethnicitycategoriescount=$#{$categories};
275         my $ethcatpopup;
276         if ($ethnicitycategoriescount>=0) {
277                 $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
278                                         -id => 'ethnicity',
279                                         -values=>$categories,
280                                         -default=>$data{'ethnicity'},
281                                         -labels=>$labels);
282                 $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
283         }
284         
285         
286         ($categories,$labels)=borrowercategories($category_type,$op);
287         
288         #if u modify the borrowers u must have the right value for is category code
289         
290         (my $default_category=$data{'categorycode'}) if ($op  eq '');
291         my $catcodepopup = CGI::popup_menu(-name=>'categorycode',
292                                         -id => 'categorycode',
293                                         -values=>$categories,
294                                         -default=>$default_category,
295                                         -labels=>$labels);
296         #test in city
297         my $default_city;
298         if ($op eq ''){
299         (my $selectcity=&getidcity($data{'city'})) if ($select_city eq '');
300         $default_city=$selectcity;
301         }
302         my($cityid,$name_city)=getcities();
303         $template->param( city_cgipopup => 1) if ($cityid );
304         my $citypopup = CGI::popup_menu(-name=>'select_city',
305                                         -id => 'select_city',
306                                         -values=>$cityid,
307                                         -labels=>$name_city,
308 #                                       -override => 1,
309                                         -default=>$default_city
310                                         );      
311         
312         my $default_roadtype;
313         $default_roadtype=$data{'streettype'} ;
314         my($roadtypeid,$road_type)=getroadtypes();
315         $template->param( road_cgipopup => 1) if ($roadtypeid );
316         my $roadpopup = CGI::popup_menu(-name=>'streettype',
317                                         -id => 'streettype',
318                                         -values=>$roadtypeid,
319                                         -labels=>$road_type,
320                                         -override => 1,
321                                         -default=>$default_roadtype
322                                         );      
323
324         
325         my @relationships = split /,|\|/,C4::Context->preference('BorrowerRelationship');
326         my @relshipdata;
327         while (@relationships) {
328                 my $relship = shift @relationships || '';
329                 my %row = ('relationship' => $relship);
330                 if ($data{'relationship'} eq $relship) {
331                         $row{'selected'}=' selected';
332                 } else {
333                         $row{'selected'}='';
334                 }
335                 push(@relshipdata, \%row);
336         }
337         my %flags = ( 'gonenoaddress' => ['gonenoaddress', 'Adresse Ã©rronée'],
338                       'lost'          => ['lost', 'Carte Perdue'],
339                       'debarred'      => ['debarred', 'Lecteur exclu']);
340
341         my @flagdata;
342         foreach (keys(%flags)) {
343         my $key = $_;
344         my %row =  ('key'   => $key,
345                         'name'  => $flags{$key}[0],
346                         'html'  => $flags{$key}[1]);
347         if ($data{$key}) {
348                 $row{'yes'}=' checked';
349                 $row{'no'}='';
350         } else {
351                 $row{'yes'}='';
352                 $row{'no'}=' checked';
353         }
354         push(@flagdata, \%row);
355         }
356
357         if ($modify){
358         $template->param( modify => 1 );
359         }
360
361         #Convert dateofbirth to correct format
362         $data{'dateofbirth'} = format_date($data{'dateofbirth'});
363         my @branches;
364         my @select_branch;
365         my %select_branches;
366         my $branches=getbranches();
367         my $default;
368         # -----------------------------------------------------
369         #  the value of ip from the branches hash table
370                 my $select_ip;
371         # $ip is the ip of user when is connect to koha 
372                 my $ip = $ENV{'REMOTE_ADDR'};
373         # -----------------------------------------------------
374         foreach my $branch (keys %$branches) {
375                 if ((not C4::Context->preference("IndependantBranches")) || (C4::Context->userenv->{'flags'} == 1)) {
376                         push @select_branch, $branch;
377                         $select_branches{$branch} = $branches->{$branch}->{'branchname'};
378 #                take the ip number from branches "op"
379                         $select_ip = $branches->{$branch}->{'branchip'} || '';
380                                 
381 #               test $select_ip equal $ip to attribute the default value for the scrolling list
382                         if ($select_ip eq $ip)  {
383                                                 $default = $branches->{$branch}->{'branchcode'};
384                                                 }
385                         } else {
386                                 push @select_branch, $branch if ($branch eq C4::Context->userenv->{'branch'});
387                                 $select_branches{$branch} = $branches->{$branch}->{'branchname'} if ($branch eq C4::Context->userenv->{'branch'});
388                                         
389                                 $default = C4::Context->userenv->{'branch'};
390                                         
391                                 }
392         }
393 # --------------------------------------------------------------------------------------------------------
394         my $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
395                                            -name   => 'branchcode',
396                                            -values => \@select_branch,
397                                            -labels => \%select_branches,
398                                            -size   => 1,
399                                            -multiple =>0,
400                                            -override => 1,      
401                                            -default => $default,
402                                         );
403        my $CGIorganisations;
404        my $member_of_institution;
405        if (C4::Context->preference("memberofinstitution")){
406            my $organisations=get_institutions();
407            my @orgs;
408            my %org_labels;
409            foreach my $organisation (keys %$organisations) {
410                push @orgs,$organisation;
411                $org_labels{$organisation}=$organisations->{$organisation}->{'surname'};
412            }
413            $member_of_institution=1;
414            
415            $CGIorganisations = CGI::scrolling_list( -id => 'organisations',
416                -name     => 'organisations',
417                -labels   => \%org_labels,
418                -values   => \@orgs,
419                -size     => 5,
420                -multiple => 'true'
421
422                
423            );
424        }
425
426
427 # --------------------------------------------------------------------------------------------------------
428         
429         my $CGIsort1 = buildCGIsort("Bsort1","sort1",$data{'sort1'});
430         if ($CGIsort1) {
431                 $template->param(CGIsort1 => $CGIsort1);
432                 $template->param( sort1 => $data{'sort1'});
433         } else {
434                 $template->param( sort1 => $data{'sort1'});
435         }
436         
437         my $CGIsort2 = buildCGIsort("Bsort2","sort2",$data{'sort2'});
438         if ($CGIsort2) {
439                 $template->param(CGIsort2 =>$CGIsort2);
440         } else {
441                 $template->param( sort2 => $data{'sort2'});
442         }
443
444         
445         $data{'opacnotes'} =~ s/\\//g;
446         $data{'borrowernotes'} =~ s/\\//g;
447
448         # increase step to see next page
449         if ($nok) {
450             foreach my $error (@errors) {
451                 $template->param( $error => 1);
452             }
453             $template->param(nok => 1);
454         }
455         else {
456             $step++;
457         }
458
459
460         $template->param(
461                 BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
462                 category_type   => $category_type,#to know the category type of the borrower
463                 select_city     => $select_city,
464                 "step_$step"    => 1,# associate with step to know where u are
465                 step            => $step,
466                 destination     => $destination,#to know wher u come from and wher u must go in redirect
467                 check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
468 #                               flags           =>$data{'flags'},               
469                 "op$op"         => 1,
470 #               op                      => $op,
471                 nodouble        => $nodouble,
472                 borrowernumber  => $borrowernumber,#register number
473                 cardnumber      => $data{'cardnumber'},
474                 surname         => uc($data{'surname'}),
475                 firstname       => ucfirst($data{'firstname'}),
476                 "title_".$data{'title'}   => " SELECTED ",
477                 title           => $data{'title'},
478                 othernames      => $data{'othernames'},
479                 initials        => $data{'initials'},
480                 streetnumber    => $data{'streetnumber'},
481                 streettype      =>$data{'streettype'},
482                 address          => $data{'address'},
483                 address2        => $data{'address2'},   
484                 city            => $data{'city'},
485                 zipcode         => $data{'zipcode'},
486                 email           => $data{'email'},
487                 phone           => $data{'phone'},
488                 mobile          => $data{'mobile'},
489                 fax             => $data{'fax'},
490                 phonepro        => $data{'phonepro'},
491                 emailpro        => $data{'emailpro'},
492                 b_address       => $data{'b_address'},
493                 b_city          => $data{'b_city'},
494                 b_zipcode       => $data{'b_zipcode'},
495                 b_email         => $data{'b_email'},
496                 b_phone        => $data{'b_phone'},
497                 dateofbirth     => $data{'dateofbirth'},
498                 branchcode      => $data{'branchcode'},
499                 catcodepopup    => $catcodepopup,
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($data{'contactfirstname'}),
508                 "contacttitle_".$data{'contacttitle'} => "SELECTED" ,
509                 contacttitle    => $data{'contacttitle'},
510                 guarantorid     => $guarantorid,
511                 ethcatpopup     => $ethcatpopup,
512                 sex             => $data{'sex'},
513                 login           => $data{'login'},      
514                 password        => $data{'password'},   
515                 opacnotes       => $data{'opacnotes'},  
516                 contactnotes    => $data{'contactnotes'},
517                 borrowernotes   => $data{'borrowernotes'},
518                 relshiploop     => \@relshipdata,
519                 relationship    => $data{'relationship'},
520                 citypopup       => $citypopup,
521                 roadpopup       => $roadpopup,  
522                 contacttype     => $data{'contacttype'},
523                 organisations   => $data{'organisations'},
524                 flagloop        => \@flagdata,
525 #               "contacttype_".$data{'contacttype'} =>" SELECTED ",
526                 dateformat      => display_date_format(),
527                 check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
528                 modify          => $modify,
529 #               city_choice       => $city_choice ,#check if the city was selected
530                 nok             => $nok,#flag to konw if an error 
531                 CGIbranch => $CGIbranch,
532                 memberofinstution => $member_of_institution,
533                 CGIorganisations => $CGIorganisations,
534                 );
535         #$template->param(Institution => 1) if ($categorycode eq "I");
536         output_html_with_http_headers $input, $cookie, $template->output;
537 }
538
539 # Local Variables:
540 # tab-width: 8
541 # End: