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