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