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