Add Local-use statistical patron category_type
[koha.git] / members / memberentry.pl
1 #!/usr/bin/perl
2
3 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 # pragma
21 use strict;
22
23 # external modules
24 use Date::Calc qw/Today/;
25 use CGI;
26 # use Digest::MD5 qw(md5_base64);
27
28 # internal modules
29 use C4::Auth;
30 use C4::Context;
31 use C4::Output;
32 use C4::Members;
33 use C4::Koha;
34 use C4::Dates qw/format_date format_date_in_iso/;
35 use C4::Input;
36 use C4::Log;
37 use C4::Branch; # GetBranches
38
39 #use Smart::Comments;
40
41 use vars qw($debug);
42
43 BEGIN {
44         $debug = $ENV{DEBUG} || 0;
45 }
46         
47 my $input = new CGI;
48 ($debug) or $debug = $input->param('debug') || 0;
49 my %data;
50
51 my $dbh = C4::Context->dbh;
52
53 my ($template, $loggedinuser, $cookie)
54     = get_template_and_user({template_name => "members/memberentrygen.tmpl",
55            query => $input,
56            type => "intranet",
57            authnotrequired => 0,
58            flagsrequired => {borrowers => 1},
59            debug => ($debug) ? 1 : 0,
60            });
61 my $guarantorid=$input->param('guarantorid');
62 my $borrowernumber=$input->param('borrowernumber');
63 my $actionType=$input->param('actionType') || '';
64 my $modify=$input->param('modify');
65 my $delete=$input->param('delete');
66 my $op=$input->param('op');
67 my $destination=$input->param('destination');
68 my $cardnumber=$input->param('cardnumber');
69 my $check_member=$input->param('check_member');
70 my $name_city=$input->param('name_city');
71 my $nodouble=$input->param('nodouble');
72 my $select_city=$input->param('select_city');
73 my $zipcode=$input->param('zipcode');
74 my $city=$input->param('city');
75 my $nok=$input->param('nok');
76 my $guarantorinfo=$input->param('guarantorinfo');
77 my $step=$input->param('step') || 0;
78 my @errors;
79 my $default_city;
80 # $check_categorytype contains the value of duplicate borrowers category type to redirect in good template in step =2
81 my $check_categorytype=$input->param('check_categorytype');
82 # NOTE: Alert for ethnicity and ethnotes fields, they are invalid in all borrowers form
83 my $borrower_data;
84 my $NoUpdateLogin;
85 my $userenv = C4::Context->userenv;
86
87 $template->param("uppercasesurnames" => C4::Context->preference('uppercasesurnames'));
88
89 # function to designate mandatory fields (visually 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' or $op eq 'save');
98 my $categorycode = $input->param('categorycode') || $borrower_data->{'categorycode'};
99 my $category_type = $input->param('category_type');
100 my $new_c_type = $category_type; #if we have input param, then we've already chosen the cat_type.
101 unless ($category_type or !($categorycode)){
102   my $borrowercategory= GetBorrowercategory($categorycode);
103   $category_type = $borrowercategory->{'category_type'};
104 }
105 $category_type="A" unless $category_type; # FIXME we should display a error message instead of a 500 error !
106
107 # if a add or modify is requested => check validity of data.
108 %data = %$borrower_data if ($borrower_data);
109
110 my %newdata;    # comes from $input->param()
111 if ($op eq 'insert' || $op eq 'modify' || $op eq 'save') {
112     my @names= ($borrower_data && $op ne 'save') ? keys %$borrower_data : $input->param();
113     foreach my $key (@names) {
114         $newdata{$key} = $input->param($key) if (defined $input->param($key));
115         $newdata{$key} =~ s/\"/"/gg unless $key eq 'borrowernotes' or $key eq 'opacnote';
116     }
117         my $dateobject = C4::Dates->new();
118         my $syspref = $dateobject->regexp();            # same syspref format for all 3 dates
119         my $iso     = $dateobject->regexp('iso');       # 
120         foreach (qw(dateenrolled dateexpiry dateofbirth)) {
121                 my $userdate = $newdata{$_} or next;
122                 if ($userdate =~ /$syspref/) {
123                         $newdata{$_} = format_date_in_iso($userdate);   # if they match syspref format, then convert to ISO
124                 } elsif ($userdate =~ /$iso/) {
125                         warn "Date $_ ($userdate) is already in ISO format";
126                 } else {
127                         ($userdate eq '0000-00-00') and warn "Data error: $_ is '0000-00-00'";
128                         $template->param( "ERROR_$_" => 1 );    # else ERROR!
129                         push(@errors,"ERROR_$_");
130                 }
131         }
132   # check permission to modify login info.
133     if (ref($borrower_data) && ($borrower_data->{'category_type'} eq 'S') && ! (C4::Auth::haspermission($dbh,$userenv->{'id'},{'staffaccess'=>1})) )  {
134                 $NoUpdateLogin =1;
135         }
136 }
137
138 #############test for member being unique #############
139 if ($op eq 'insert'){
140         my $category_type_send=$category_type if ($category_type eq 'I'); 
141         my $check_category; # recover the category code of the doublon suspect borrowers
142                         #   ($result,$categorycode) = checkuniquemember($collectivity,$surname,$firstname,$dateofbirth)
143         ($check_member,$check_category) = checkuniquemember(
144                         $category_type_send, 
145                         ($newdata{surname}     ? $newdata{surname}     : $data{surname}    ),
146                         ($newdata{firstname}   ? $newdata{firstname}   : $data{firstname}  ),
147                         ($newdata{dateofbirth} ? $newdata{dateofbirth} : $data{dateofbirth})
148                 );
149           
150   #   recover the category type if the borrowers is a doublon 
151         my $tmpborrowercategory=GetBorrowercategory($check_category);
152         $check_categorytype=$tmpborrowercategory->{'category_type'};
153 }
154
155   #recover all data from guarantor address phone ,fax... 
156 if (($category_type eq 'C' || $category_type eq 'P') and $guarantorid ne '' ){
157   my $guarantordata=GetMember($guarantorid);
158   $guarantorinfo=$guarantordata->{'surname'}." , ".$guarantordata->{'firstname'};
159   if (($data{'contactname'} eq '' or $data{'contactname'} ne $guarantordata->{'surname'})) {
160     $data{'contactfirstname'}= $guarantordata->{'firstname'}; 
161     $data{'contactname'}     = $guarantordata->{'surname'};
162     $data{'contacttitle'}    = $guarantordata->{'title'};  
163           foreach (qw(streetnumber address streettype address2 zipcode city phone phonepro mobile fax email emailpro branchcode)) {
164                 $data{$_} = $guarantordata->{$_};
165         }
166   }
167 }
168
169 ###############test to take the right zipcode and city name ##############
170 if ( $guarantorid eq ''){
171     $newdata{'city'}= $city;
172     $newdata{'zipcode'}=$zipcode; 
173 }
174
175 #builds default userid
176 if ( (defined $newdata{'userid'}) && ($newdata{'userid'} eq '')){
177   my $onefirstnameletter = substr($data{'firstname'},0,1);
178   my  $fivesurnameletter = substr($data{'surname'},0,9);
179   $newdata{'userid'}=lc($onefirstnameletter.$fivesurnameletter);
180 }
181   
182 $debug and warn join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
183 my $loginexist=0;
184 if ($op eq 'save' || $op eq 'insert'){
185   if (checkcardnumber($newdata{cardnumber},$newdata{borrowernumber})){ 
186     push @errors, 'ERROR_cardnumber';
187   } 
188   my $dateofbirthmandatory = (scalar grep {$_ eq "dateofbirth"} @field_check) ? 1 : 0;
189   if ($newdata{dateofbirth} && $dateofbirthmandatory) {
190     my $age = GetAge($newdata{dateofbirth});
191     my $borrowercategory=GetBorrowercategory($newdata{'categorycode'});   
192         my ($low,$high) = ($borrowercategory->{'dateofbirthrequired'}, $borrowercategory->{'upperagelimit'});
193     if (($high && ($age > $high)) or ($age < $low)) {
194       push @errors, 'ERROR_age_limitations';
195           $template->param('ERROR_age_limitations' => "$low to $high");
196     }
197   }
198   if (C4::Context->preference("IndependantBranches")) {
199     if ($userenv && $userenv->{flags} != 1){
200       $debug and print STDERR "  $newdata{'branchcode'} : ".$userenv->{flags}.":".$userenv->{branch};
201       unless (!$newdata{'branchcode'} || $userenv->{branch} eq $newdata{'branchcode'}){
202         push @errors, "ERROR_branch";
203       }
204     }
205   }
206   # Check if the userid is unique
207   unless (Check_Userid($newdata{'userid'},$borrowernumber)) {
208     push @errors, "ERROR_login_exist";
209     $loginexist=1; 
210   }
211 }
212
213 if ($op eq 'modify' || $op eq 'insert'){
214   unless ($newdata{'dateexpiry'}){
215         my $arg2 = $newdata{'dateenrolled'} || sprintf('%04d-%02d-%02d', Today());
216     $newdata{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
217   }
218 }
219
220 ###  Error checks should happen before this line.
221
222 $nok = $nok || scalar(@errors);
223 if ((!$nok) and ($op eq 'insert' or $op eq 'save')){
224         $debug and warn "$op dates: " . join "\t", map {"$_: $newdata{$_}"} qw(dateofbirth dateenrolled dateexpiry);
225         if ($op eq 'insert'){
226                 # we know it's not a duplicate borrowernumber or there would already be an error
227                 $borrowernumber = &AddMember(%newdata);
228                 if ($data{'organisations'}){            
229                         # need to add the members organisations
230                         my @orgs=split(/\|/,$data{'organisations'});
231                         add_member_orgs($borrowernumber,\@orgs);
232                 }
233         } elsif ($op eq 'save'){ 
234                 if ($NoUpdateLogin) {
235                         delete $newdata{'password'};
236                         delete $newdata{'userid'};
237                 }
238                 &ModMember(%newdata);    
239         }
240         print scalar ($destination eq "circ") ? 
241                 $input->redirect("/cgi-bin/koha/circ/circulation.pl?borrowernumber=$borrowernumber") :
242                 $input->redirect("/cgi-bin/koha/members/moremember.pl?borrowernumber=$borrowernumber") ;
243         exit;           # You can only send 1 redirect!  After that, content or other headers don't matter.
244 }
245
246 if ($delete){
247         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
248         exit;           # same as above
249 }
250
251 if ($nok){
252   $op="add" if ($op eq "insert");
253   $op="modify" if ($op eq "save");
254   %data=%newdata; 
255   $template->param( updtype => ($op eq 'add' ?'I':'M'));        # used to check for $op eq "insert"... but we just changed $op!
256   unless ($step){  
257     $template->param( step_1 => 1,step_2 => 1,step_3 => 1);
258   }  
259
260 if (C4::Context->preference("IndependantBranches")) {
261   my $userenv = C4::Context->userenv;
262   if ($userenv->{flags} != 1 && $data{branchcode}){
263     unless ($userenv->{branch} eq $data{'branchcode'}){
264       print $input->redirect("/cgi-bin/koha/members/members-home.pl");
265           exit;
266     }
267   }
268 }
269 if ($op eq 'add'){
270         my $arg2 = $newdata{'dateenrolled'} || sprintf('%04d-%02d-%02d', Today()); 
271         $data{'dateexpiry'} = GetExpiryDate($newdata{'categorycode'},$arg2);
272         $template->param( updtype => 'I',step_1=>1,step_2=>1,step_3=>1);
273         
274
275 if ($op eq "modify")  {
276   $template->param( updtype => 'M',modify => 1 );
277   $template->param( step_1=>1,step_2=>1,step_3=>1) unless $step;
278 }
279 # my $cardnumber=$data{'cardnumber'};
280 $data{'cardnumber'}=fixup_cardnumber($data{'cardnumber'}) if $op eq 'add';
281 if ($data{'sex'} eq 'F'){
282   $template->param(female => 1);
283 } elsif ($data{'sex'} eq 'M'){
284     $template->param(male => 1);
285 } else {
286     $template->param(none => 1);
287 }
288
289 ##Now all the data to modify a member.
290 my ($categories,$labels)=ethnicitycategories();
291   
292 my $ethnicitycategoriescount=$#{$categories};
293 my $ethcatpopup;
294 if ($ethnicitycategoriescount>=0) {
295   $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
296         -id => 'ethnicity',
297         -tabindex=>'',
298         -values=>$categories,
299         -default=>$data{'ethnicity'},
300         -labels=>$labels);
301   $template->param(ethcatpopup => $ethcatpopup); # bad style, has to be fixed
302 }
303
304 my @typeloop;
305 foreach ( ($new_c_type) ? ($new_c_type) : qw(C A S P I X)){
306         my $action="WHERE category_type=?";
307         ($categories,$labels)=GetborCatFromCatType($_,$action);
308         my @categoryloop;
309         foreach my $cat (@$categories){
310                 push @categoryloop,{'categorycode' => $cat,
311                           'categoryname' => $labels->{$cat},
312                           'categorycodeselected' => ($cat eq $borrower_data->{'categorycode'}),
313                 };
314         }
315         my %typehash;
316         $typehash{'typename'}=$_;
317         $typehash{'categoryloop'}=\@categoryloop;
318         push @typeloop,{'typename' => $_,
319           'categoryloop' => \@categoryloop};
320 }  
321 $template->param('typeloop' => \@typeloop);
322
323 # test in city
324 $select_city=getidcity($data{'city'}) if ($guarantorid ne '0');
325 ($default_city=$select_city) if ($step eq 0);
326 if ($select_city eq '' ){
327         $default_city = &getidcity($data{'city'});
328 }
329 my($cityid);
330 ($cityid,$name_city)=GetCities();
331 $template->param( city_cgipopup => 1) if ($cityid );
332 my $citypopup = CGI::popup_menu(-name=>'select_city',
333         -id => 'select_city',
334         -values=>$name_city,
335         -labels=>$name_city,
336         -default=>$default_city,
337         );  
338   
339 my $default_roadtype;
340 $default_roadtype=$data{'streettype'} ;
341 my($roadtypeid,$road_type)=GetRoadTypes();
342   $template->param( road_cgipopup => 1) if ($roadtypeid );
343 my $roadpopup = CGI::popup_menu(-name=>'streettype',
344         -id => 'streettype',
345         -values=>$roadtypeid,
346         -labels=>$road_type,
347         -override => 1,
348         -default=>$default_roadtype
349         );  
350
351 my $default_borrowertitle;
352 $default_borrowertitle=$data{'title'} ;
353 my($borrowertitle)=GetTitles();
354 $template->param( title_cgipopup => 1) if ($borrowertitle);
355 my $borrotitlepopup = CGI::popup_menu(-name=>'title',
356         -id => 'btitle',
357         -values=>$borrowertitle,
358         -override => 1,
359         -default=>$default_borrowertitle
360         );    
361
362 my @relationships = split /,|\|/,C4::Context->preference('BorrowerRelationship');
363 my @relshipdata;
364 while (@relationships) {
365   my $relship = shift @relationships || '';
366   my %row = ('relationship' => $relship);
367   if ($data{'relationship'} eq $relship) {
368     $row{'selected'}=' selected';
369   } else {
370     $row{'selected'}='';
371   }
372   push(@relshipdata, \%row);
373 }
374
375 my %flags = ( 'gonenoaddress' => ['gonenoaddress' ],
376         'lost'          => ['lost'],
377         'debarred'      => ['debarred']);
378
379  
380 my @flagdata;
381 foreach (keys(%flags)) {
382         my $key = $_;
383         my %row =  ('key'   => $key,
384                     'name'  => $flags{$key}[0]);
385         if ($data{$key}) {
386                 $row{'yes'}=' checked';
387                 $row{'no'}='';
388     }
389         else {
390                 $row{'yes'}='';
391                 $row{'no'}=' checked';
392         }
393         push @flagdata,\%row;
394 }
395
396 #get Branches
397 my @branches;
398 my @select_branch;
399 my %select_branches;
400
401 my $onlymine=(C4::Context->preference('IndependantBranches') && 
402               C4::Context->userenv && 
403               C4::Context->userenv->{flags} !=1  && 
404               C4::Context->userenv->{branch}?1:0);
405               
406 my $branches=GetBranches($onlymine);
407 my $default;
408
409 foreach my $branch (sort keys %$branches) {
410     push @select_branch,$branch;
411     $select_branches{$branch} = $branches->{$branch}->{'branchname'};
412     $default = C4::Context->userenv->{'branch'} if (C4::Context->userenv && C4::Context->userenv->{'branch'});
413 }
414 # --------------------------------------------------------------------------------------------------------
415   #in modify mod :default value from $CGIbranch comes from borrowers table
416   #in add mod: default value come from branches table (ip correspendence)
417 $default=$data{'branchcode'}  if ($op eq 'modify' || ($op eq 'add' && $category_type eq 'C'));
418 my $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
419             -name   => 'branchcode',
420             -values => \@select_branch,
421             -labels => \%select_branches,
422             -size   => 1,
423             -override => 1,  
424             -multiple =>0,
425             -default => $default,
426         );
427 my $CGIorganisations;
428 my $member_of_institution;
429 if (C4::Context->preference("memberofinstitution")){
430     my $organisations=get_institutions();
431     my @orgs;
432     my %org_labels;
433     foreach my $organisation (keys %$organisations) {
434         push @orgs,$organisation;
435         $org_labels{$organisation}=$organisations->{$organisation}->{'surname'};
436     }
437     $member_of_institution=1;
438     
439     $CGIorganisations = CGI::scrolling_list( -id => 'organisations',
440         -name     => 'organisations',
441         -labels   => \%org_labels,
442         -values   => \@orgs,
443         -size     => 5,
444         -multiple => 'true'
445
446     );
447 }
448
449
450 # --------------------------------------------------------------------------------------------------------
451
452 my $CGIsort = buildCGIsort("Bsort1","sort1",$data{'sort1'});
453 if ($CGIsort) {
454   $template->param(CGIsort1 => $CGIsort);
455 }
456 $template->param( sort1 => $data{'sort1'});             # shouldn't this be in an "else" statement like the 2nd one?
457
458 $CGIsort = buildCGIsort("Bsort2","sort2",$data{'sort2'});
459 if ($CGIsort) {
460   $template->param(CGIsort2 => $CGIsort);
461 } else {
462   $template->param( sort2 => $data{'sort2'});
463 }
464
465 if ($nok) {
466     foreach my $error (@errors) {
467         $template->param($error) || $template->param( $error => 1);
468     }
469     $template->param(nok => 1);
470 }
471   
472   #Formatting data for display    
473   
474 if ($data{'dateenrolled'} eq ''){
475   my $today = sprintf('%04d-%02d-%02d', Today());       # ISO format
476   $data{'dateenrolled'}=$today;
477 }
478 if (C4::Context->preference('uppercasesurnames')) {
479         $data{'surname'}    =uc($data{'surname'}    );
480         $data{'contactname'}=uc($data{'contactname'});
481 }
482 foreach (qw(dateenrolled dateexpiry dateofbirth)) {
483         $data{$_} = format_date($data{$_});     # back to syspref for display
484         $template->param( $_ => $data{$_});
485 }
486
487 $template->param( "showguarantor"  => ($category_type=~/A|I|S|X/) ? 0 : 1); # associate with step to know where you are
488 $debug and warn "memberentry step: $step";
489 $template->param(%data);
490 $template->param( "step_$step"  => 1) if $step; # associate with step to know where u are
491 $template->param(  step  => $step   ) if $step; # associate with step to know where u are
492 $template->param( debug  => $debug  ) if $debug;
493 $template->param(
494   BorrowerMandatoryField => C4::Context->preference("BorrowerMandatoryField"),#field to test with javascript
495   category_type => $category_type,#to know the category type of the borrower
496   DHTMLcalendar_dateformat => C4::Dates->DHTMLcalendar(),
497   select_city => $select_city,
498   "$category_type"  => 1,# associate with step to know where u are
499   destination   => $destination,#to know wher u come from and wher u must go in redirect
500   check_member    => $check_member,#to know if the borrower already exist(=>1) or not (=>0) 
501   flags   =>$data{'flags'},   
502   "op$op"   => 1,
503   nodouble  => $nodouble,
504   borrowernumber  => $borrowernumber,#register number
505   "contacttitle_".$data{'contacttitle'} => "SELECTED" ,
506   guarantorid => $guarantorid,
507   ethcatpopup => $ethcatpopup,
508   relshiploop => \@relshipdata,
509   citypopup => $citypopup,
510   roadpopup => $roadpopup,  
511   borrotitlepopup => $borrotitlepopup,
512   guarantorinfo   => $guarantorinfo,
513   flagloop  => \@flagdata,
514   dateformat      => C4::Dates->new()->visual(),
515   C4::Context->preference('dateformat') => 1,
516   check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
517   modify          => $modify,
518   nok     => $nok,#flag to konw if an error 
519   CGIbranch => $CGIbranch,
520   memberofinstution => $member_of_institution,
521   CGIorganisations => $CGIorganisations,
522   NoUpdateLogin =>  $NoUpdateLogin
523   );
524   
525 output_html_with_http_headers $input, $cookie, $template->output;
526
527 # Local Variables:
528 # tab-width: 8
529 # End: