added tc_scheduling_priority table, removed pri and notes fields from tc_individual...
[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 #| individual           | int(16) unsigned |      | PRI | NULL    | auto_increment |
112 #| mls_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 #| scheduling_priority  | int(10) unsigned | YES  |     | 30      |                |
118 #| attending            | tinyint(1)       | YES  |     | 0       |                |
119 #| valid                | tinyint(1)       | YES  |     | NULL    |                |
120 #+----------------------+------------------+------+-----+---------+----------------+
121 sub update_tc_individual_table
122 {
123         print "\n-> Updating tc_individual table\n";
124
125         # Set all records to be invalid. Only mark them as valid if they appear on the new list.
126         $sth = $dbh->prepare("update tc_individual set valid=0");
127         $sth->execute or die "-E- DB error: $DBI::errstr\n";
128
129         foreach $index (keys %membership_data)
130         {
131                 $hashref = $membership_data{$index};
132                 $id = $membership_data{$index}{'Indiv ID'};
133                 $individual_name = $membership_data{$index}{'Preferred Name'};
134                 $address = $membership_data{$index}{'Street 1'};
135                 if($membership_data{$index}{'Street 2'} ne "") { 
136                         $address .= " " . $membership_data{$index}{'Street 2'};
137                 }
138                 $phone = $membership_data{$index}{'Household Phone'};
139                 $priesthood = $membership_data{$index}{'Priesthood'};
140                 $hhposition = $membership_data{$index}{'HH Position'};
141                 $organization = $organization_by_id{$id};
142                 $attending = 0;
143                 if(($organization =~ /Elders/) ||
144                    ($organization =~ /Young Men/) ||
145                    ($organization =~ /Sunday School/) ||
146                    ($organization =~ /Primary/)
147                    ) { $attending = 1; }
148                 if($phone =~ /(\d\d\d-\d\d\d\d)/) { $phone = "$areacode-$1"; }
149                 if($phone =~ /^\(\d\d\d\) (\d\d\d-\d\d\d\d)/) { $phone = "$1-$2"; }
150                 $email = $membership_data{$index}{'indiv E-mail'};
151                 if ($email eq "") { $email = $membership_data{$index}{'Household E-mail'}; }
152                 $sth = $dbh->prepare("select * from tc_individual where name=\"$individual_name\"");
153                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
154                 my @data = ();
155                 while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
156                 my $rows = scalar @data;
157                 if($rows == 0) {
158                         # No existing records found for this individual, make a new entry
159                         print "   Adding new individual: $individual_name\n";
160                         $sth = $dbh->prepare("insert into tc_individual values (NULL,'$id',\"$individual_name\",'$address','$phone','$email','','$hhposition','$priesthood',NULL,$attending,1)");
161                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
162                 } elsif($rows == 1) {
163                         # An existing record was found for this individual, update it
164                         print "   Updating existing individual: $individual_name\n";
165                         $sth = $dbh->prepare("update tc_individual set valid=1 where name=\"$individual_name\"");
166                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
167                         if($phone ne "") { 
168                                 $sth = $dbh->prepare("update tc_individual set phone='$phone' where name=\"$individual_name\"");
169                         } else {
170                                 $sth = $dbh->prepare("update tc_individual set phone=NULL where name=\"$individual_name\"");
171                         }
172                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
173                         if($address ne "") { 
174                                 $sth = $dbh->prepare("update tc_individual set address='$address' where name=\"$individual_name\"");
175                         } else {
176                                 $sth = $dbh->prepare("update tc_individual set address=NULL where name=\"$individual_name\"");
177                         }
178                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
179                         $sth = $dbh->prepare("update tc_individual set attending='$attending' where name=\"$individual_name\"");
180                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
181                         $sth = $dbh->prepare("update tc_individual set mls_id='$id' where name=\"$individual_name\"");
182                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
183                         $sth = $dbh->prepare("update tc_individual set priesthood='$priesthood' where name=\"$individual_name\"");
184                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
185                         $sth = $dbh->prepare("update tc_individual set email='$email' where name=\"$individual_name\"");
186                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
187                         $sth = $dbh->prepare("update tc_individual set hh_position='$hhposition' where name=\"$individual_name\"");
188                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
189                 } else {
190                         # More than one record was found. Error! This shouldn't happen.
191                         print "   -E- More than one record found ($rows) for individual: $individual_name\n";
192                 }
193         }
194         $sth->finish();
195 }
196
197 # 3RD_CALLING
198 #+--------------+------------------+------+-----+---------+-------+
199 #| Field        | Type             | Null | Key | Default | Extra |
200 #+--------------+------------------+------+-----+---------+-------+
201 #| indiv_id     | int(16) unsigned | YES  |     | NULL    |       |
202 #| name         | varchar(30)      | YES  |     | NULL    |       |
203 #| organization | varchar(30)      | YES  |     | NULL    |       |
204 #| position     | varchar(30)      | YES  |     | NULL    |       |
205 #| sequence     | int(16) unsigned | YES  |     | NULL    |       |
206 #| sustained    | date             | YES  |     | NULL    |       |
207 #+--------------+------------------+------+-----+---------+-------+
208 sub update_tc_calling_table()
209 {
210         print "\n-> Updating tc_calling table\n";
211
212         #print "-> Organization Data Dump\n\n";
213         #&print_hash(\%organization_data);
214
215         # Delete all records from the calling table. We have no history to
216         # save here. Just re-populate with the latest calling information.
217         $sth = $dbh->prepare("delete from tc_calling ");
218         $sth->execute or die "-E- DB error: $DBI::errstr\n";
219
220         foreach $index (keys %organization_data)
221         {
222                 $indiv_id = $organization_data{$index}{'Indiv ID'};
223                 $name = $organization_data{$index}{'Indiv Name'};
224                 $name =~ s/\'/\\'/g; #'
225                 $organization = $organization_data{$index}{'Organization'};
226                 $organization_by_name{$name} = $organization;
227                 $organization_by_id{$indiv_id} = $organization;
228                 $position = $organization_data{$index}{'Position'};
229                 $sequence = $organization_data{$index}{'Org Seq'};
230                 $sustained = $organization_data{$index}{'Sustained'};
231                 $sustained =~ /(\S+) (\d+)/; $month=$1; $year=$2;
232                 if($name eq "") { next; }
233                 print "   Adding new Calling: $name -> $position\n";
234                 $sth = $dbh->prepare("insert into tc_calling values ('$indiv_id','$name','$organization','$position','$sequence','$month $year')");
235                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
236         }
237 }
238
239 # 3RD_DISTRICT
240 #+------------+------------------+------+-----+---------+-------+
241 #| Field      | Type             | Null | Key | Default | Extra |
242 #+------------+------------------+------+-----+---------+-------+
243 #| district   | int(16) unsigned |      | PRI | 0       |       |
244 #| name       | varchar(30)      | YES  |     | NULL    |       |
245 #| supervisor | int(16) unsigned | YES  |     | NULL    |       |
246 #| valid      | tinyint(1)       | YES  |     | NULL    |       |
247 #+------------+------------------+------+-----+---------+-------+
248 sub update_tc_district_table
249 {
250     # Districts should be created by hand. This subroutine only
251     # updates the supervisor's ID in each district.
252     print "\n-> Updating tc_district table\n";
253     $sth = $dbh->prepare("select * from tc_district");
254     $sth->execute or die "-E- DB error: $DBI::errstr\n";
255     while($sqlhashref = $sth->fetchrow_hashref) {
256         $supervisor_name = $sqlhashref->{name};
257         $district = $sqlhashref->{district};
258         $sth2 = $dbh->prepare("select * from tc_individual where name='$supervisor_name'");
259         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
260         $sqlhashref2 = $sth2->fetchrow_hashref;
261         $supervisor_id = $sqlhashref2->{individual};
262         $sth2->finish();
263         $sth2 = $dbh->prepare("update tc_district set supervisor='$supervisor_id' where district='$district'");
264         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
265         $sth2->finish();
266     }
267     $sth->finish();
268 }
269
270 # 3RD_COMPANIONSHIP
271 #+----------------------+------------------+------+-----+---------+-------+
272 #| Field                | Type             | Null | Key | Default | Extra |
273 #+----------------------+------------------+------+-----+---------+-------+
274 #| companionship        | int(16) unsigned |      |     | 0       |       |
275 #| individual           | int(16) unsigned | YES  |     | NULL    |       |
276 #| district             | int(16) unsigned | YES  |     | NULL    |       |
277 #| scheduling_priority  | int(10) unsigned | YES  |     | 30      |       |
278 #| valid                | tinyint(1)       | YES  |     | NULL    |       |
279 #+----------------------+------------------+------+-----+---------+-------+
280 sub update_tc_companionship_table
281 {
282         print "\n-> Updating tc_companionship table\n";
283
284         # First, mark all existing companionships as invalid in case they have been dissolved
285         $sth = $dbh->prepare("update tc_companionship set valid=0");
286         $sth->execute or die "-E- DB error: $DBI::errstr\n";
287
288         foreach $index (keys %hometeaching_data)
289         {
290                 $hashref = $hometeaching_data{$index};
291                 foreach $key (keys %$hashref) {
292                         if($key =~ /Quorum/i && $hometeaching_data{$index}{$key} =~ /Elders/i) {
293                                 foreach $field ("Home Teacher 1","Home Teacher 2") {
294                                         $individual_name = $hometeaching_data{$index}{$field};
295                                         if($individual_name eq "") { next; }
296                                         $sth2 = $dbh->prepare("select * from tc_individual where name='$individual_name'");
297                                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
298                                         $sqlhashref2 = $sth2->fetchrow_hashref;
299                                         $individual = $sqlhashref2->{individual};
300                                         $id = $hometeaching_data{$index}{'Comp ID'};
301                                         $district = $hometeaching_data{$index}{'HT District'};
302                                         $sth = $dbh->prepare("select * from tc_companionship where individual='$individual' and companionship='$id'");
303                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
304                                         my @data = ();
305                                         while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
306                                         my $rows = scalar @data;
307                                         if($rows == 0) {
308                                                 # No existing records found for this companionship, make a new entry
309                                                 print "   Adding Companion to companionship: $individual_name -> $id\n";
310                                                 $sth = $dbh->prepare("insert into tc_companionship values ($id,'$individual','$district',NULL,1)");
311                                                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
312                                         } else {
313                                                 # An existing companionship was found for this companionship, update it
314                                                 $sth2 = $dbh->prepare("select * from tc_companionship where district='$district' and companionship='$id'");
315                                                 $sth2->execute or die "-E- DB error: $DBI::errstr\n";
316                                                 print "   Updating Companionship with individual: $individual_name ($individual) -> $id\n";
317                                                 $sth = $dbh->prepare("update tc_companionship set district='$district' where individual='$individual' and companionship='$id'");
318                                                 $sth->execute or die "-E- DB error 'district': $DBI::errstr\n";
319                                                 $sth = $dbh->prepare("update tc_companionship set individual='$individual' where individual='$individual' and companionship='$id'");
320                                                 $sth->execute or die "-E- DB error 'individual': $DBI::errstr\n";
321                                                 $sth = $dbh->prepare("update tc_companionship set valid=1 where individual='$individual' and companionship='$id'");
322                                                 $sth->execute or die "-E- DB error 'valid': $DBI::errstr\n";
323                                         }
324                                         $sth->finish();
325                                         $sth2->finish();                    
326                                 }
327                         }
328                 }
329         }
330 }
331
332 # 3RD_FAMILY
333 #+----------------------+------------------+------+-----+---------+-------+
334 #| Field                | Type             | Null | Key | Default | Extra |
335 #+----------------------+------------------+------+-----+---------+-------+
336 #| family               | int(16) unsigned |      | PRI | 0       |   A   |
337 #| hofh_id              | int(16) unsigned | YES  |     | NULL    |       |
338 #| name                 | varchar(30)      | YES  |     | NULL    |       |
339 #| name_id              | varchar(30)      | YES  |     | NULL    |       |
340 #| individual           | int(16) unsigned | YES  |     | NULL    |       |
341 #| companionship        | int(16) unsigned | YES  |     | NULL    |       |
342 #| scheduling_priority  | int(10) unsigned | YES  |     | 30      |       |
343 #| valid                | tinyint(1)       | YES  |     | NULL    |       |
344 #+----------------------+------------------+------+-----+---------+-------+
345 sub update_tc_family_table
346 {
347         print "\n-> Updating tc_family table\n";
348
349         # Set all records to be invalid. Only mark them as valid if they appear on the new list.
350         $sth = $dbh->prepare("update tc_family set valid=0");
351         $sth->execute or die "-E- DB error: $DBI::errstr\n";
352         $sth = $dbh->prepare("update tc_family set companionship=0");
353         $sth->execute or die "-E- DB error: $DBI::errstr\n";
354
355         foreach $index (keys %membership_data)
356         {
357                 $hashref = $membership_data{$index};
358                 foreach $key (keys %$hashref) {
359                         if($key =~ /HH Position/i && $membership_data{$index}{$key} =~ /Head of Household/i) {
360                                 $family_name = $membership_data{$index}{'Preferred Name'};
361                                 $family_name =~ s/\'/\\'/g; #'
362                                 $id = $membership_data{$index}{'HofH ID'};
363                                 $name_id = uc($family_name);
364
365                                 # Find out how many families match this family's name
366                                 $sth = $dbh->prepare("select * from tc_family where name_id='$name_id'");
367                                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
368                                 my @data = ();
369                                 while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
370                                 my $rows = scalar @data;
371
372                                 if($rows == 0) {
373                                         # No existing records found for this family, make a new entry
374                                         print "   Adding new Family: $family_name\n";
375                                         $sth = $dbh->prepare("insert into tc_family values (NULL,$id,'$family_name','$name_id','0','0',NULL,1)");
376                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
377                                 } elsif($rows == 1) {
378                                         # An existing record was found for this family, update it
379                                         print "   Updating existing family: $family_name\n";
380                                         $sth = $dbh->prepare("update tc_family set hofh_id=$id where name_id='$name_id'");
381                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
382                                         $sth = $dbh->prepare("update tc_family set valid=1 where name_id='$name_id'");
383                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
384                                 } else {
385                                         # More than one record was found. Error! This shouldn't happen.
386                                         print "   -E- More than one record found ($rows) for family name: $family_name\n";
387                                 }
388
389                                 # Now update the individual field for this family
390                                 $sth = $dbh->prepare("select * from tc_individual WHERE name='$family_name'");
391                                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
392                                 while($sqlhashref = $sth->fetchrow_hashref) {
393                                         $individual = $sqlhashref->{individual};
394                                         print "   Updating family individual: $family_name -> $individual\n";
395                                         $sth = $dbh->prepare("update tc_family set individual=$individual where name_id='$name_id'");
396                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
397                                 }
398
399                                 # Now update the hometeaching field for this family
400                                 foreach $index (keys %hometeaching_data)
401                                 {
402                                         $hashref = $hometeaching_data{$index};
403                                         foreach $key (keys %$hashref) {
404                                                 if($hometeaching_data{$index}{'Household'} =~ /(\S+)\s+(\S+),\s+(\S+)\s+(.*)/) {
405                                                         $a = $1; $b = $2; $c = $3; $d = $4;
406                                                         if($family_name =~ /$a/ && $hometeaching_data{$index}{'Household'} !~ /$family_name/i) { 
407                                                                 print "I: Adjusting hometeaching match from: $hometeaching_data{$index}{'Household'} to $a, $c $d\n";
408                                                                 $hometeaching_data{$index}{'Household'} = "$a, $c $d";
409                                                         }
410                                                 }
411                                                 if($key =~ /Quorum/i &&
412                                                    $hometeaching_data{$index}{$key} =~ /Elders/i &&
413                                                    $hometeaching_data{$index}{'Household'} =~ /$family_name/i &&
414                                                    $data[0]->{companionship} != $hometeaching_data{$index}{'Comp ID'}
415                                                    )
416                                                 {
417                                                         print "   Updating hometeaching assignment for $family_name family\n";
418                                                         $companionship = $hometeaching_data{$index}{'Comp ID'};
419                                                         $sth = $dbh->prepare("update tc_family set companionship='$companionship' where name_id='$name_id'");
420                                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
421                                                 }
422                                         }
423                                 }
424                                 $sth->finish();
425                         }
426                 }
427         }
428 }
429
430 # 3RD_VISIT
431 #+----------------+------------------+------+-----+---------+-------+
432 #| Field          | Type             | Null | Key | Default | Extra |
433 #+----------------+------------------+------+-----+---------+-------+
434 #| visit          | int(16) unsigned |      | PRI | 0       |   A   |
435 #| family         | int(16) unsigned | YES  | UNI | NULL    |       |
436 #| companionship  | int(16) unsigned | YES  |     | NULL    |       |
437 #| date           | date             | YES  |     | NULL    |       |
438 #| notes          | varchar(128)     | YES  |     | NULL    |       |
439 #| visited        | varchar(1)       | YES  |     | NULL    |       |
440 #+----------------+------------------+------+-----+---------+-------+
441 sub update_tc_visit_table
442 {
443         print "\n-> updating tc_visit table\n";
444         
445         my $month_header_retrieved = 0;
446         my $month_header;
447         my @data_months;
448         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);
449         ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
450         my %visit_status = ('X', 'y', '-', 'n', '', '');
451         
452         foreach $index (keys %hometeaching_stats_data)
453         {
454                 $hashref = $hometeaching_stats_data{$index};
455                 #foreach $key (keys %$hashref) {print "$key\n";}
456                 
457                 $family_name = $hometeaching_stats_data{$index}{"Preferred Name"};
458                 print "   Updating visit data: $family_name\n";
459
460                 # get family id from tc_family
461                 $sth = $dbh->prepare("select * from tc_family where name=\"$family_name\" and valid=1");
462                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
463                 my @family_data = ();
464                 while($sqlhashref = $sth->fetchrow_hashref) { push(@family_data, $sqlhashref); }
465                 my $family_rows = scalar @family_data;
466                 if($family_rows > 0) { 
467                         $family_id = $family_data[0]->{'family'}; 
468                         $comp_id = $family_data[0]->{'companionship'};
469                 }
470                 else { next; }
471                 #print "family_id = $family_id\n";
472                 #print "comp_id = $comp_id\n";
473                 
474                 # ignore visits that weren't done by the quorum
475                 if ($comp_id == 0) { next; }
476                 
477                 # retrieve the month header if not already done
478                 if ($month_header_retrieved == 0)
479                 {
480                         foreach $key (keys %$hashref) 
481                         {
482                                 if (($key ne "Preferred Name") && ($key ne "Home Teachers"))
483                                 {
484                                         $month_header = $key;
485                                         @data_months = split /\t/, $key;
486                                 }
487                         }
488                         $month_header_retrieved = 1;
489                 }
490                 
491                 # loop through history data
492                 @history = split /\t/, $hometeaching_stats_data{$index}{$month_header};
493                 my $data_year = 1900 + $yearOffset;
494                 my $data_month = $months{$data_months[-1]};
495                 #print "$month_header\n";
496                 #print $hometeaching_stats_data{$index}{$month_header};
497                 #print "\n";
498                 foreach $i (reverse(0..$#history)) {
499                         # went back a calendar year, decrement $data_year
500                         if ($months{$data_months[$i]} > $data_month)
501                         {
502                                 $data_year -= 1;
503                         }
504                         $data_month = $months{$data_months[$i]};
505                         my $visit_date = sprintf("%4d-%02d-01\n", $data_year, $data_month);
506                         #print "$visit_date\n";
507                         my $importing_status = $visit_status{$history[$i]};
508                         #print "importing_status = $importing_status\n";
509                         #print "select * from tc_visit where family=$family_id and companionship=$comp_id and date='$visit_date'\n";
510                         $sth = $dbh->prepare("select * from tc_visit where family=$family_id and companionship=$comp_id and date='$visit_date'");
511                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
512                         my @visit_data = ();
513                         while($sqlhashref = $sth->fetchrow_hashref) { push(@visit_data, $sqlhashref); }
514                         my $visit_rows = scalar @visit_data;
515                         if($visit_rows > 0) { 
516                                 my $visited = $visit_data[0]->{'visited'}; 
517                                 #print "visited = $visited\n";
518                                 # update visit if data is different in tc_visit
519                                 if ($visited ne $importing_status)
520                                 {
521                                         #print "importing_status = $importing_status\n";
522                                         $sth = $dbh->prepare("update tc_visit set visited='$importing_status' where family='$family_id' and date='$visit_date' and companionship='$comp_id'");
523                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
524                                 }
525                         } else {
526                                 if ($importing_status ne '')
527                                 {
528                                         # add visit if it doesn't exist in tc_visit
529                                         $sth = $dbh->prepare("insert into tc_visit values (NULL, '$family_id', '$comp_id', '', '', '$visit_date', '', '$importing_status', 'hometeaching')");
530                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
531                                 }
532                         }
533                 }
534         }
535 }
536
537 ######################################################################
538 sub check_for_changed_ids
539 {
540         # If the Indiv ID & HofH ID has changed between data sets, we could have problems
541         my ($oldhashref, $newhashref) = @_;
542         my $found_problem = 0;
543
544         foreach $oldindex (keys %$oldhashref)
545         {
546                 $mls_id = $oldhashref->{$oldindex}{'Indiv ID'};
547                 $hofh_id  = $oldhashref->{$oldindex}{'HofH ID'};
548                 $full_name = $oldhashref->{$oldindex}{'Full Name'};
549                 $hh_position = $oldhashref->{$oldindex}{'HH Position'};
550                 if($hh_position =~ /Other/i) { next; }
551
552                 foreach $newindex (keys %$newhashref)
553                 {
554                         if($newhashref->{$newindex}{'Full Name'} eq $full_name &&
555                            $mls_id != $newhashref->{$newindex}{'Indiv ID'})
556                         {
557                                 print "-W- Indiv ID for $full_name changed from $mls_id to $newhashref->{$newindex}{'Indiv ID'}\n";
558                                 $found_problem = 1;
559                         }
560
561                         if($newhashref->{$newindex}{'Full Name'} eq $full_name &&
562                            $hofh_id != $newhashref->{$newindex}{'HofH ID'})
563                         {
564                                 print "-W- HofH ID for $full_name changed from $hofh_id to $newhashref->{$newindex}{'HofH ID'}\n";
565                                 $found_problem = 1;
566                         }
567                 }
568         }
569
570         return $found_problem;
571 }
572
573 sub update_family_in_tc_individual_table
574 {
575         print "\n-> Updating family info in tc_individual table\n";
576
577         foreach $index (keys %membership_data)
578         {
579                 $hashref = $membership_data{$index};
580
581                 # get some information from hash about this individual
582                 $name = $membership_data{$index}{'Preferred Name'};
583                 $hofh_id = $membership_data{$index}{'HofH ID'};
584
585                 # Find the family id for this individual's HofH_id
586                 $sth = $dbh->prepare("select * from tc_family where hofh_id=$hofh_id and valid=1");
587                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
588                 my @family_data = ();
589                 while($sqlhashref = $sth->fetchrow_hashref) { push(@family_data, $sqlhashref); }
590                 my $family_rows = scalar @family_data;
591                 if($family_rows > 0) { 
592                         $family_id = $family_data[0]->{'family'};
593
594                         print "   Updating family data for: $name\n";
595
596                         # write the family id to the individual's data in tc_individual
597                         $sth = $dbh->prepare("update tc_individual set family='$family_id' where name=\"$name\""); 
598                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
599                 } else {
600                         $family_id = 0; 
601                 }
602         }
603 }
604
605 sub update_organization_class_data
606 {
607         print "\n-> Updating organization class info in tc_individual table\n";
608
609         foreach $index (keys %organization_class_data)
610         {
611                 # get name and organization info for each individual
612                 $name = $organization_class_data{$index}{'Preferred Name'};
613                 $org_class = $organization_class_data{$index}{'Organization Class'};
614
615                 if ($org_class =~ m/Elder/i) {
616                         #print "   $name:  Elder\n";
617                         $sth = $dbh->prepare("update tc_individual set steward='Elder' where name=\"$name\"");
618                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
619                 }
620                 if ($org_class =~ m/High Priest/i) {
621                         #print "   $name:  High Priest\n";
622                         $sth = $dbh->prepare("update tc_individual set steward='High Priest' where name=\"$name\"");
623                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
624                 }
625         }
626 }
627
628 sub update_tc_scheduling_priority_table
629 {
630         print "\n-> Updating scheduling priority table\n";
631         
632         # individuals
633         # TODO: make steward flexible with a setting in the config file
634         $sth = $dbh->prepare("select * from tc_individual where steward='Elder' and valid=1");
635         $sth->execute or die "-E- DB error: $DBI::errstr\n";
636         while($sqlhashref = $sth->fetchrow_hashref) {
637                 $individual = $sqlhashref->{individual};
638                 $scheduling_priority = $sqlhashref->{scheduling_priority};
639                 if ($scheduling_priority == 'NULL')
640                 {
641                         $sth2 = $dbh->prepare("insert into tc_scheduling_priority values (NULL, 30, '')");
642                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
643                         $scheduling_priority = $dbh->last_insert_id(NULL,NULL,'tc_scheduling_priority',NULL);
644                         $sth2 = $dbh->prepare("update tc_individual set scheduling_priority=$scheduling_priority where individual=$individual");
645                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
646                 }
647         }
648         
649         # families
650         # TODO: make steward flexible with a setting in the config file
651         $sth = $dbh->prepare("select tf.scheduling_priority, tf.family from tc_family AS tf JOIN tc_individual AS ti ON tf.individual=ti.individual and ti.steward='Elder' and tf.valid=1");
652         $sth->execute or die "-E- DB error: $DBI::errstr\n";
653         while($sqlhashref = $sth->fetchrow_hashref) {
654                 $family = $sqlhashref->{family};
655                 $scheduling_priority = $sqlhashref->{scheduling_priority};
656                 #print "$family   $scheduling_priority\n";
657                 if ($scheduling_priority == 'NULL')
658                 {
659                         $sth2 = $dbh->prepare("insert into tc_scheduling_priority values (NULL, 30, '')");
660                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
661                         $scheduling_priority = $dbh->last_insert_id(NULL,NULL,'tc_scheduling_priority',NULL);
662                         $sth2 = $dbh->prepare("update tc_family set scheduling_priority=$scheduling_priority where family=$family");
663                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
664                 }
665         }
666         
667         # companionships
668         # TODO: make steward flexible with a setting in the config file
669         $sth = $dbh->prepare("select tc.individual, tc.scheduling_priority from tc_companionship AS tc JOIN tc_individual AS ti ON tc.individual=ti.individual and (ti.steward='Elder' or ti.steward='') and tc.valid=1");
670         $sth->execute or die "-E- DB error: $DBI::errstr\n";
671         while($sqlhashref = $sth->fetchrow_hashref) {
672                 $individual = $sqlhashref->{individual};
673                 $scheduling_priority = $sqlhashref->{scheduling_priority};
674                 #print "$individual   $scheduling_priority\n";
675                 if ($scheduling_priority == 'NULL')
676                 {
677                         $sth2 = $dbh->prepare("insert into tc_scheduling_priority values (NULL, 30, '')");
678                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
679                         $scheduling_priority = $dbh->last_insert_id(NULL,NULL,'tc_scheduling_priority',NULL);
680                         $sth2 = $dbh->prepare("update tc_companionship set scheduling_priority=$scheduling_priority where individual=$individual");
681                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
682                 }
683         }
684         
685 }
686
687 ######################################################################
688 # MAIN
689 ######################################################################
690
691 ###################################################
692 # Open a connection to the database
693 $dbh=DBI->connect("dbi:mysql:dbname=$dbname:host=$dbhost:port=$dbport",$dbuser,$dbpass,{
694     AutoCommit=>0,
695     PrintError=>0}) or print "Connect Failure:".$DBI::errstr."\n" and exit 2;
696
697 ###################################################
698 # Check old directory against new directory to ensure
699 # that the Indiv ID & HofH ID have not changed between updates
700 if(defined $opt_o) {
701         print "-> Comparing old data files to new ones: $opt_o => $opt_n\n";
702         my %old_membership_data = ();
703         my %new_membership_data = ();
704         &csv_to_hash("$opt_o/Membership.csv",\%old_membership_data);
705         &csv_to_hash("$opt_n/Membership.csv",\%new_membership_data);
706
707         $changed_ids=&check_for_changed_ids(\%old_membership_data, \%new_membership_data);
708
709         if($changed_ids) {
710                 print "\n";
711                 print "-E- Some Indiv IDs and HofH IDs have changed for Head of Households between \n";
712                 print "    $opt_o and $opt_n data sets.\n";
713                 print "    This script is not currently setup to handle this properly.\n";
714                 print "\n";
715                 print "    Exiting without updating...\n\n";
716                 exit;
717         }
718 }
719
720 ###################################################
721 # Process command line options
722 if(defined $opt_n) { $datadir = $opt_n; }
723 else { $datadir = shift(@ARGV); }
724 print "\n-> Processing all ward data files in $datadir\n";
725
726 ###################################################
727 # Parse Ward Data Files
728 &csv_to_hash("$datadir/Organization\ class\ per\ member.csv", \%organization_class_data);
729 &csv_to_hash("$datadir/Membership.csv",\%membership_data);
730 &csv_to_hash("$datadir/HomeTeaching.csv",\%hometeaching_data);
731 &csv_to_hash("$datadir/Organization.csv",\%organization_data);
732 &optional_csv_to_hash("$datadir/Home\ Teacher\ per\ Companionship.csv", \%hometeaching_stats_data);
733 %organization_by_name = ();
734 %organization_by_id = ();
735
736 if($opt_v) {
737         print "-> Membership Data Dump\n\n";
738         &print_hash(\%membership_data);
739         print "-> HomeTeaching Data Dump\n\n";
740         &print_hash(\%hometeaching_data);
741         print "-> Organization Data Dump\n\n";
742         &print_hash(\%organization_data);
743         print "-> HomeTeaching Stats Data Dump\n\n";
744         &print_hash(\%hometeaching_stats_data);
745 }
746
747 if($opt_s) { $dbh->disconnect(); exit; }
748
749 # Now update the various eq DB tables
750 &update_tc_calling_table();
751 &update_tc_individual_table();
752 &update_tc_district_table();
753 &update_tc_companionship_table();
754 &update_tc_family_table();
755 &update_tc_visit_table();
756 &update_family_in_tc_individual_table();
757 &update_organization_class_data();
758 &update_tc_scheduling_priority_table();
759
760 print "\n-> Import Successful! DONE...\n";
761
762 ###################################################
763 # Disconnect from the database
764 $dbh->disconnect();
765
766 ######################################################################
767
768