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