ef7eac4a6cb403645fe1692e92cfb50bb80af0bd
[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     {
40         $line = $_;
41         @data = split /\",/, $line;
42         if(!$found_header) { @header = @data; $found_header = 1; }
43         else {
44             foreach $i (0..$#data-1) {
45                 $data[$i] =~ s/\"//g;
46                 $header[$i] =~ s/\"//g;
47                 $hashref->{$index}{$header[$i]} = $data[$i];
48                 #print "$index: $i: $header[$i]: $data[$i]\n";
49             }
50             $index++;
51         }
52     }
53     
54     close(FILE);
55 }
56
57 ######################################################################
58 sub print_hash
59 {
60     my ($hashref) = @_;
61
62     foreach $key (sort {$a <=> $b} keys %$hashref) {
63         print "Index: $key\n";
64         foreach $field (keys %{$hashref->{$key}}) {
65             print "$field: $hashref->{$key}{$field}\n";
66         }
67         print "\n";
68     }
69 }
70
71 ######################################################################
72
73 # EQ_AARONIC
74 #+-------+--------------------+------+-----+---------+-------+
75 #| Field | Type               | Null | Key | Default | Extra |
76 #+-------+--------------------+------+-----+---------+-------+
77 #| aaronic | int(16) unsigned |      | PRI | 0       |   A   |
78 #| name    | varchar(60)      | YES  |     | NULL    |       |
79 #| phone   | varchar(12)      | YES  |     | NULL    |       |
80 #| valid   | tinyint(1)       | YES  |     | NULL    |       |
81 #+-------+--------------------+------+-----+---------+-------+
82 sub update_eq_aaronic_table
83 {
84     print "\n-> Updating eq_aaronic table\n";
85
86     # Set all records to be invalid. Only mark them as valid if they appear on the new list.
87     $sth = $dbh->prepare("update eq_aaronic set valid=0");
88     $sth->execute or die "-E- DB error: $DBI::errstr\n";
89     
90     foreach $index (keys %membership_data)
91     {
92         $hashref = $membership_data{$index};
93         foreach $key (keys %$hashref) {
94             if($key =~ /Priesthood/i &&
95                ($membership_data{$index}{$key} =~ /^Deacon\s*$/i ||
96                 $membership_data{$index}{$key} =~ /^Teacher\s*$/i ||
97                 $membership_data{$index}{$key} =~ /^Priest\s*$/i)) {
98                 $aaronic_name = $membership_data{$index}{'Preferred Name'};
99                 $phone = $membership_data{$index}{'Phone 1'};
100                 if($phone =~ /(\d\d\d-\d\d\d\d)/) { $phone = "$areacode-$1"; }
101                 if($phone =~ /^\(\d\d\d\) (\d\d\d-\d\d\d\d)/) { $phone = "$1-$2"; }
102                 $sth = $dbh->prepare("select * from eq_aaronic where name='$aaronic_name'");
103                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
104                 my @data = ();
105                 while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
106                 my $rows = scalar @data;
107                 if($rows == 0) {
108                     # No existing records found for this aaronic, make a new entry
109                     print "   Adding new Aaronic: $aaronic_name\n";
110                     $sth = $dbh->prepare("insert into eq_aaronic values (NULL,'$aaronic_name','$phone',1)");
111                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
112                 } elsif($rows == 1) {
113                     # An existing record was found for this aaronic, update it, mark it valid!
114                     print "   Updating existing aaronic: $aaronic_name\n";
115                     $sth = $dbh->prepare("update eq_aaronic set phone='$phone' where name='$aaronic_name'");
116                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
117                     $sth = $dbh->prepare("update eq_aaronic set valid=1 where name='$aaronic_name'");
118                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
119                 } else {
120                     # More than one record was found. Error! This shouldn't happen.
121                     print "   -E- More than one record found ($rows) for aaronic name: $aaronic_name\n";
122                 }
123             }
124         }
125     }
126     $sth->finish();
127 }
128
129 # EQ_ELDER
130 #+-------------+------------------+------+-----+---------+----------------+
131 #| Field       | Type             | Null | Key | Default | Extra          |
132 #+-------------+------------------+------+-----+---------+----------------+
133 #| elder       | int(16) unsigned |      | PRI | NULL    | auto_increment |
134 #| indiv_id    | int(16) unsigned |      |     | NULL    |                |
135 #| name        | varchar(60)      | YES  |     | NULL    |                |
136 #| phone       | varchar(12)      | YES  |     | NULL    |                |
137 #| email       | varchar(120)     | YES  |     | NULL    |                |
138 #| ppi_pri     | int(10) unsigned | YES  |     | 1       |                |
139 #| ppi_notes   | varchar(128)     | YES  |     | NULL    |                |
140 #| int_pri     | int(10) unsigned | YES  |     | 1       |                |
141 #| int_notes   | varchar(128)     | YES  |     | NULL    |                |
142 #| attending   | tinyint(1)       | YES  |     | 0       |                |
143 #| valid       | tinyint(1)       | YES  |     | NULL    |                |
144 #+-------------+------------------+------+-----+---------+----------------+
145 sub update_eq_elder_table
146 {
147     print "\n-> Updating eq_elder table\n";
148
149     # Set all records to be invalid. Only mark them as valid if they appear on the new list.
150     $sth = $dbh->prepare("update eq_elder set valid=0");
151     $sth->execute or die "-E- DB error: $DBI::errstr\n";
152     
153     foreach $index (keys %membership_data)
154     {
155         $hashref = $membership_data{$index};
156         foreach $key (keys %$hashref) {
157             if($key =~ /Priesthood/i && $membership_data{$index}{$key} =~ /Elder/i) {
158                 $id = $membership_data{$index}{'Indiv ID'};
159                 $elder_name = $membership_data{$index}{'Preferred Name'};
160                 $phone = $membership_data{$index}{'Phone 1'};
161                 $organization = $organization_by_id{$id};
162                 $attending = 0;
163                 if(($organization =~ /Elders/) ||
164                    ($organization =~ /Young Men/) ||
165                    ($organization =~ /Sunday School/) ||
166                    ($organization =~ /Primary/)
167                    ) { $attending = 1; }
168                 if($phone =~ /(\d\d\d-\d\d\d\d)/) { $phone = "$areacode-$1"; }
169                 if($phone =~ /^\(\d\d\d\) (\d\d\d-\d\d\d\d)/) { $phone = "$1-$2"; }
170                 $sth = $dbh->prepare("select * from eq_elder where name='$elder_name'");
171                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
172                 my @data = ();
173                 while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
174                 my $rows = scalar @data;
175                 if($rows == 0) {
176                     # No existing records found for this elder, make a new entry
177                     print "   Adding new Elder: $elder_name\n";
178                     $sth = $dbh->prepare("insert into eq_elder values (NULL,'$id','$elder_name','$phone','','1','','1','',$attending,1)");
179                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
180                 } elsif($rows == 1) {
181                     # An existing record was found for this elder, update it
182                     print "   Updating existing Elder: $elder_name\n";
183                     $sth = $dbh->prepare("update eq_elder set valid=1 where name='$elder_name'");
184                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
185                     if($phone ne "") { 
186                         $sth = $dbh->prepare("update eq_elder set phone='$phone' where name='$elder_name'");
187                     } else {
188                         $sth = $dbh->prepare("update eq_elder set phone=NULL where name='$elder_name'");
189                     }
190                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
191                     $sth = $dbh->prepare("update eq_elder set attending='$attending' where name='$elder_name'");
192                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
193                     $sth = $dbh->prepare("update eq_elder set indiv_id='$id' where name='$elder_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 Elder: $elder_name\n";
198                 }
199             }
200         }
201     }
202     $sth->finish();
203 }
204
205 # EQ_CALLING
206 #+--------------+------------------+------+-----+---------+-------+
207 #| Field        | Type             | Null | Key | Default | Extra |
208 #+--------------+------------------+------+-----+---------+-------+
209 #| indiv_id     | int(16) unsigned | YES  |     | NULL    |       |
210 #| name         | varchar(30)      | YES  |     | NULL    |       |
211 #| organization | varchar(30)      | YES  |     | NULL    |       |
212 #| position     | varchar(30)      | YES  |     | NULL    |       |
213 #| sequence     | int(16) unsigned | YES  |     | NULL    |       |
214 #| sustained    | date             | YES  |     | NULL    |       |
215 #+--------------+------------------+------+-----+---------+-------+
216 sub update_eq_calling_table()
217 {
218     print "\n-> Updating eq_calling table\n";
219
220     #print "-> Organization Data Dump\n\n";
221     #&print_hash(\%organization_data);
222     
223     # Delete all records from the calling table. We have no history to
224     # save here. Just re-populate with the latest calling information.
225     $sth = $dbh->prepare("delete from eq_calling ");
226     $sth->execute or die "-E- DB error: $DBI::errstr\n";
227     
228     foreach $index (keys %organization_data)
229     {
230         $indiv_id = $organization_data{$index}{'Indiv ID'};
231         $name = $organization_data{$index}{'Indiv Name'};
232         $name =~ s/\'/\\'/g; #'
233         $organization = $organization_data{$index}{'Organization'};
234         $organization_by_name{$name} = $organization;
235         $organization_by_id{$indiv_id} = $organization;
236         $position = $organization_data{$index}{'Position'};
237         $sequence = $organization_data{$index}{'Org Seq'};
238         $sustained = $organization_data{$index}{'Sustained'};
239         $sustained =~ /(\S+) (\d+)/; $month=$1; $year=$2;
240         if($name eq "") { next; }
241         print "   Adding new Calling: $name -> $position\n";
242         $sth = $dbh->prepare("insert into eq_calling values ('$indiv_id','$name','$organization','$position','$sequence','$month $year')");
243         $sth->execute or die "-E- DB error: $DBI::errstr\n";
244     }
245 }
246
247 # EQ_DISTRICT
248 #+------------+------------------+------+-----+---------+-------+
249 #| Field      | Type             | Null | Key | Default | Extra |
250 #+------------+------------------+------+-----+---------+-------+
251 #| district   | int(16) unsigned |      | PRI | 0       |       |
252 #| name       | varchar(30)      | YES  |     | NULL    |       |
253 #| supervisor | int(16) unsigned | YES  |     | NULL    |       |
254 #| valid      | tinyint(1)       | YES  |     | NULL    |       |
255 #+------------+------------------+------+-----+---------+-------+
256 sub update_eq_district_table
257 {
258     # Districts should be created by hand. This subroutine only
259     # updates the supervisor's ID in each district.
260     print "\n-> Updating eq_district table\n";
261     $sth = $dbh->prepare("select * from eq_district");
262     $sth->execute or die "-E- DB error: $DBI::errstr\n";
263     while($sqlhashref = $sth->fetchrow_hashref) {
264         $supervisor_name = $sqlhashref->{name};
265         $district = $sqlhashref->{district};
266         $sth2 = $dbh->prepare("select * from eq_elder where name='$supervisor_name'");
267         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
268         $sqlhashref2 = $sth2->fetchrow_hashref;
269         $supervisor_id = $sqlhashref2->{elder};
270         $sth2->finish();
271         $sth2 = $dbh->prepare("update eq_district set supervisor='$supervisor_id' where district='$district'");
272         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
273         $sth2->finish();
274     }
275     $sth->finish();
276 }
277
278 # EQ_COMPANIONSHIP
279 #+---------------+------------------+------+-----+---------+-------+
280 #| Field         | Type             | Null | Key | Default | Extra |
281 #+---------------+------------------+------+-----+---------+-------+
282 #| companionship | int(16) unsigned |      |     | 0       |       |
283 #| elder         | int(16) unsigned | YES  |     | NULL    |       |
284 #| aaronic       | int(16) unsigned | YES  |     | NULL    |       |
285 #| district      | int(16) unsigned | YES  |     | NULL    |       |
286 #| valid         | tinyint(1)       | YES  |     | NULL    |       |
287 #+---------------+------------------+------+-----+---------+-------+
288 sub update_eq_companionship_table
289 {
290     print "\n-> Updating eq_companionship table\n";
291
292     # First, mark all existing companionships as invalid in case they have been dissolved
293     $sth = $dbh->prepare("update eq_companionship set valid=0");
294     $sth->execute or die "-E- DB error: $DBI::errstr\n";
295     # Second, mark all the aaronic invalid. We'll only mark the ones as valid that are assigned to hometeach
296     $sth = $dbh->prepare("update eq_aaronic set valid=0");
297     $sth->execute or die "-E- DB error: $DBI::errstr\n";
298     
299     foreach $index (keys %hometeaching_data)
300     {
301         $hashref = $hometeaching_data{$index};
302         foreach $key (keys %$hashref) {
303             if($key =~ /Quorum/i && $hometeaching_data{$index}{$key} =~ /Elders/i) {
304                 foreach $field ("Home Teacher 1","Home Teacher 2") {
305                     $elder_name = $hometeaching_data{$index}{$field};
306                     if($elder_name eq "") { next; }
307                     $sth2 = $dbh->prepare("select * from eq_elder where name='$elder_name'");
308                     $sth2->execute or die "-E- DB error: $DBI::errstr\n";
309                     $sqlhashref2 = $sth2->fetchrow_hashref;
310                     $elder = $sqlhashref2->{elder};
311                     $aaronic = "NULL";
312                     if($elder eq "") {
313                         $sth2 = $dbh->prepare("select * from eq_aaronic where name='$elder_name'");
314                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
315                         $sqlhashref2 = $sth2->fetchrow_hashref;
316                         $aaronic = $sqlhashref2->{aaronic};
317                         $elder = "NULL";
318                         if($aaronic eq "") { print "-W- Unable to find $elder_name in eq_elder or eq_aaronic tables\n"; next; }
319                     } 
320                     $id = $hometeaching_data{$index}{'Comp ID'};
321                     $district = $hometeaching_data{$index}{'HT District'};
322                     $sth = $dbh->prepare("select * from eq_companionship where elder='$elder' and aaronic='$aaronic' and companionship='$id'");
323                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
324                     my @data = ();
325                     while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
326                     my $rows = scalar @data;
327                     if($rows == 0) {
328                         # No existing records found for this companionship, make a new entry
329                         print "   Adding Companion to companionship: $elder_name -> $id\n";
330                         $sth = $dbh->prepare("insert into eq_companionship values ($id,'$elder','$aaronic','$district',1)");
331                         $sth->execute or die "-E- DB error: $DBI::errstr\n";
332                     } else {
333                         # An existing companionship was found for this companionship, update it
334                         $sth2 = $dbh->prepare("select * from eq_companionship where district='$district' and companionship='$id'");
335                         $sth2->execute or die "-E- DB error: $DBI::errstr\n";
336                         if($elder ne "NULL") {
337                             print "   Updating Companionship with Elder: $elder_name ($elder) -> $id\n";
338                             $sth = $dbh->prepare("update eq_companionship set district='$district' where elder='$elder' and companionship='$id'");
339                             $sth->execute or die "-E- DB error 'district': $DBI::errstr\n";
340                             $sth = $dbh->prepare("update eq_companionship set elder='$elder' where elder='$elder' and companionship='$id'");
341                             $sth->execute or die "-E- DB error 'elder': $DBI::errstr\n";
342                             $sth = $dbh->prepare("update eq_companionship set valid=1 where elder='$elder' and companionship='$id'");
343                             $sth->execute or die "-E- DB error 'valid': $DBI::errstr\n";
344                         } else {
345                             print "   Updating Companionship with Aaronic: $elder_name ($aaronic) -> $id\n";
346                             $sth = $dbh->prepare("update eq_companionship set district='$district' where aaronic='$aaronic' and companionship='$id'");
347                             $sth->execute or die "-E- DB error: $DBI::errstr\n";
348                             $sth = $dbh->prepare("update eq_companionship set aaronic='$aaronic' where aaronic='$aaronic' and companionship='$id'");
349                             $sth->execute or die "-E- DB error: $DBI::errstr\n";
350                             $sth = $dbh->prepare("update eq_companionship set valid=1 where aaronic='$aaronic' and companionship='$id'");
351                             $sth->execute or die "-E- DB error: $DBI::errstr\n";                            
352                             $sth = $dbh->prepare("update eq_aaronic set valid=1 where aaronic='$aaronic'");
353                             $sth->execute or die "-E- DB error: $DBI::errstr\n";
354                         }
355                     }
356                     $sth->finish();
357                     $sth2->finish();                
358                 }
359             }
360         }
361     }
362 }
363
364 # EQ_FAMILY
365 #+---------------+------------------+------+-----+---------+-------+
366 #| Field         | Type             | Null | Key | Default | Extra |
367 #+---------------+------------------+------+-----+---------+-------+
368 #| family        | int(16) unsigned |      | PRI | 0       |   A   |
369 #| hofh_id       | int(16) unsigned | YES  |     | NULL    |       |
370 #| name          | varchar(30)      | YES  |     | NULL    |       |
371 #| name_id       | varchar(30)      | YES  |     | NULL    |       |
372 #| elder_id      | int(16) unsigned | YES  |     | NULL    |       |
373 #| companionship | int(16) unsigned | YES  |     | NULL    |       |
374 #| visit_pri     | int(10) unsigned | YES  |     | 1       |       |
375 #| visit_notes   | varchar(128)     | YES  |     | NULL    |       |
376 #| valid         | tinyint(1)       | YES  |     | NULL    |       |
377 #+---------------+------------------+------+-----+---------+-------+
378 sub update_eq_family_table
379 {
380     print "\n-> Updating eq_family table\n";
381
382     # Set all records to be invalid. Only mark them as valid if they appear on the new list.
383     $sth = $dbh->prepare("update eq_family set valid=0");
384     $sth->execute or die "-E- DB error: $DBI::errstr\n";
385     $sth = $dbh->prepare("update eq_family set companionship=0");
386     $sth->execute or die "-E- DB error: $DBI::errstr\n";
387     
388     foreach $index (keys %membership_data)
389     {
390         $hashref = $membership_data{$index};
391         foreach $key (keys %$hashref) {
392             if($key =~ /HH Position/i && $membership_data{$index}{$key} =~ /Head of Household/i) {
393                 $family_name = $membership_data{$index}{'Preferred Name'};
394                 $family_name =~ s/\'/\\'/g; #'
395                 $id = $membership_data{$index}{'HofH ID'};
396                 $name_id = uc($family_name);
397
398                 # Find out how many families match this family's name
399                 $sth = $dbh->prepare("select * from eq_family where name_id='$name_id'");
400                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
401                 my @data = ();
402                 while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
403                 my $rows = scalar @data;
404                 
405                 if($rows == 0) {
406                     # No existing records found for this family, make a new entry
407                     print "   Adding new Family: $family_name\n";
408                     $sth = $dbh->prepare("insert into eq_family values (NULL,$id,'$family_name','$name_id','0','0','1','',1)");
409                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
410                 } elsif($rows == 1) {
411                     # An existing record was found for this family, update it
412                     print "   Updating existing family: $family_name\n";
413                     $sth = $dbh->prepare("update eq_family set hofh_id=$id where name_id='$name_id'");
414                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
415                     $sth = $dbh->prepare("update eq_family set valid=1 where name_id='$name_id'");
416                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
417                 } else {
418                     # More than one record was found. Error! This shouldn't happen.
419                     print "   -E- More than one record found ($rows) for family name: $family_name\n";
420                 }
421
422                 # Now update the elder_id field for this family
423                 $sth = $dbh->prepare("select * from eq_elder WHERE name='$family_name'");
424                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
425                 while($sqlhashref = $sth->fetchrow_hashref) {
426                     $elder_id = $sqlhashref->{elder};
427                     print "   Updating family elder_id: $family_name -> $elder_id\n";
428                     $sth = $dbh->prepare("update eq_family set elder_id=$elder_id where name_id='$name_id'");
429                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
430                 }
431                 
432                 # Now update the hometeaching field for this family
433                 foreach $index (keys %hometeaching_data)
434                 {
435                     $hashref = $hometeaching_data{$index};
436                     foreach $key (keys %$hashref) {
437                         if($hometeaching_data{$index}{'Household'} =~ /(\S+)\s+(\S+),\s+(\S+)\s+(.*)/) {
438                             $a = $1; $b = $2; $c = $3; $d = $4;
439                             if($family_name =~ /$a/ && $hometeaching_data{$index}{'Household'} !~ /$family_name/i) { 
440                                 print "I: Adjusting hometeaching match from: $hometeaching_data{$index}{'Household'} to $a, $c $d\n";
441                                 $hometeaching_data{$index}{'Household'} = "$a, $c $d";
442                             }
443                         }
444                         if($key =~ /Quorum/i &&
445                            $hometeaching_data{$index}{$key} =~ /Elders/i &&
446                            $hometeaching_data{$index}{'Household'} =~ /$family_name/i &&
447                            $data[0]->{companionship} != $hometeaching_data{$index}{'Comp ID'}
448                            )
449                         {
450                             print "   Updating hometeaching assignment for $family_name family\n";
451                             $companionship = $hometeaching_data{$index}{'Comp ID'};
452                             $sth = $dbh->prepare("update eq_family set companionship='$companionship' where name_id='$name_id'");
453                             $sth->execute or die "-E- DB error: $DBI::errstr\n";
454                         }
455                     }
456                 }
457                 $sth->finish();
458             }
459         }
460     }
461 }
462
463 # EQ_PARENT
464 #+----------+------------------+------+-----+---------+-------+
465 #| Field    | Type             | Null | Key | Default | Extra |
466 #+----------+------------------+------+-----+---------+-------+
467 #| parent   | int(16) unsigned |      | PRI | 0       |   A   |
468 #| family   | int(16) unsigned | YES  |     | NULL    |       |
469 #| name     | varchar(30)      | YES  |     | NULL    |       |
470 #| birthday | date             | YES  |     | NULL    |       |
471 #| phone    | varchar(12)      | YES  |     | NULL    |       |
472 #| address  | varchar(255)     | YES  |     | NULL    |       |
473 #| indiv_id | int(16) unsigned | YES  | UNI | NULL    |       |
474 #| valid    | tinyint(1)       | YES  |     | NULL    |       |
475 #+----------+------------------+------+-----+---------+-------+
476 sub update_eq_parent_table
477 {
478     print "\n-> Updating eq_parent table\n";
479
480     # Set all records to be invalid. Only mark them as valid if they appear on the new list.
481     $sth = $dbh->prepare("update eq_parent set valid=0");
482     $sth->execute or die "-E- DB error: $DBI::errstr\n";
483     
484     foreach $index (keys %membership_data)
485     {
486         $hashref = $membership_data{$index};
487         foreach $key (keys %$hashref) {
488             if($key =~ /HH Position/i &&
489                $membership_data{$index}{$key} =~ /Head of Household/i ||
490                $membership_data{$index}{$key} =~ /Spouse/i
491                ) {
492                 # Get some information from the hash about this parent
493                 $parent_name = $membership_data{$index}{'Preferred Name'};
494                 $parent_name =~ s/\'/\\'/g; #'
495                 $birthday = $membership_data{$index}{'Birth'};
496                 $birthday =~ /(\d+) (\S+) (\d+)/; $day=$1; $month=$monthname2num{$2}; $year=$3;
497                 $hofh_id = $membership_data{$index}{'HofH ID'};
498                 $id = $membership_data{$index}{'Indiv ID'};
499                 $phone = $membership_data{$index}{'Phone 1'};
500                 if($phone =~ /(\d\d\d-\d\d\d\d)/) { $phone = "$areacode-$1"; }
501                 if($phone =~ /^\(\d\d\d\) (\d\d\d-\d\d\d\d)/) { $phone = "$1-$2"; }
502                 $address = $membership_data{$index}{'Street 1'};
503                 if($membership_data{$index}{'Street 2'} ne "") { 
504                     $address .= " " . $membership_data{$index}{'Street 2'};
505                 }
506
507                 # Find the family id for this parent's HofH_ID.
508                 $sth = $dbh->prepare("select * from eq_family where hofh_id='$hofh_id' and valid=1");
509                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
510                 my @family_data = ();
511                 while($sqlhashref = $sth->fetchrow_hashref) { push(@family_data, $sqlhashref); }
512                 my $family_rows = scalar @family_data;
513                 if($family_rows > 0) { $family_id = $family_data[0]->{'family'}; }
514                 else { $family_id = 0; }
515                 
516                 # Find out how many parents match this parent's name
517                 $sth = $dbh->prepare("select * from eq_parent where name='$parent_name'");
518                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
519                 my @data = ();
520                 while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
521                 my $rows = scalar @data;
522                 
523                 if($rows == 0 && $family_rows > 0) {
524                     # No existing records found for this parent, make a new entry
525                     print "   Adding new Parent: $parent_name\n";
526                     $sth = $dbh->prepare("insert into eq_parent values (NULL,$family_id,'$parent_name','$year-$month-$day','$phone','$address','$id',1)");
527                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
528                 } elsif($rows == 1 && $family_rows > 0) {
529                     # An existing record was found for this parent, update it
530                     print "   Updating existing parent: $parent_name\n";
531                     $sth = $dbh->prepare("update eq_parent set family='$family_id' where name='$parent_name'");
532                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
533                     $sth = $dbh->prepare("update eq_parent set birthday='$year-$month-$day' where name='$parent_name'");
534                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
535                     $sth = $dbh->prepare("update eq_parent set phone='$phone' where name='$parent_name'");
536                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
537                     $sth = $dbh->prepare("update eq_parent set address='$address' where name='$parent_name'");
538                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
539                     $sth = $dbh->prepare("update eq_parent set valid=1 where name='$parent_name'");
540                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
541                     $sth = $dbh->prepare("update eq_parent set indiv_id='$id' where name='$parent_name'");
542                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
543                 } elsif($rows > 1) {
544                     # More than one record was found. Error! This shouldn't happen.
545                     print "   -E- More than one record found with same parent name: $parent_name with hofh_id: $hofh_id\n";
546                 } else {
547                     print "   -E- Unable to find a family to attach this parent to: $parent_name with hofh_id: $hofh_id\n";
548                 }
549                 $sth->finish();
550             }
551         }
552     }
553 }
554
555 # EQ_CHILD
556 #+----------+------------------+------+-----+---------+-------+
557 #| Field    | Type             | Null | Key | Default | Extra |
558 #+----------+------------------+------+-----+---------+-------+
559 #| child    | int(16) unsigned |      | PRI | 0       |   A   |
560 #| family   | int(16) unsigned | YES  |     | NULL    |       |
561 #| name     | varchar(30)      | YES  |     | NULL    |       |
562 #| birthday | date             | YES  |     | NULL    |       |
563 #| indiv_id | int(16) unsigned | YES  | UNI | NULL    |       |
564 #| valid    | tinyint(1)       | YES  |     | NULL    |       |
565 #+----------+------------------+------+-----+---------+-------+
566 sub update_eq_child_table
567 {
568     print "\n-> Updating eq_child table\n";
569
570     # Set all records to be invalid. Only mark them as valid if they appear on the new list.
571     $sth = $dbh->prepare("update eq_child set valid=0");
572     $sth->execute or die "-E- DB error: $DBI::errstr\n";
573     
574     foreach $index (keys %membership_data)
575     {
576         $hashref = $membership_data{$index};
577         foreach $key (keys %$hashref) {
578             if($key =~ /HH Position/i && $membership_data{$index}{$key} =~ /Other/i ) {
579                 $child_name = $membership_data{$index}{'Full Name'};
580                 $child_name =~ s/\'/\\'/g; #'
581                 $birthday = $membership_data{$index}{'Birth'};
582                 $birthday =~ /(\d+) (\S+) (\d+)/; $day=$1; $month=$monthname2num{$2}; $year=$3;
583                 $id = $membership_data{$index}{'Indiv ID'};
584                 $hofh_id = $membership_data{$index}{'HofH ID'};
585
586                 # Find the family id for this child's HofH_ID.
587                 $sth = $dbh->prepare("select * from eq_family where hofh_id='$hofh_id' and valid=1");
588                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
589                 my @family_data = ();
590                 while($sqlhashref = $sth->fetchrow_hashref) { push(@family_data, $sqlhashref); }
591                 my $family_rows = scalar @family_data;
592                 if($family_rows > 0) { $family_id = $family_data[0]->{'family'}; }
593                 else { $family_id = 0; }
594                 
595                 # Find out how many children have the same name for the same family
596                 $sth = $dbh->prepare("select * from eq_child where name='$child_name'");
597                 $sth->execute or die "-E- DB error: $DBI::errstr\n";
598                 my @data = ();
599                 while($sqlhashref = $sth->fetchrow_hashref) { push(@data, $sqlhashref); }
600                 my $rows = scalar @data;
601                 
602                 if($rows == 0 && $family_rows > 0) {
603                     # No existing records found for this child, make a new entry
604                     print "   Adding new Child: $child_name\n";
605                     $sth = $dbh->prepare("insert into eq_child values (NULL,$family_id,'$child_name','$year-$month-$day','$id',1)");
606                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
607                 } elsif($rows == 1 && $family_rows > 0) {
608                     # An existing record was found for this child, update it
609                     print "   Updating existing child: $child_name\n";
610                     $sth = $dbh->prepare("update eq_child set family='$family_id' where name='$child_name'");
611                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
612                     $sth = $dbh->prepare("update eq_child set birthday='$year-$month-$day' where name='$child_name'");
613                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
614                     $sth = $dbh->prepare("update eq_child set valid=1 where name='$child_name'");
615                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
616                     $sth = $dbh->prepare("update eq_child set indiv_id='$id' where name='$child_name'");
617                     $sth->execute or die "-E- DB error: $DBI::errstr\n";
618                 } else {
619                     # More than one record was found. Error! This shouldn't happen.
620                     print "   -E- More than one record found ($rows) with same child name: $child_name\n";
621                 }
622                 $sth->finish();
623             }
624         }
625     }
626 }
627
628 ######################################################################
629 sub check_for_changed_ids
630 {
631     # If the Indiv ID & HofH ID has changed between data sets, we could have problems
632     my ($oldhashref, $newhashref) = @_;
633     my $found_problem = 0;
634     
635     foreach $oldindex (keys %$oldhashref)
636     {
637         $indiv_id = $oldhashref->{$oldindex}{'Indiv ID'};
638         $hofh_id  = $oldhashref->{$oldindex}{'HofH ID'};
639         $full_name = $oldhashref->{$oldindex}{'Full Name'};
640         $hh_position = $oldhashref->{$oldindex}{'HH Position'};
641         if($hh_position =~ /Other/i) { next; }
642
643         foreach $newindex (keys %$newhashref)
644         {
645             if($newhashref->{$newindex}{'Full Name'} eq $full_name &&
646                $indiv_id != $newhashref->{$newindex}{'Indiv ID'})
647             {
648                 print "-W- Indiv ID for $full_name changed from $indiv_id to $newhashref->{$newindex}{'Indiv ID'}\n";
649                 $found_problem = 1;
650             }
651
652             if($newhashref->{$newindex}{'Full Name'} eq $full_name &&
653                $hofh_id != $newhashref->{$newindex}{'HofH ID'})
654             {
655                 print "-W- HofH ID for $full_name changed from $hofh_id to $newhashref->{$newindex}{'HofH ID'}\n";
656                 $found_problem = 1;
657             }
658         }
659     }
660     
661     return $found_problem;
662 }
663
664 ######################################################################
665 # MAIN
666 ######################################################################
667
668 ###################################################
669 # Open a connection to the database
670 $dbh=DBI->connect("dbi:mysql:dbname=$dbname:host=$dbhost:port=$dbport",$dbuser,$dbpass,{
671     AutoCommit=>0,
672     PrintError=>0}) or print "Connect Failure:".$DBI::errstr."\n" and exit 2;
673
674 ###################################################
675 # Check old directory against new directory to ensure
676 # that the Indiv ID & HofH ID have not changed between updates
677 if(defined $opt_o) {
678     print "-> Comparing old data files to new ones: $opt_o => $opt_n\n";
679     my %old_membership_data = ();
680     my %new_membership_data = ();
681     &csv_to_hash("$opt_o/Membership.csv",\%old_membership_data);
682     &csv_to_hash("$opt_n/Membership.csv",\%new_membership_data);
683
684     $changed_ids=&check_for_changed_ids(\%old_membership_data, \%new_membership_data);
685     
686     if($changed_ids) {
687         print "\n";
688         print "-E- Some Indiv IDs and HofH IDs have changed for Head of Households between \n";
689         print "    $opt_o and $opt_n data sets.\n";
690         print "    This script is not currently setup to handle this properly.\n";
691         print "\n";
692         print "    Exiting without updating...\n\n";
693         exit;
694     }
695 }
696
697 ###################################################
698 # Process command line options
699 if(defined $opt_n) { $datadir = $opt_n; }
700 else { $datadir = shift(@ARGV); }
701 print "\n-> Processing all ward data files in $datadir\n";
702
703 ###################################################
704 # Parse Ward Data Files
705 &csv_to_hash("$datadir/Membership.csv",\%membership_data);
706 &csv_to_hash("$datadir/HomeTeaching.csv",\%hometeaching_data);
707 &csv_to_hash("$datadir/Organization.csv",\%organization_data);
708 %organization_by_name = ();
709 %organization_by_id = ();
710
711 if($opt_v) {
712     print "-> Membership Data Dump\n\n";
713     &print_hash(\%membership_data);
714     print "-> HomeTeaching Data Dump\n\n";
715     &print_hash(\%hometeaching_data);
716     print "-> Organization Data Dump\n\n";
717     &print_hash(\%organization_data);
718 }
719
720 if($opt_s) { $dbh->disconnect(); exit; }
721
722 # Now update the various eq DB tables
723 &update_eq_calling_table();
724 &update_eq_elder_table();
725 &update_eq_aaronic_table();
726 &update_eq_district_table();
727 &update_eq_companionship_table();
728 &update_eq_family_table();
729 &update_eq_parent_table();
730 &update_eq_child_table();
731
732 print "\n-> Import Successful! DONE...\n";
733
734 ###################################################
735 # Disconnect from the database
736 $dbh->disconnect();
737
738 ######################################################################
739
740