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