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