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