Code to display list of organisations/institutions if memberofinstitution is set...
[koha.git] / members / memberentry.pl
1 #!/usr/bin/perl
2 # $Id$
3
4 # Copyright 2006 SAN OUEST PROVENCE et Paul POULAIN
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along with
18 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
19 # Suite 330, Boston, MA  02111-1307 USA
20
21 # pragma
22 use strict;
23
24 # external modules
25 use Date::Calc qw/Today/;
26 use CGI;
27 use HTML::Template;
28 use Date::Manip;
29 use Digest::MD5 qw(md5_base64);
30
31 # internal modules
32 use C4::Auth;
33 use C4::Context;
34 use C4::Output;
35 use C4::Interface::CGI::Output;
36 use C4::Search;
37 use C4::Members;
38 use C4::Koha;
39 use C4::Date;
40 use C4::Input;
41 use C4::Log;
42
43 my $input = new CGI;
44 my %data;
45
46
47 my $dbh = C4::Context->dbh;
48
49 my $category_type = $input->param('category_type') || die "NO CATEGORY_TYPE !"; # A, E, C, or P
50 my $step=$input->param('step') || 0;
51 my ($template, $loggedinuser, $cookie)
52     = get_template_and_user({template_name => "members/memberentry$category_type.tmpl",
53                              query => $input,
54                              type => "intranet",
55                              authnotrequired => 0,
56                              flagsrequired => {borrowers => 1},
57                              debug => 1,
58                              });
59
60 my $borrowerid=$input->param('borrowerid');
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 $categorycode=$input->param('categorycode');
68 my $destination=$input->param('destination');
69 my $cardnumber=$input->param('cardnumber');
70 my $check_member=$input->param('check_member');
71 my $name_city=$input->param('name_city');
72 my $nodouble=$input->param('nodouble');
73 my $select_city=$input->param('select_city');
74 my $nok=$input->param('nok');
75
76 my @errors;
77
78 # $check_categorytype contains the value of duplicate borrowers category type to redirect in good template in step =2
79 my $check_categorytype=$input->param('check_categorytype');
80 # NOTE: Alert for ethnicity and ethnotes fields, they are unvalided in all borrowers form
81
82
83 #function  to automatic setup the mandatory  fields (visual with css)
84 my $check_BorrowerMandatoryField=C4::Context->preference("BorrowerMandatoryField");
85 my @field_check=split(/\|/,$check_BorrowerMandatoryField);
86 foreach (@field_check) {
87 $template->param( "mandatory$_" => 1);          
88 }       
89
90 $template->param( "checked" => 1) if ($nodouble eq 1);
91
92
93 # if a add or modify is requested => check validity of data.
94 if ($op eq 'add' or $op eq 'modify') {
95         my @names=$input->param;
96         foreach my $key (@names){
97                 $data{$key}=$input->param($key)||'';
98                 $data{$key}=~ s/\'/\\\'/g;
99                 $data{$key}=~ s/\"/\\\"/g;
100         }
101
102         #############test for member being unique #############
103         if ($op eq 'add' && $step eq 2){
104                 (my $category_type_send=$category_type ) if ($category_type eq 'I'); 
105                 my $check_category; # recover the category code of the doublon suspect borrowers
106            ($check_member,$check_category)= checkuniquemember($category_type_send,$data{'surname'},$data{'firstname'},format_date_in_iso($data{'dateofbirth'}));
107 #       recover the category type if the borrowers is a duplicate
108         ($check_categorytype,undef)=getcategorytype($check_category);
109         }
110
111 # CHECKS step by step
112 # STEP 1
113         if ($step eq 1) {
114                 ###############test to take the right zipcode and city name ##############
115                 if ($category_type ne 'I' and $guarantorid){
116                         my ($borrower_city,$borrower_zipcode)=&getzipnamecity($select_city);
117                         $data{'city'}= $borrower_city;
118                         $data{'zipcode'}=$borrower_zipcode;
119                 }
120                 if ($category_type eq 'C' and $guarantorid){
121                         my $guarantordata=getguarantordata($guarantorid);
122                         if (($data{'contactname'} eq '' or $data{'contactname'} ne $guarantordata->{'surname'})) {
123                                 $data{'contactfirstname'}=$guarantordata->{'firstname'};        
124                                 $data{'contactname'}=$guarantordata->{'surname'};
125                                 $data{'contacttitle'}=$guarantordata->{'title'};
126                                 $data{'streetnumber'}=$guarantordata->{'streetnumber'};
127                                 $data{'address'}=$guarantordata->{'address'};
128                                 $data{'streettype'}=$guarantordata->{'streettype'};
129                                 $data{'address2'}=$guarantordata->{'address2'};
130                                 $data{'zipcode'}=$guarantordata->{'zipcode'};
131                                 $data{'city'}=$guarantordata->{'city'};
132                                 $data{'phone'}=$guarantordata->{'phone'};
133                                 $data{'phonepro'}=$guarantordata->{'phonepro'};
134                                 $data{'mobile'}=$guarantordata->{'mobile'};
135                                 $data{'fax'}=$guarantordata->{'fax'};
136                                 $data{'email'}=$guarantordata->{'email'};
137                                 $data{'emailpro'}=$guarantordata->{'emailpro'};
138                         }
139                     }
140                 if ($categorycode ne 'I') {
141                     # is the age of the borrower compatible with age limitations of
142                     # the borrower category
143                     my $query = '
144 SELECT upperagelimit,
145        dateofbirthrequired
146   FROM categories
147   WHERE categorycode = ?
148 ';
149                     my $sth=$dbh->prepare($query);
150                     $sth->execute($categorycode);
151                     my $category_info = $sth->fetchrow_hashref;
152
153                     my $age = get_age(format_date_in_iso($data{dateofbirth}));
154
155                     if ($age > $category_info->{upperagelimit}
156                             or $age < $category_info->{dateofbirthrequired}
157                         ) {
158                         push @errors, 'ERROR_age_limitations';
159                         $nok = 1;
160                     }
161                 }
162         }
163 # STEP 2
164         if ($step eq 2) {
165                         if ( ($data{'login'} eq '')){
166                                 my $onefirstnameletter=substr($data{'firstname'},0,1);
167                                 my $fivesurnameletter=substr($data{'surname'},0,5);
168                                 $data{'login'}=lc($onefirstnameletter.$fivesurnameletter);
169                         }
170                         if ($op eq 'add' and $data{'dateenrolled'} eq ''){
171                                 my $today=today();
172                                 #insert ,in field "dateenrolled" , the current date
173                                 $data{'dateenrolled'}=$today;
174                                 #if date expiry is null u must calculate the value only in this case
175                                 $data{'dateexpiry'} = calcexpirydate($data{'categorycode'},$today);
176                         }
177                         if ($op eq 'modify' ){
178                         my $today=today();
179 #                       if date expiry is null u must calculate the value only in this case
180                         if ($data{'dateexpiry'} eq ''){
181                         $data{'dateexpiry'} = calcexpirydate($data{'categorycode'},$today);
182                         }
183                 }
184         }
185 # STEP 3
186         if ($step eq 3) {
187                 # this value show if the login and password are been used
188                 my $loginexist=checkuserpassword($borrowerid,$data{'login'},$data{'password'});
189                 # test to know if u must save or create the borrowers
190                 if ($op eq 'modify'){
191                         # test to know if another user have the same password and same login            
192                         if ($loginexist eq 0) {
193                                 &modmember(%data);              
194                                 logaction($loggedinuser,"MEMBERS","modify member", $borrowerid, "");
195                         }
196                         else {
197                                 push @errors, "ERROR_login_exist";
198                                 $nok=1;
199                         }
200                 }else{
201                         # test to know if another user have the same password and same login     
202                         if ($loginexist) {
203                                 push @errors, "ERROR_login_exist";
204                                 $nok=1;
205                         } else {
206                                 $borrowerid = &newmember(%data);
207                                 logaction($loggedinuser,"MEMBERS","add member", $borrowerid, "");
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=$borrowerid");
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=$borrowerid");
234         print $input->redirect("/cgi-bin/koha/deletemem.pl?member=$borrowernumber");
235 } else {  # this else goes down the whole script
236         # retrieve previous values : either in DB or in CGI, in case of errors in values
237         my $data;
238 # test to now if u add or modify a borrower (modify =>to take all carateristic of the borrowers)
239         if (!$op and !$data{'surname'}) {
240                 $data=borrdata('',$borrowerid);
241                 %data=%$data;
242         }
243         if (C4::Context->preference("IndependantBranches")) {
244                 my $userenv = C4::Context->userenv;
245                 if ($userenv->{flags} != 1 && $data{branchcode}){
246                         unless ($userenv->{branch} eq $data{'branchcode'}){
247                                 print $input->redirect("/cgi-bin/koha/members/members-home.pl");
248                         }
249                 }
250         }
251         if ($op eq 'add'){
252                 $template->param( updtype => 'I');
253         } else {
254                 $template->param( updtype => 'M');
255         }
256         my $cardnumber=$data{'cardnumber'};
257         $cardnumber=fixup_cardnumber($data{'cardnumber'}) if $op eq 'add';
258         if ($data{'sex'} eq 'F'){
259                 $template->param(female => 1);
260         }
261         my ($categories,$labels)=ethnicitycategories();
262         my $ethnicitycategoriescount=$#{$categories};
263         my $ethcatpopup;
264         if ($ethnicitycategoriescount>=0) {
265                 $ethcatpopup = CGI::popup_menu(-name=>'ethnicity',
266                                         -id => 'ethnicity',
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         my $default_city;
286         if ($op eq ''){
287         (my $selectcity=&getidcity($data{'city'})) if ($select_city eq '');
288         $default_city=$selectcity;
289         }
290         my($cityid,$name_city)=getcities();
291         $template->param( city_cgipopup => 1) if ($cityid );
292         my $citypopup = CGI::popup_menu(-name=>'select_city',
293                                         -id => 'select_city',
294                                         -values=>$cityid,
295                                         -labels=>$name_city,
296 #                                       -override => 1,
297                                         -default=>$default_city
298                                         );      
299         
300         my $default_roadtype;
301         $default_roadtype=$data{'streettype'} ;
302         my($roadtypeid,$road_type)=getroadtypes();
303         $template->param( road_cgipopup => 1) if ($roadtypeid );
304         my $roadpopup = CGI::popup_menu(-name=>'streettype',
305                                         -id => 'streettype',
306                                         -values=>$roadtypeid,
307                                         -labels=>$road_type,
308                                         -override => 1,
309                                         -default=>$default_roadtype
310                                         );      
311
312         
313         my @relationships = split /,|\|/,C4::Context->preference('BorrowerRelationship');
314         my @relshipdata;
315         while (@relationships) {
316                 my $relship = shift @relationships || '';
317                 my %row = ('relationship' => $relship);
318                 if ($data{'relationship'} eq $relship) {
319                         $row{'selected'}=' selected';
320                 } else {
321                         $row{'selected'}='';
322                 }
323                 push(@relshipdata, \%row);
324         }
325         my %flags = ( 'gonenoaddress' => ['gonenoaddress', 'Adresse Ã©rronée'],
326                       'lost'          => ['lost', 'Carte Perdue'],
327                       'debarred'      => ['debarred', 'Lecteur exclu']);
328
329         my @flagdata;
330         foreach (keys(%flags)) {
331         my $key = $_;
332         my %row =  ('key'   => $key,
333                         'name'  => $flags{$key}[0],
334                         'html'  => $flags{$key}[1]);
335         if ($data{$key}) {
336                 $row{'yes'}=' checked';
337                 $row{'no'}='';
338         } else {
339                 $row{'yes'}='';
340                 $row{'no'}=' checked';
341         }
342         push(@flagdata, \%row);
343         }
344
345         if ($modify){
346         $template->param( modify => 1 );
347         }
348
349         #Convert dateofbirth to correct format
350         $data{'dateofbirth'} = format_date($data{'dateofbirth'});
351         my @branches;
352         my @select_branch;
353         my %select_branches;
354         my $branches=getbranches();
355         my $default;
356         # -----------------------------------------------------
357         #  the value of ip from the branches hash table
358                 my $select_ip;
359         # $ip is the ip of user when is connect to koha 
360                 my $ip = $ENV{'REMOTE_ADDR'};
361         # -----------------------------------------------------
362         foreach my $branch (keys %$branches) {
363                 if ((not C4::Context->preference("IndependantBranches")) || (C4::Context->userenv->{'flags'} == 1)) {
364                         push @select_branch, $branch;
365                         $select_branches{$branch} = $branches->{$branch}->{'branchname'};
366 #                take the ip number from branches "op"
367                         $select_ip = $branches->{$branch}->{'branchip'} || '';
368                                 
369 #               test $select_ip equal $ip to attribute the default value for the scrolling list
370                         if ($select_ip eq $ip)  {
371                                                 $default = $branches->{$branch}->{'branchcode'};
372                                                 }
373                         } else {
374                                 push @select_branch, $branch if ($branch eq C4::Context->userenv->{'branch'});
375                                 $select_branches{$branch} = $branches->{$branch}->{'branchname'} if ($branch eq C4::Context->userenv->{'branch'});
376                                         
377                                 $default = C4::Context->userenv->{'branch'};
378                                         
379                                 }
380         }
381 # --------------------------------------------------------------------------------------------------------
382         my $CGIbranch = CGI::scrolling_list(-id    => 'branchcode',
383                                            -name   => 'branchcode',
384                                            -values => \@select_branch,
385                                            -labels => \%select_branches,
386                                            -size   => 1,
387                                            -multiple =>0,
388                                            -override => 1,      
389                                            -default => $default,
390                                         );
391        my $CGIorganisations;
392        my $member_of_institution;
393        if (C4::Context->preference("memberofinstitution")){
394            my $organisations=get_institutions();
395            my @orgs;
396            my %orgs;
397            foreach my $organisation (keys %$organisations) {
398                push @orgs,$organisation;
399                $orgs{$organisation}=$organisations->{$organisation}->{'surname'};
400            }
401                
402            $member_of_institution=1;
403            
404            $CGIorganisations = CGI::scrolling_list( -name=>'organisations',
405                -values=>\@orgs,
406                -size=>5,
407                -multiple=>'true'
408                -labels=>\%orgs,
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         warn "CITY".$data{city};
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                 borrowerid      => $borrowerid,#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                 login           => $data{'login'},      
500                 password        => $data{'password'},   
501                 opacnotes       => $data{'opacnotes'},  
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                 flagloop        => \@flagdata,
510 #                               "contacttype_".$data{'contacttype'} =>" SELECTED ",
511                 dateformat      => display_date_format(),
512                 check_categorytype =>$check_categorytype,#to recover the category type with checkcategorytype function
513                         modify          => $modify,
514 #                               city_choice       => $city_choice ,#check if the city was selected
515                 nok             => $nok,#flag to konw if an error 
516                 CGIbranch => $CGIbranch,
517                 memberofinstution => $member_of_institution,
518                 CGIorganisations => $CGIorganisations,
519                 );
520         #$template->param(Institution => 1) if ($categorycode eq "I");
521         output_html_with_http_headers $input, $cookie, $template->output;
522 }
523
524 sub get_age {
525     my ($date, $date_ref) = @_;
526
527     if (not defined $date_ref) {
528         $date_ref = sprintf('%04d-%02d-%02d', Today());
529     }
530
531     my ($year1, $month1, $day1) = split /-/, $date;
532     my ($year2, $month2, $day2) = split /-/, $date_ref;
533
534     my $age = $year2 - $year1;
535     if ($month1.$day1 > $month2.$day2) {
536         $age--;
537     }
538
539     return $age;
540 }
541
542 # Local Variables:
543 # tab-width: 8
544 # End: