a11906b99977bef3d8201971d9be73fd9c5f0f1b
[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 # TC_INDIVIDUAL
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 # TC_CALLING
198 #+--------------+------------------+------+-----+---------+-------+
199 #| Field        | Type             | Null | Key | Default | Extra |
200 #+--------------+------------------+------+-----+---------+-------+
201 #| name         | varchar(30)      | YES  |     | NULL    |       |
202 #| organization | varchar(30)      | YES  |     | NULL    |       |
203 #| position     | varchar(30)      | YES  |     | NULL    |       |
204 #| sustained    | date             | YES  |     | NULL    |       |
205 #+--------------+------------------+------+-----+---------+-------+
206 sub update_tc_calling_table()
207 {
208         print "\n-> Updating tc_calling table\n";
209
210         #print "-> Organization Data Dump\n\n";
211         #&print_hash(\%organization_data);
212
213         # Delete all records from the calling table. We have no history to
214         # save here. Just re-populate with the latest calling information.
215         $sth = $dbh->prepare("delete from tc_calling ");
216         $sth->execute or die "-E- DB error: $DBI::errstr\n";
217
218         foreach $index (keys %organization_data)
219         {
220                 $name = $organization_data{$index}{'Indiv Name'};
221                 $name =~ s/\'/\\'/g; #'
222                 $organization = $organization_data{$index}{'Organization'};
223                 $organization_by_name{$name} = $organization;
224                 $organization_by_id{$indiv_id} = $organization;
225                 $position = $organization_data{$index}{'Position'};
226                 $sustained = $organization_data{$index}{'Sustained'};
227                 $sustained =~ /(\S+) (\d+)/; $month=$1; $year=$2;
228                 if($name eq "") { next; }
229                 print "   Adding new Calling: $name -> $position\n";
230                 $sth = $dbh->prepare("insert into tc_calling values ('$name','$organization','$position','$month $year')");
231                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
232         }
233 }
234
235 # TC_COMPANIONSHIP
236 #+----------------------+------------------+------+-----+---------+-------+
237 #| Field                | Type             | Null | Key | Default | Extra |
238 #+----------------------+------------------+------+-----+---------+-------+
239 #| companionship        | int(16) unsigned |      |     | 0       |       |
240 #| individual           | int(16) unsigned | YES  |     | NULL    |       |
241 #| district             | int(16) unsigned | YES  |     | NULL    |       |
242 #| scheduling_priority  | int(10) unsigned | YES  |     | 30      |       |
243 #| valid                | tinyint(1)       | YES  |     | NULL    |       |
244 #+----------------------+------------------+------+-----+---------+-------+
245 sub update_tc_companionship_table
246 {
247         print "\n-> Updating tc_companionship table\n";
248
249         # First, mark all existing companionships as invalid in case they have been dissolved
250         $sth = $dbh->prepare("update tc_companionship set valid=0");
251         $sth->execute or die "-E- DB error: $DBI::errstr\n";
252
253         foreach $index (keys %hometeaching_data)
254         {
255                 $hashref = $hometeaching_data{$index};
256                 foreach $key (keys %$hashref) {
257                         if($key =~ /Quorum/i && $hometeaching_data{$index}{$key} =~ /Elders/i) {
258                                 foreach $field ("Home Teacher 1","Home Teacher 2") {
259                                         $individual_name = $hometeaching_data{$index}{$field};
260                                         if($individual_name eq "") { next; }
261                                         $sth2 = $dbh->prepare("select * from tc_individual where name='$individual_name'");
262                                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
263                                         $sqlhashref2 = $sth2->fetchrow_hashref;
264                                         $individual = $sqlhashref2->{individual};
265                                         $id = $hometeaching_data{$index}{'Comp ID'};
266                                         $district = $hometeaching_data{$index}{'HT District'};
267                                         $sth = $dbh->prepare("select * from tc_companionship where individual='$individual' and companionship='$id'");
268                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
269                                         my @data = ();
270                                         while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
271                                         my $rows = scalar @data;
272                                         if($rows == 0) {
273                                                 # No existing records found for this companionship, make a new entry
274                                                 print "   Adding Companion to companionship: $individual_name -> $id\n";
275                                                 $sth = $dbh->prepare("insert into tc_companionship values ($id,'$individual','$district',NULL,1)");
276                                                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
277                                         } else {
278                                                 # An existing companionship was found for this companionship, update it
279                                                 $sth2 = $dbh->prepare("select * from tc_companionship where district='$district' and companionship='$id'");
280                                                 $sth2->execute or die "-E- DB error: $DBI::errstr\n";
281                                                 print "   Updating Companionship with individual: $individual_name ($individual) -> $id\n";
282                                                 $sth = $dbh->prepare("update tc_companionship set district='$district' where individual='$individual' and companionship='$id'");
283                                                 $sth->execute or die "-E- DB error 'district': $DBI::errstr\n";
284                                                 $sth = $dbh->prepare("update tc_companionship set individual='$individual' where individual='$individual' and companionship='$id'");
285                                                 $sth->execute or die "-E- DB error 'individual': $DBI::errstr\n";
286                                                 $sth = $dbh->prepare("update tc_companionship set valid=1 where individual='$individual' and companionship='$id'");
287                                                 $sth->execute or die "-E- DB error 'valid': $DBI::errstr\n";
288                                         }
289                                         $sth->finish();
290                                         $sth2->finish();                    
291                                 }
292                         }
293                 }
294         }
295 }
296
297 # TC_FAMILY
298 #+----------------------+------------------+------+-----+---------+-------+
299 #| Field                | Type             | Null | Key | Default | Extra |
300 #+----------------------+------------------+------+-----+---------+-------+
301 #| family               | int(16) unsigned |      | PRI | 0       |   A   |
302 #| individual           | int(16) unsigned | YES  |     | NULL    |       |
303 #| companionship        | int(16) unsigned | YES  |     | NULL    |       |
304 #| scheduling_priority  | int(10) unsigned | YES  |     | 30      |       |
305 #| valid                | tinyint(1)       | YES  |     | NULL    |       |
306 #+----------------------+------------------+------+-----+---------+-------+
307 sub update_tc_family_table
308 {
309         print "\n-> Updating tc_family table\n";
310
311         # Set all records to be invalid. Only mark them as valid if they appear on the new list.
312         $sth = $dbh->prepare("update tc_family set valid=0 and companionship=0");
313         $sth->execute or die "-E- DB error: $DBI::errstr\n";
314
315         # find head of households in tc_individual
316         $sth = $dbh->prepare("SELECT * FROM tc_individual WHERE hh_position='Head of Household' and valid=1");
317         $sth->execute or die "-E- DB error: $DBI::errstr\n";
318         my @individual_data = ();
319         while ($sqlhashref = $sth->fetchrow_hashref) { push(@individual_data, $sqlhashref); }
320         my $individual_count = scalar @individual_data;
321         for($i=0;$i<$individual_count;$i++) {
322                 $individual = $individual_data[$i]{'individual'};
323                 $name = $individual_data[$i]{'name'};
324                 
325                 $sth2 = $dbh->prepare("SELECT * FROM tc_family WHERE individual='$individual'");
326                 $sth2->execute or die "-E- DB error: $DBI::errstr\n";
327                 
328                 my @data = ();
329                 while($sqlhashref2 = $sth2->fetchrow_hashref) { push(@data, $sqlhashref2); }
330                 my $rows = scalar @data;
331
332                 if($rows == 0) {
333                         # No existing records found for this family, make a new entry
334                         print "   Adding new Family: $name\n";
335                         $sth2 = $dbh->prepare("INSERT INTO tc_family VALUES (NULL,'$individual','0',NULL,1)");
336                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
337                 } elsif($rows == 1) {
338                         # An existing record was found for this family, update it
339                         print "   Updating existing family: $name\n";
340                         $sth2 = $dbh->prepare("UPDATE tc_family SET valid='1' WHERE individual='$individual'");
341                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
342                 } else {
343                         # More than one record was found. Error! This shouldn't happen.
344                         print "   -E- More than one record found ($rows) for family name: $name\n";
345                 }
346                 
347                 # Now update the hometeaching field for this family
348                 foreach $index (keys %hometeaching_data)
349                 {
350                         $hashref = $hometeaching_data{$index};
351                         foreach $key (keys %$hashref) {
352                                 if($hometeaching_data{$index}{'Household'} =~ /(\S+)\s+(\S+),\s+(\S+)\s+(.*)/) {
353                                         $a = $1; $b = $2; $c = $3; $d = $4;
354                                         if($name =~ /$a/ && $hometeaching_data{$index}{'Household'} !~ /$name/i) { 
355                                                 print "I: Adjusting hometeaching match from: $hometeaching_data{$index}{'Household'} to $a, $c $d\n";
356                                                 $hometeaching_data{$index}{'Household'} = "$a, $c $d";
357                                         }
358                                 }
359                                 if($key =~ /Quorum/i &&
360                                    $hometeaching_data{$index}{$key} =~ /Elders/i &&
361                                    $hometeaching_data{$index}{'Household'} =~ /$name/i &&
362                                    $data[0]->{companionship} != $hometeaching_data{$index}{'Comp ID'}
363                                   )
364                                 {
365                                         print "   Updating hometeaching assignment for $name family\n";
366                                         $companionship = $hometeaching_data{$index}{'Comp ID'};
367                                         $sth2 = $dbh->prepare("update tc_family set companionship='$companionship' where individual='$individual'");
368                                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
369                                 }
370                         }
371                 }
372                 $sth->finish();
373         }
374 }
375
376 # TC_VISIT
377 #+----------------+------------------+------+-----+---------+-------+
378 #| Field          | Type             | Null | Key | Default | Extra |
379 #+----------------+------------------+------+-----+---------+-------+
380 #| visit          | int(16) unsigned |      | PRI | 0       |   A   |
381 #| family         | int(16) unsigned | YES  | UNI | NULL    |       |
382 #| companionship  | int(16) unsigned | YES  |     | NULL    |       |
383 #| date           | date             | YES  |     | NULL    |       |
384 #| notes          | varchar(128)     | YES  |     | NULL    |       |
385 #| visited        | varchar(1)       | YES  |     | NULL    |       |
386 #+----------------+------------------+------+-----+---------+-------+
387 sub update_tc_visit_table
388 {
389         print "\n-> updating tc_visit table\n";
390         
391         my $month_header_retrieved = 0;
392         my $month_header;
393         my @data_months;
394         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);
395         ($second, $minute, $hour, $dayOfMonth, $month, $yearOffset, $dayOfWeek, $dayOfYear, $daylightSavings) = localtime();
396         my %visit_status = ('X', 'y', '-', 'n', '', '');
397         
398         foreach $index (keys %hometeaching_stats_data)
399         {
400                 $hashref = $hometeaching_stats_data{$index};
401                 #foreach $key (keys %$hashref) {print "$key\n";}
402                 
403                 $family_name = $hometeaching_stats_data{$index}{"Preferred Name"};
404                 print "   Updating visit data: $family_name\n";
405
406                 # get family id from tc_family
407                 $sth = $dbh->prepare("SELECT * FROM tc_family AS tf JOIN tc_individual AS ti WHERE tf.individual=ti.individual AND ti.name=\"$family_name\" AND tf.valid=1");
408                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
409                 my @family_data = ();
410                 while($sqlhashref = $sth->fetchrow_hashref) { push(@family_data, $sqlhashref); }
411                 my $family_rows = scalar @family_data;
412                 if($family_rows > 0) { 
413                         $family_id = $family_data[0]->{'family'}; 
414                         $comp_id = $family_data[0]->{'companionship'};
415                 }
416                 else { next; }
417                 #print "family_id = $family_id\n";
418                 #print "comp_id = $comp_id\n";
419                 
420                 # ignore visits that weren't done by the quorum
421                 if ($comp_id == 0) { next; }
422                 
423                 # retrieve the month header if not already done
424                 if ($month_header_retrieved == 0)
425                 {
426                         foreach $key (keys %$hashref) 
427                         {
428                                 if (($key ne "Preferred Name") && ($key ne "Home Teachers"))
429                                 {
430                                         $month_header = $key;
431                                         @data_months = split /\t/, $key;
432                                 }
433                         }
434                         $month_header_retrieved = 1;
435                 }
436                 
437                 # loop through history data
438                 @history = split /\t/, $hometeaching_stats_data{$index}{$month_header};
439                 my $data_year = 1900 + $yearOffset;
440                 my $data_month = $months{$data_months[-1]};
441                 #print "$month_header\n";
442                 #print $hometeaching_stats_data{$index}{$month_header};
443                 #print "\n";
444                 foreach $i (reverse(0..$#history)) {
445                         # went back a calendar year, decrement $data_year
446                         if ($months{$data_months[$i]} > $data_month)
447                         {
448                                 $data_year -= 1;
449                         }
450                         $data_month = $months{$data_months[$i]};
451                         my $visit_date = sprintf("%4d-%02d-01\n", $data_year, $data_month);
452                         #print "$visit_date\n";
453                         my $importing_status = $visit_status{$history[$i]};
454                         #print "importing_status = $importing_status\n";
455                         #print "select * from tc_visit where family=$family_id and companionship=$comp_id and date='$visit_date'\n";
456                         $sth = $dbh->prepare("select * from tc_visit where family=$family_id and companionship=$comp_id and date='$visit_date'");
457                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
458                         my @visit_data = ();
459                         while($sqlhashref = $sth->fetchrow_hashref) { push(@visit_data, $sqlhashref); }
460                         my $visit_rows = scalar @visit_data;
461                         if($visit_rows > 0) { 
462                                 my $visited = $visit_data[0]->{'visited'}; 
463                                 #print "visited = $visited\n";
464                                 # update visit if data is different in tc_visit
465                                 if ($visited ne $importing_status)
466                                 {
467                                         #print "importing_status = $importing_status\n";
468                                         $sth = $dbh->prepare("update tc_visit set visited='$importing_status' where family='$family_id' and date='$visit_date' and companionship='$comp_id'");
469                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
470                                 }
471                         } else {
472                                 if ($importing_status ne '')
473                                 {
474                                         # add visit if it doesn't exist in tc_visit
475                                         $sth = $dbh->prepare("insert into tc_visit values (NULL, '$family_id', '$comp_id', '', '', '$visit_date', '', '$importing_status', 'hometeaching')");
476                                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
477                                 }
478                         }
479                 }
480         }
481 }
482
483 ######################################################################
484 sub check_for_changed_ids
485 {
486         # If the Indiv ID & HofH ID has changed between data sets, we could have problems
487         my ($oldhashref, $newhashref) = @_;
488         my $found_problem = 0;
489
490         foreach $oldindex (keys %$oldhashref)
491         {
492                 $mls_id = $oldhashref->{$oldindex}{'Indiv ID'};
493                 $hofh_id  = $oldhashref->{$oldindex}{'HofH ID'};
494                 $full_name = $oldhashref->{$oldindex}{'Full Name'};
495                 $hh_position = $oldhashref->{$oldindex}{'HH Position'};
496                 if($hh_position =~ /Other/i) { next; }
497
498                 foreach $newindex (keys %$newhashref)
499                 {
500                         if($newhashref->{$newindex}{'Full Name'} eq $full_name &&
501                            $mls_id != $newhashref->{$newindex}{'Indiv ID'})
502                         {
503                                 print "-W- Indiv ID for $full_name changed from $mls_id to $newhashref->{$newindex}{'Indiv ID'}\n";
504                                 $found_problem = 1;
505                         }
506
507                         if($newhashref->{$newindex}{'Full Name'} eq $full_name &&
508                            $hofh_id != $newhashref->{$newindex}{'HofH ID'})
509                         {
510                                 print "-W- HofH ID for $full_name changed from $hofh_id to $newhashref->{$newindex}{'HofH ID'}\n";
511                                 $found_problem = 1;
512                         }
513                 }
514         }
515
516         return $found_problem;
517 }
518
519 sub update_organization_class_data
520 {
521         print "\n-> Updating organization class info in tc_individual table\n";
522
523         foreach $index (keys %organization_class_data)
524         {
525                 # get name and organization info for each individual
526                 $name = $organization_class_data{$index}{'Preferred Name'};
527                 $org_class = $organization_class_data{$index}{'Organization Class'};
528
529                 if ($org_class =~ m/Elder/i) {
530                         #print "   $name:  Elder\n";
531                         $sth = $dbh->prepare("update tc_individual set steward='Elder' where name=\"$name\"");
532                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
533                 }
534                 if ($org_class =~ m/High Priest/i) {
535                         #print "   $name:  High Priest\n";
536                         $sth = $dbh->prepare("update tc_individual set steward='High Priest' where name=\"$name\"");
537                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
538                 }
539         }
540 }
541
542 sub update_tc_scheduling_priority_table
543 {
544         print "\n-> Updating scheduling priority table\n";
545         
546         # individuals
547         # TODO: make steward flexible with a setting in the config file
548         $sth = $dbh->prepare("select * from tc_individual where steward='Elder' and valid=1");
549         $sth->execute or die "-E- DB error: $DBI::errstr\n";
550         while($sqlhashref = $sth->fetchrow_hashref) {
551                 $individual = $sqlhashref->{individual};
552                 $scheduling_priority = $sqlhashref->{scheduling_priority};
553                 if ($scheduling_priority == 'NULL')
554                 {
555                         $sth2 = $dbh->prepare("insert into tc_scheduling_priority values (NULL, 30, '')");
556                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
557                         $scheduling_priority = $dbh->last_insert_id(NULL,NULL,'tc_scheduling_priority',NULL);
558                         $sth2 = $dbh->prepare("update tc_individual set scheduling_priority=$scheduling_priority where individual=$individual");
559                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
560                 }
561         }
562         
563         # families
564         # TODO: make steward flexible with a setting in the config file
565         $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");
566         $sth->execute or die "-E- DB error: $DBI::errstr\n";
567         while($sqlhashref = $sth->fetchrow_hashref) {
568                 $family = $sqlhashref->{family};
569                 $scheduling_priority = $sqlhashref->{scheduling_priority};
570                 #print "$family   $scheduling_priority\n";
571                 if ($scheduling_priority == 'NULL')
572                 {
573                         $sth2 = $dbh->prepare("insert into tc_scheduling_priority values (NULL, 30, '')");
574                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
575                         $scheduling_priority = $dbh->last_insert_id(NULL,NULL,'tc_scheduling_priority',NULL);
576                         $sth2 = $dbh->prepare("update tc_family set scheduling_priority=$scheduling_priority where family=$family");
577                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
578                 }
579         }
580         
581         # companionships
582         # TODO: make steward flexible with a setting in the config file
583         $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");
584         $sth->execute or die "-E- DB error: $DBI::errstr\n";
585         while($sqlhashref = $sth->fetchrow_hashref) {
586                 $individual = $sqlhashref->{individual};
587                 $scheduling_priority = $sqlhashref->{scheduling_priority};
588                 #print "$individual   $scheduling_priority\n";
589                 if ($scheduling_priority == 'NULL')
590                 {
591                         $sth2 = $dbh->prepare("insert into tc_scheduling_priority values (NULL, 30, '')");
592                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
593                         $scheduling_priority = $dbh->last_insert_id(NULL,NULL,'tc_scheduling_priority',NULL);
594                         $sth2 = $dbh->prepare("update tc_companionship set scheduling_priority=$scheduling_priority where individual=$individual");
595                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
596                 }
597         }
598         
599 }
600
601 ######################################################################
602 # MAIN
603 ######################################################################
604
605 ###################################################
606 # Open a connection to the database
607 $dbh=DBI->connect("dbi:mysql:dbname=$dbname:host=$dbhost:port=$dbport",$dbuser,$dbpass,{
608     AutoCommit=>0,
609     PrintError=>0}) or print "Connect Failure:".$DBI::errstr."\n" and exit 2;
610
611 ###################################################
612 # Check old directory against new directory to ensure
613 # that the Indiv ID & HofH ID have not changed between updates
614 if(defined $opt_o) {
615         print "-> Comparing old data files to new ones: $opt_o => $opt_n\n";
616         my %old_membership_data = ();
617         my %new_membership_data = ();
618         &csv_to_hash("$opt_o/Membership.csv",\%old_membership_data);
619         &csv_to_hash("$opt_n/Membership.csv",\%new_membership_data);
620
621         $changed_ids=&check_for_changed_ids(\%old_membership_data, \%new_membership_data);
622
623         if($changed_ids) {
624                 print "\n";
625                 print "-E- Some Indiv IDs and HofH IDs have changed for Head of Households between \n";
626                 print "    $opt_o and $opt_n data sets.\n";
627                 print "    This script is not currently setup to handle this properly.\n";
628                 print "\n";
629                 print "    Exiting without updating...\n\n";
630                 exit;
631         }
632 }
633
634 ###################################################
635 # Process command line options
636 if(defined $opt_n) { $datadir = $opt_n; }
637 else { $datadir = shift(@ARGV); }
638 print "\n-> Processing all ward data files in $datadir\n";
639
640 ###################################################
641 # Parse Ward Data Files
642 &csv_to_hash("$datadir/Organization\ class\ per\ member.csv", \%organization_class_data);
643 &csv_to_hash("$datadir/Membership.csv",\%membership_data);
644 &csv_to_hash("$datadir/HomeTeaching.csv",\%hometeaching_data);
645 &csv_to_hash("$datadir/Organization.csv",\%organization_data);
646 &optional_csv_to_hash("$datadir/Home\ Teacher\ per\ Companionship.csv", \%hometeaching_stats_data);
647 %organization_by_name = ();
648 %organization_by_id = ();
649
650 if($opt_v) {
651         print "-> Membership Data Dump\n\n";
652         &print_hash(\%membership_data);
653         print "-> HomeTeaching Data Dump\n\n";
654         &print_hash(\%hometeaching_data);
655         print "-> Organization Data Dump\n\n";
656         &print_hash(\%organization_data);
657         print "-> HomeTeaching Stats Data Dump\n\n";
658         &print_hash(\%hometeaching_stats_data);
659 }
660
661 if($opt_s) { $dbh->disconnect(); exit; }
662
663 # Now update the various eq DB tables
664 &update_tc_calling_table();
665 &update_tc_individual_table();
666 &update_tc_companionship_table();
667 &update_tc_family_table();
668 &update_tc_visit_table();
669 &update_organization_class_data();
670 &update_tc_scheduling_priority_table();
671
672 print "\n-> Import Successful! DONE...\n";
673
674 ###################################################
675 # Disconnect from the database
676 $dbh->disconnect();
677
678 ######################################################################
679
680