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