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