97b3fa1729d13af91c520293abffd4ef8faac48f
[eq/.git] / bin / import_ward_data
1 #!/usr/bin/perl
2
3 use DBI;
4 use Getopt::Std;
5
6 $mydir = `cd \$(dirname $0) 2>/dev/null; pwd`; chomp($mydir);
7 unshift @INC,("$mydir/../setup");
8 if( -f "$mydir/../setup/db_config.local") { require "db_config.local"; }
9 else { require "db_config"; }
10
11 %hometeaching_data = ();
12 %membership_data = ();
13 getopts('vsn:o:');
14
15 $monthname2num{'Jan'} = '01';
16 $monthname2num{'Feb'} = '02';
17 $monthname2num{'Mar'} = '03';
18 $monthname2num{'Apr'} = '04';
19 $monthname2num{'May'} = '05';
20 $monthname2num{'Jun'} = '06';
21 $monthname2num{'Jul'} = '07';
22 $monthname2num{'Aug'} = '08';
23 $monthname2num{'Sep'} = '09';
24 $monthname2num{'Oct'} = '10';
25 $monthname2num{'Nov'} = '11';
26 $monthname2num{'Dec'} = '12';
27
28 ######################################################################
29 # SUBROUTINES
30 ######################################################################
31 sub csv_to_hash
32 {
33         my ($filename, $hashref) = @_;
34
35         open(FILE,$filename) || die "-E- Could not open $filename for reading\n";
36
37         my $found_header = 0; my $index = 0;
38         while(<FILE>) {
39                 $line = $_;
40                 @data = split /\",/, $line;
41                 if(!$found_header) { 
42                         @header = @data; 
43                         $found_header = 1; 
44                 } else {
45                         foreach $i (0..$#data-1) {
46                                 $data[$i] =~ s/\"//g;
47                                 $header[$i] =~ s/\"//g;
48                                 $hashref->{$index}{$header[$i]} = $data[$i];
49                                 #print "$index: $i: $header[$i]: $data[$i]\n";
50                         }
51                         $index++;
52                 }
53         }
54
55         close(FILE);
56 }
57
58 sub optional_csv_to_hash
59 {
60         my ($filename, $hashref) = @_;
61
62         my $opened = open(FILE,$filename);
63
64         if ($opened) {
65                 my $found_header = 0; my $index = 0;
66                 while(<FILE>) {
67                         $line = $_;
68                         @data = split /\",/, $line;
69                         if(!$found_header) { 
70                                 @header = @data; 
71                                 $found_header = 1; 
72                         } else {
73                                 foreach $i (0..$#data-1) {
74                                         $data[$i] =~ s/\"//g;
75                                         $header[$i] =~ s/\"//g;
76                                         $hashref->{$index}{$header[$i]} = $data[$i];
77                                         #print "$index: $i: $header[$i]: $data[$i]\n";
78                                 }
79                                 $index++;
80                         }
81                 }
82
83                 close(FILE);
84         }
85         else
86         {
87         print "-W- could not open optional csv file $filename\n";
88         }
89 }
90
91 ######################################################################
92 sub print_hash
93 {
94         my ($hashref) = @_;
95
96         foreach $key (sort {$a <=> $b} keys %$hashref) {
97                 print "Index: $key\n";
98                 foreach $field (keys %{$hashref->{$key}}) {
99                         print "$field: $hashref->{$key}{$field}\n";
100                 }
101                 print "\n";
102         }
103 }
104
105 ######################################################################
106
107 # 3RD_INDIV
108 #+-------------+------------------+------+-----+---------+----------------+
109 #| Field       | Type             | Null | Key | Default | Extra          |
110 #+-------------+------------------+------+-----+---------+----------------+
111 #| indiv       | int(16) unsigned |      | PRI | NULL    | auto_increment |
112 #| mls_indiv_id| int(16) unsigned |      |     | NULL    |                |
113 #| name        | varchar(60)      | YES  |     | NULL    |                |
114 #| phone       | varchar(12)      | YES  |     | NULL    |                |
115 #| email       | varchar(120)     | YES  |     | NULL    |                |
116 #| priesthood  | enum             | YES  |     | NULL    |                |
117 #| ppi_pri     | int(10) unsigned | YES  |     | 1       |                |
118 #| ppi_notes   | varchar(128)     | YES  |     | NULL    |                |
119 #| hti_pri     | int(10) unsigned | YES  |     | 1       |                |
120 #| hti_notes   | varchar(128)     | YES  |     | NULL    |                |
121 #| attending   | tinyint(1)       | YES  |     | 0       |                |
122 #| valid       | tinyint(1)       | YES  |     | NULL    |                |
123 #+-------------+------------------+------+-----+---------+----------------+
124 sub update_tc_individual_table
125 {
126         print "\n-> Updating tc_individual table\n";
127
128         # Set all records to be invalid. Only mark them as valid if they appear on the new list.
129         $sth = $dbh->prepare("update tc_individual set valid=0");
130         $sth->execute or die "-E- DB error: $DBI::errstr\n";
131
132         foreach $index (keys %membership_data)
133         {
134                 $hashref = $membership_data{$index};
135                 $id = $membership_data{$index}{'Indiv ID'};
136                 $indiv_name = $membership_data{$index}{'Preferred Name'};
137                 $address = $membership_data{$index}{'Street 1'};
138                 if($membership_data{$index}{'Street 2'} ne "") { 
139                         $address .= " " . $membership_data{$index}{'Street 2'};
140                 }
141                 $phone = $membership_data{$index}{'Household Phone'};
142                 $priesthood = $membership_data{$index}{'Priesthood'};
143                 $hhposition = $membership_data{$index}{'HH Position'};
144                 $organization = $organization_by_id{$id};
145                 $attending = 0;
146                 if(($organization =~ /Elders/) ||
147                    ($organization =~ /Young Men/) ||
148                    ($organization =~ /Sunday School/) ||
149                    ($organization =~ /Primary/)
150                    ) { $attending = 1; }
151                 if($phone =~ /(\d\d\d-\d\d\d\d)/) { $phone = "$areacode-$1"; }
152                 if($phone =~ /^\(\d\d\d\) (\d\d\d-\d\d\d\d)/) { $phone = "$1-$2"; }
153                 $email = $membership_data{$index}{'indiv E-mail'};
154                 if ($email eq "") { $email = $membership_data{$index}{'Household E-mail'}; }
155                 $sth = $dbh->prepare("select * from tc_individual where name=\"$indiv_name\"");
156                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
157                 my @data = ();
158                 while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
159                 my $rows = scalar @data;
160                 if($rows == 0) {
161                         # No existing records found for this indiv, make a new entry
162                         print "   Adding new indiv: $indiv_name\n";
163                         $sth = $dbh->prepare("insert into tc_individual values (NULL,'$id',\"$indiv_name\",'$address','$phone','$email','','$hhposition','$priesthood','','$default_interview_pri','','$default_interview_pri','',$attending,1)");
164                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
165                 } elsif($rows == 1) {
166                         # An existing record was found for this indiv, update it
167                         print "   Updating existing indiv: $indiv_name\n";
168                         $sth = $dbh->prepare("update tc_individual set valid=1 where name=\"$indiv_name\"");
169                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
170                         if($phone ne "") { 
171                                 $sth = $dbh->prepare("update tc_individual set phone='$phone' where name=\"$indiv_name\"");
172                         } else {
173                                 $sth = $dbh->prepare("update tc_individual set phone=NULL where name=\"$indiv_name\"");
174                         }
175                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
176                         if($address ne "") { 
177                                 $sth = $dbh->prepare("update tc_individual set address='$address' where name=\"$indiv_name\"");
178                         } else {
179                                 $sth = $dbh->prepare("update tc_individual set address=NULL where name=\"$indiv_name\"");
180                         }
181                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
182                         $sth = $dbh->prepare("update tc_individual set attending='$attending' where name=\"$indiv_name\"");
183                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
184                         $sth = $dbh->prepare("update tc_individual set mls_indiv_id='$id' where name=\"$indiv_name\"");
185                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
186                         $sth = $dbh->prepare("update tc_individual set priesthood='$priesthood' where name=\"$indiv_name\"");
187                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
188                         $sth = $dbh->prepare("update tc_individual set email='$email' where name=\"$indiv_name\"");
189                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
190                         $sth = $dbh->prepare("update tc_individual set hh_position='$hhposition' where name=\"$indiv_name\"");
191                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
192                 } else {
193                         # More than one record was found. Error! This shouldn't happen.
194                         print "   -E- More than one record found ($rows) for indiv: $indiv_name\n";
195                 }
196         }
197         $sth->finish();
198 }
199
200 # 3RD_CALLING
201 #+--------------+------------------+------+-----+---------+-------+
202 #| Field        | Type             | Null | Key | Default | Extra |
203 #+--------------+------------------+------+-----+---------+-------+
204 #| indiv_id     | int(16) unsigned | YES  |     | NULL    |       |
205 #| name         | varchar(30)      | YES  |     | NULL    |       |
206 #| organization | varchar(30)      | YES  |     | NULL    |       |
207 #| position     | varchar(30)      | YES  |     | NULL    |       |
208 #| sequence     | int(16) unsigned | YES  |     | NULL    |       |
209 #| sustained    | date             | YES  |     | NULL    |       |
210 #+--------------+------------------+------+-----+---------+-------+
211 sub update_tc_calling_table()
212 {
213         print "\n-> Updating tc_calling table\n";
214
215         #print "-> Organization Data Dump\n\n";
216         #&print_hash(\%organization_data);
217
218         # Delete all records from the calling table. We have no history to
219         # save here. Just re-populate with the latest calling information.
220         $sth = $dbh->prepare("delete from tc_calling ");
221         $sth->execute or die "-E- DB error: $DBI::errstr\n";
222
223         foreach $index (keys %organization_data)
224         {
225                 $indiv_id = $organization_data{$index}{'Indiv ID'};
226                 $name = $organization_data{$index}{'Indiv Name'};
227                 $name =~ s/\'/\\'/g; #'
228                 $organization = $organization_data{$index}{'Organization'};
229                 $organization_by_name{$name} = $organization;
230                 $organization_by_id{$indiv_id} = $organization;
231                 $position = $organization_data{$index}{'Position'};
232                 $sequence = $organization_data{$index}{'Org Seq'};
233                 $sustained = $organization_data{$index}{'Sustained'};
234                 $sustained =~ /(\S+) (\d+)/; $month=$1; $year=$2;
235                 if($name eq "") { next; }
236                 print "   Adding new Calling: $name -> $position\n";
237                 $sth = $dbh->prepare("insert into tc_calling values ('$indiv_id','$name','$organization','$position','$sequence','$month $year')");
238                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
239         }
240 }
241
242 # 3RD_DISTRICT
243 #+------------+------------------+------+-----+---------+-------+
244 #| Field      | Type             | Null | Key | Default | Extra |
245 #+------------+------------------+------+-----+---------+-------+
246 #| district   | int(16) unsigned |      | PRI | 0       |       |
247 #| name       | varchar(30)      | YES  |     | NULL    |       |
248 #| supervisor | int(16) unsigned | YES  |     | NULL    |       |
249 #| valid      | tinyint(1)       | YES  |     | NULL    |       |
250 #+------------+------------------+------+-----+---------+-------+
251 sub update_tc_district_table
252 {
253     # Districts should be created by hand. This subroutine only
254     # updates the supervisor's ID in each district.
255     print "\n-> Updating tc_district table\n";
256     $sth = $dbh->prepare("select * from tc_district");
257     $sth->execute or die "-E- DB error: $DBI::errstr\n";
258     while($sqlhashref = $sth->fetchrow_hashref) {
259         $supervisor_name = $sqlhashref->{name};
260         $district = $sqlhashref->{district};
261         $sth2 = $dbh->prepare("select * from tc_individual where name='$supervisor_name'");
262         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
263         $sqlhashref2 = $sth2->fetchrow_hashref;
264         $supervisor_id = $sqlhashref2->{indiv};
265         $sth2->finish();
266         $sth2 = $dbh->prepare("update tc_district set supervisor='$supervisor_id' where district='$district'");
267         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
268         $sth2->finish();
269     }
270     $sth->finish();
271 }
272
273 # 3RD_COMPANIONSHIP
274 #+---------------+------------------+------+-----+---------+-------+
275 #| Field         | Type             | Null | Key | Default | Extra |
276 #+---------------+------------------+------+-----+---------+-------+
277 #| companionship | int(16) unsigned |      |     | 0       |       |
278 #| indiv         | int(16) unsigned | YES  |     | NULL    |       |
279 #| district      | int(16) unsigned | YES  |     | NULL    |       |
280 #| valid         | tinyint(1)       | YES  |     | NULL    |       |
281 #+---------------+------------------+------+-----+---------+-------+
282 sub update_tc_companionship_table
283 {
284         print "\n-> Updating tc_companionship table\n";
285
286         # First, mark all existing companionships as invalid in case they have been dissolved
287         $sth = $dbh->prepare("update tc_companionship set valid=0");
288         $sth->execute or die "-E- DB error: $DBI::errstr\n";
289
290         foreach $index (keys %hometeaching_data)
291         {
292                 $hashref = $hometeaching_data{$index};
293                 foreach $key (keys %$hashref) {
294                         if($key =~ /Quorum/i && $hometeaching_data{$index}{$key} =~ /Elders/i) {
295                                 foreach $field ("Home Teacher 1","Home Teacher 2") {
296                                         $indiv_name = $hometeaching_data{$index}{$field};
297                                         if($indiv_name eq "") { next; }
298                                         $sth2 = $dbh->prepare("select * from tc_individual where name='$indiv_name'");
299                                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
300                                         $sqlhashref2 = $sth2->fetchrow_hashref;
301                                         $indiv = $sqlhashref2->{indiv};
302                                         $id = $hometeaching_data{$index}{'Comp ID'};
303                                         $district = $hometeaching_data{$index}{'HT District'};
304                                         $sth = $dbh->prepare("select * from tc_companionship where indiv='$indiv' and companionship='$id'");
305                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
306                                         my @data = ();
307                                         while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
308                                         my $rows = scalar @data;
309                                         if($rows == 0) {
310                                                 # No existing records found for this companionship, make a new entry
311                                                 print "   Adding Companion to companionship: $indiv_name -> $id\n";
312                                                 $sth = $dbh->prepare("insert into tc_companionship values ($id,'$indiv','$district',1)");
313                                                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
314                                         } else {
315                                                 # An existing companionship was found for this companionship, update it
316                                                 $sth2 = $dbh->prepare("select * from tc_companionship where district='$district' and companionship='$id'");
317                                                 $sth2->execute or die "-E- DB error: $DBI::errstr\n";
318                                                 print "   Updating Companionship with indiv: $indiv_name ($indiv) -> $id\n";
319                                                 $sth = $dbh->prepare("update tc_companionship set district='$district' where indiv='$indiv' and companionship='$id'");
320                                                 $sth->execute or die "-E- DB error 'district': $DBI::errstr\n";
321                                                 $sth = $dbh->prepare("update tc_companionship set indiv='$indiv' where indiv='$indiv' and companionship='$id'");
322                                                 $sth->execute or die "-E- DB error 'indiv': $DBI::errstr\n";
323                                                 $sth = $dbh->prepare("update tc_companionship set valid=1 where indiv='$indiv' and companionship='$id'");
324                                                 $sth->execute or die "-E- DB error 'valid': $DBI::errstr\n";
325                                         }
326                                         $sth->finish();
327                                         $sth2->finish();                    
328                                 }
329                         }
330                 }
331         }
332 }
333
334 # 3RD_FAMILY
335 #+---------------+------------------+------+-----+---------+-------+
336 #| Field         | Type             | Null | Key | Default | Extra |
337 #+---------------+------------------+------+-----+---------+-------+
338 #| family        | int(16) unsigned |      | PRI | 0       |   A   |
339 #| hofh_id       | int(16) unsigned | YES  |     | NULL    |       |
340 #| name          | varchar(30)      | YES  |     | NULL    |       |
341 #| name_id       | varchar(30)      | YES  |     | NULL    |       |
342 #| individual    | int(16) unsigned | YES  |     | NULL    |       |
343 #| companionship | int(16) unsigned | YES  |     | NULL    |       |
344 #| visit_pri     | int(10) unsigned | YES  |     | 1       |       |
345 #| visit_notes   | varchar(128)     | YES  |     | NULL    |       |
346 #| valid         | tinyint(1)       | YES  |     | NULL    |       |
347 #+---------------+------------------+------+-----+---------+-------+
348 sub update_tc_family_table
349 {
350         print "\n-> Updating tc_family table\n";
351
352         # Set all records to be invalid. Only mark them as valid if they appear on the new list.
353         $sth = $dbh->prepare("update tc_family set valid=0");
354         $sth->execute or die "-E- DB error: $DBI::errstr\n";
355         $sth = $dbh->prepare("update tc_family set companionship=0");
356         $sth->execute or die "-E- DB error: $DBI::errstr\n";
357
358         foreach $index (keys %membership_data)
359         {
360                 $hashref = $membership_data{$index};
361                 foreach $key (keys %$hashref) {
362                         if($key =~ /HH Position/i && $membership_data{$index}{$key} =~ /Head of Household/i) {
363                                 $family_name = $membership_data{$index}{'Preferred Name'};
364                                 $family_name =~ s/\'/\\'/g; #'
365                                 $id = $membership_data{$index}{'HofH ID'};
366                                 $name_id = uc($family_name);
367
368                                 # Find out how many families match this family's name
369                                 $sth = $dbh->prepare("select * from tc_family where name_id='$name_id'");
370                                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
371                                 my @data = ();
372                                 while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
373                                 my $rows = scalar @data;
374
375                                 if($rows == 0) {
376                                         # No existing records found for this family, make a new entry
377                                         print "   Adding new Family: $family_name\n";
378                                         $sth = $dbh->prepare("insert into tc_family values (NULL,$id,'$family_name','$name_id','0','0','$default_visit_pri','',1)");
379                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
380                                 } elsif($rows == 1) {
381                                         # An existing record was found for this family, update it
382                                         print "   Updating existing family: $family_name\n";
383                                         $sth = $dbh->prepare("update tc_family set hofh_id=$id where name_id='$name_id'");
384                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
385                                         $sth = $dbh->prepare("update tc_family set valid=1 where name_id='$name_id'");
386                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
387                                 } else {
388                                         # More than one record was found. Error! This shouldn't happen.
389                                         print "   -E- More than one record found ($rows) for family name: $family_name\n";
390                                 }
391
392                                 # Now update the individual field for this family
393                                 $sth = $dbh->prepare("select * from tc_individual WHERE name='$family_name'");
394                                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
395                                 while($sqlhashref = $sth->fetchrow_hashref) {
396                                         $individual = $sqlhashref->{indiv};
397                                         print "   Updating family individual: $family_name -> $individual\n";
398                                         $sth = $dbh->prepare("update tc_family set individual=$individual where name_id='$name_id'");
399                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
400                                 }
401
402                                 # Now update the hometeaching field for this family
403                                 foreach $index (keys %hometeaching_data)
404                                 {
405                                         $hashref = $hometeaching_data{$index};
406                                         foreach $key (keys %$hashref) {
407                                                 if($hometeaching_data{$index}{'Household'} =~ /(\S+)\s+(\S+),\s+(\S+)\s+(.*)/) {
408                                                         $a = $1; $b = $2; $c = $3; $d = $4;
409                                                         if($family_name =~ /$a/ && $hometeaching_data{$index}{'Household'} !~ /$family_name/i) { 
410                                                                 print "I: Adjusting hometeaching match from: $hometeaching_data{$index}{'Household'} to $a, $c $d\n";
411                                                                 $hometeaching_data{$index}{'Household'} = "$a, $c $d";
412                                                         }
413                                                 }
414                                                 if($key =~ /Quorum/i &&
415                                                    $hometeaching_data{$index}{$key} =~ /Elders/i &&
416                                                    $hometeaching_data{$index}{'Household'} =~ /$family_name/i &&
417                                                    $data[0]->{companionship} != $hometeaching_data{$index}{'Comp ID'}
418                                                    )
419                                                 {
420                                                         print "   Updating hometeaching assignment for $family_name family\n";
421                                                         $companionship = $hometeaching_data{$index}{'Comp ID'};
422                                                         $sth = $dbh->prepare("update tc_family set companionship='$companionship' where name_id='$name_id'");
423                                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
424                                                 }
425                                         }
426                                 }
427                                 $sth->finish();
428                         }
429                 }
430         }
431 }
432
433 # 3RD_VISIT
434 #+----------------+------------------+------+-----+---------+-------+
435 #| Field          | Type             | Null | Key | Default | Extra |
436 #+----------------+------------------+------+-----+---------+-------+
437 #| visit          | int(16) unsigned |      | PRI | 0       |   A   |
438 #| family         | int(16) unsigned | YES  | UNI | NULL    |       |
439 #| companionship  | int(16) unsigned | YES  |     | NULL    |       |
440 #| date           | date             | YES  |     | NULL    |       |
441 #| notes          | varchar(128)     | YES  |     | NULL    |       |
442 #| visited        | varchar(1)       | YES  |     | NULL    |       |
443 #+----------------+------------------+------+-----+---------+-------+
444 sub update_tc_visit_table
445 {
446         print "\n-> updating tc_visit table\n";
447         
448         my $month_header_retrieved = 0;
449         my $month_header;
450         my @data_months;
451         my %months = ('Jan', 1, 'Feb', 2, 'Mar', 3, 'Apr', 4, 'May', 5, 'Jun', 6, 'Jul', 7, 'Aug', 8, 'Sep', 9, 'Oct', 10, 'Nov', 11, 'Dec', 12);
452         ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
453         my %visit_status = ('X', 'y', '-', 'n', '', '');
454         
455         foreach $index (keys %hometeaching_stats_data)
456         {
457                 $hashref = $hometeaching_stats_data{$index};
458                 #foreach $key (keys %$hashref) {print "$key\n";}
459                 
460                 $family_name = $hometeaching_stats_data{$index}{"Preferred Name"};
461                 print "   Updating visit data: $family_name\n";
462
463                 # get family id from tc_family
464                 $sth = $dbh->prepare("select * from tc_family where name=\"$family_name\" and valid=1");
465                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
466                 my @family_data = ();
467                 while($sqlhashref = $sth->fetchrow_hashref) { push(@family_data, $sqlhashref); }
468                 my $family_rows = scalar @family_data;
469                 if($family_rows > 0) { 
470                         $family_id = $family_data[0]->{'family'}; 
471                         $comp_id = $family_data[0]->{'companionship'};
472                 }
473                 else { next; }
474                 #print "family_id = $family_id\n";
475                 #print "comp_id = $comp_id\n";
476                 
477                 # ignore visits that weren't done by the quorum
478                 if ($comp_id == 0) { next; }
479                 
480                 # retrieve the month header if not already done
481                 if ($month_header_retrieved == 0)
482                 {
483                         foreach $key (keys %$hashref) 
484                         {
485                                 if (($key ne "Preferred Name") && ($key ne "Home Teachers"))
486                                 {
487                                         $month_header = $key;
488                                         @data_months = split /\t/, $key;
489                                 }
490                         }
491                         $month_header_retrieved = 1;
492                 }
493                 
494                 # loop through history data
495                 @history = split /\t/, $hometeaching_stats_data{$index}{$month_header};
496                 my $data_year = 1900 + $yearOffset;
497                 my $data_month = $months{$data_months[-1]};
498                 #print "$month_header\n";
499                 #print $hometeaching_stats_data{$index}{$month_header};
500                 #print "\n";
501                 foreach $i (reverse(0..$#history)) {
502                         # went back a calendar year, decrement $data_year
503                         if ($months{$data_months[$i]} > $data_month)
504                         {
505                                 $data_year -= 1;
506                         }
507                         $data_month = $months{$data_months[$i]};
508                         my $visit_date = sprintf("%4d-%02d-01\n", $data_year, $data_month);
509                         #print "$visit_date\n";
510                         my $importing_status = $visit_status{$history[$i]};
511                         #print "importing_status = $importing_status\n";
512                         #print "select * from tc_visit where family=$family_id and companionship=$comp_id and date='$visit_date'\n";
513                         $sth = $dbh->prepare("select * from tc_visit where family=$family_id and companionship=$comp_id and date='$visit_date'");
514                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
515                         my @visit_data = ();
516                         while($sqlhashref = $sth->fetchrow_hashref) { push(@visit_data, $sqlhashref); }
517                         my $visit_rows = scalar @visit_data;
518                         if($visit_rows > 0) { 
519                                 my $visited = $visit_data[0]->{'visited'}; 
520                                 #print "visited = $visited\n";
521                                 # update visit if data is different in tc_visit
522                                 if ($visited ne $importing_status)
523                                 {
524                                         #print "importing_status = $importing_status\n";
525                                         $sth = $dbh->prepare("update tc_visit set visited='$importing_status' where family='$family_id' and date='$visit_date' and companionship='$comp_id'");
526                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
527                                 }
528                         } else {
529                                 if ($importing_status ne '')
530                                 {
531                                         # add visit if it doesn't exist in tc_visit
532                                         $sth = $dbh->prepare("insert into tc_visit values (NULL, '$family_id', '$comp_id', '', '', '$visit_date', '', '$importing_status', 'hometeaching')");
533                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
534                                 }
535                         }
536                 }
537         }
538 }
539
540 ######################################################################
541 sub check_for_changed_ids
542 {
543         # If the Indiv ID & HofH ID has changed between data sets, we could have problems
544         my ($oldhashref, $newhashref) = @_;
545         my $found_problem = 0;
546
547         foreach $oldindex (keys %$oldhashref)
548         {
549                 $mls_indiv_id = $oldhashref->{$oldindex}{'Indiv ID'};
550                 $hofh_id  = $oldhashref->{$oldindex}{'HofH ID'};
551                 $full_name = $oldhashref->{$oldindex}{'Full Name'};
552                 $hh_position = $oldhashref->{$oldindex}{'HH Position'};
553                 if($hh_position =~ /Other/i) { next; }
554
555                 foreach $newindex (keys %$newhashref)
556                 {
557                         if($newhashref->{$newindex}{'Full Name'} eq $full_name &&
558                            $mls_indiv_id != $newhashref->{$newindex}{'Indiv ID'})
559                         {
560                                 print "-W- Indiv ID for $full_name changed from $mls_indiv_id to $newhashref->{$newindex}{'Indiv ID'}\n";
561                                 $found_problem = 1;
562                         }
563
564                         if($newhashref->{$newindex}{'Full Name'} eq $full_name &&
565                            $hofh_id != $newhashref->{$newindex}{'HofH ID'})
566                         {
567                                 print "-W- HofH ID for $full_name changed from $hofh_id to $newhashref->{$newindex}{'HofH ID'}\n";
568                                 $found_problem = 1;
569                         }
570                 }
571         }
572
573         return $found_problem;
574 }
575
576 sub update_family_in_tc_individual_table
577 {
578         print "\n-> Updating family info in tc_individual table\n";
579
580         foreach $index (keys %membership_data)
581         {
582                 $hashref = $membership_data{$index};
583
584                 # get some information from hash about this individual
585                 $name = $membership_data{$index}{'Preferred Name'};
586                 $hofh_id = $membership_data{$index}{'HofH ID'};
587
588                 # Find the family id for this individual's HofH_id
589                 $sth = $dbh->prepare("select * from tc_family where hofh_id=$hofh_id and valid=1");
590                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
591                 my @family_data = ();
592                 while($sqlhashref = $sth->fetchrow_hashref) { push(@family_data, $sqlhashref); }
593                 my $family_rows = scalar @family_data;
594                 if($family_rows > 0) { 
595                         $family_id = $family_data[0]->{'family'};
596
597                         print "   Updating family data for: $name\n";
598
599                         # write the family id to the individual's data in tc_individual
600                         $sth = $dbh->prepare("update tc_individual set family='$family_id' where name=\"$name\""); 
601                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
602                 } else {
603                         $family_id = 0; 
604                 }
605         }
606 }
607
608 sub update_organization_class_data
609 {
610         print "\n-> Updating organization class info in tc_individual table\n";
611
612         foreach $index (keys %organization_class_data)
613         {
614                 # get name and organization info for each individual
615                 $name = $organization_class_data{$index}{'Preferred Name'};
616                 $org_class = $organization_class_data{$index}{'Organization Class'};
617
618                 if ($org_class =~ m/Elder/i) {
619                         #print "   $name:  Elder\n";
620                         $sth = $dbh->prepare("update tc_individual set steward='Elder' where name=\"$name\"");
621                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
622                 }
623                 if ($org_class =~ m/High Priest/i) {
624                         #print "   $name:  High Priest\n";
625                         $sth = $dbh->prepare("update tc_individual set steward='High Priest' where name=\"$name\"");
626                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
627                 }
628         }
629 }
630
631 ######################################################################
632 # MAIN
633 ######################################################################
634
635 ###################################################
636 # Open a connection to the database
637 $dbh=DBI->connect("dbi:mysql:dbname=$dbname:host=$dbhost:port=$dbport",$dbuser,$dbpass,{
638     AutoCommit=>0,
639     PrintError=>0}) or print "Connect Failure:".$DBI::errstr."\n" and exit 2;
640
641 ###################################################
642 # Check old directory against new directory to ensure
643 # that the Indiv ID & HofH ID have not changed between updates
644 if(defined $opt_o) {
645         print "-> Comparing old data files to new ones: $opt_o => $opt_n\n";
646         my %old_membership_data = ();
647         my %new_membership_data = ();
648         &csv_to_hash("$opt_o/Membership.csv",\%old_membership_data);
649         &csv_to_hash("$opt_n/Membership.csv",\%new_membership_data);
650
651         $changed_ids=&check_for_changed_ids(\%old_membership_data, \%new_membership_data);
652
653         if($changed_ids) {
654                 print "\n";
655                 print "-E- Some Indiv IDs and HofH IDs have changed for Head of Households between \n";
656                 print "    $opt_o and $opt_n data sets.\n";
657                 print "    This script is not currently setup to handle this properly.\n";
658                 print "\n";
659                 print "    Exiting without updating...\n\n";
660                 exit;
661         }
662 }
663
664 ###################################################
665 # Process command line options
666 if(defined $opt_n) { $datadir = $opt_n; }
667 else { $datadir = shift(@ARGV); }
668 print "\n-> Processing all ward data files in $datadir\n";
669
670 ###################################################
671 # Parse Ward Data Files
672 &csv_to_hash("$datadir/Organization\ class\ per\ member.csv", \%organization_class_data);
673 &csv_to_hash("$datadir/Membership.csv",\%membership_data);
674 &csv_to_hash("$datadir/HomeTeaching.csv",\%hometeaching_data);
675 &csv_to_hash("$datadir/Organization.csv",\%organization_data);
676 &optional_csv_to_hash("$datadir/Home\ Teacher\ per\ Companionship.csv", \%hometeaching_stats_data);
677 %organization_by_name = ();
678 %organization_by_id = ();
679
680 if($opt_v) {
681         print "-> Membership Data Dump\n\n";
682         &print_hash(\%membership_data);
683         print "-> HomeTeaching Data Dump\n\n";
684         &print_hash(\%hometeaching_data);
685         print "-> Organization Data Dump\n\n";
686         &print_hash(\%organization_data);
687         print "-> HomeTeaching Stats Data Dump\n\n";
688         &print_hash(\%hometeaching_stats_data);
689 }
690
691 if($opt_s) { $dbh->disconnect(); exit; }
692
693 # Now update the various eq DB tables
694 &update_tc_calling_table();
695 &update_tc_individual_table();
696 &update_tc_district_table();
697 &update_tc_companionship_table();
698 &update_tc_family_table();
699 &update_tc_visit_table();
700 &update_family_in_tc_individual_table();
701 &update_organization_class_data();
702
703 print "\n-> Import Successful! DONE...\n";
704
705 ###################################################
706 # Disconnect from the database
707 $dbh->disconnect();
708
709 ######################################################################
710
711