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