6 use FS::UID qw(adminsuidsetup);
7 use FS::cust_main_county;
8 use FS::Record qw(qsearch qsearchs dbh);
9 use DateTime::Format::Natural;
13 use FS::cust_main::Search qw(smart_search);
15 use FS::did_order_item;
21 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
23 print "started time=".time."\n";
25 #### SET THESE! #################################
26 my $file = '/home/levinse/dids1.csv';
27 my $did_vendor_id = 1;
29 my $internal_diddb_exportnum = 1; # IMPORTANT: set this to the correct exportnum or everything will go in wrong into phone_avail
31 # optionally set this one (probably not)
32 my %custname2num = (); # MyCust => 12345,
33 ################################################
38 local $SIG{HUP} = 'IGNORE';
39 local $SIG{INT} = 'IGNORE';
40 local $SIG{QUIT} = 'IGNORE';
41 local $SIG{TERM} = 'IGNORE';
42 local $SIG{TSTP} = 'IGNORE';
43 local $SIG{PIPE} = 'IGNORE';
45 my $oldAutoCommit = $FS::UID::AutoCommit;
46 local $FS::UID::AutoCommit = 0;
49 my $min_date = 1262304000; # January 1st 2010
52 my %rate_center_abbrev = ();
55 # YOU CANNOT USE THE STATE/NPA/LATA OF A DID TO TRY TO FIND ITS MSA. IT HAS
56 # NOTHING IN COMMON WITH THE STATE OF THE MSA. THERE IS SIMPLY INSUFFICIENT
57 # DATA IN THE CSV FILE TO DETERMINE CANONICAL MSA WITHOUT THIS:
58 'Washington DC' => 47900,
59 'Fort Lauderdale' => 33100,
64 'Bloomington' => 14020,
71 # more hax upon hax (the above are unique, no issues)
72 'Portland OR' => 38900,
73 'Portland ME' => 38860,
80 # cache LATA and MSA tables in one query for performance
81 my @latas = qsearch('lata', {});
82 my %latas = map { $_->latanum => $_->description } @latas;
84 my @msas = qsearch('msa', {});
85 my %msas = map { $_->msanum => $_->description } @msas;
87 # now add in the brain-dead LATA hacks
88 $latas{636} = 'BRAINERD-FARGO ND';
89 $latas{920} = 'CONNECTICUT';
90 $latas{334} = 'AUBURN-HUNTINGTON IN';
91 $latas{232} = 'NORTHEAST - PA';
92 $latas{460} = 'SOUTHEAST FL GR-EA';
93 $latas{952} = 'TAMPA FLORIDA';
94 $latas{524} = 'KANSAS CITY';
96 my $parser = new DateTime::Format::Natural( 'time_zone' => 'local' );
98 my ($dt,$min,$max) = (shift,shift,shift);
99 my $epoch = $parser->parse_datetime($dt);
101 if ($parser->success && $epoch->epoch >= $min && $epoch->epoch <= $max);
102 fatal("invalid date $dt (min=$min, max=$max)");
106 my ($their,$our) = (shift,shift);
109 return 1 if $a eq $their;
110 return 1 if ($our =~ /^([\w\s]+)-/ && $1 eq $their);
116 $str =~ s/^\s+|\s+$//g;
124 my $did = trim($columns[0]);
125 my $npa = trim($columns[1]);
126 my $state = trim($columns[2]);
127 my $rate_center_abbrev = trim($columns[3]);
128 my $rate_center = trim($columns[4]);
129 my $customer = trim($columns[5]);
130 my $submitted = parsedt(trim($columns[7]),$min_date,$max_date);
132 my $ordernum = trim($columns[8]);
133 return if $ordernum eq 'Unknown';
135 my $confirmed = parsedt(trim($columns[9]),$submitted,$max_date);
137 # sometimes, we're in a non-Y2K-compliant bullshit format, differing from
138 # all the other dates. Other times, we randomly change formats multiple times
139 # in the middle of the file for absolutely no reason...wtf
140 my $received = trim($columns[10]);
141 if ( $received =~ /^(\d{1,2})\/(\d{1,2})\/(\d{2})$/ ) {
142 $received = $2."/".$1."/20".$3;
143 } elsif ( $received !~ /^\d{2}\/\d{2}\/\d{4}$/ ) {
144 fatal("invalid received date $received");
146 if ( $ordernum == 300383 ) { # another hack due to bad data
147 $received = parsedt($received,1,$max_date)
149 $received = parsedt($received,$confirmed,$max_date);
152 my $latanum = trim($columns[12]);
153 my $latadesc = trim($columns[13]);
154 my $msadesc = trim($columns[14]);
156 fatal("invalid DID and/or NPA or NPA doesn't match DID")
157 unless ($did =~ /^(\d{3})\d{7}$/ && $npa == $1);
158 fatal("invalid state, order #, LATA #, or LATA description")
159 unless ($state =~ /^[A-Z]{2}$/ && ($ordernum =~ /^\d+$/ || $ordernum eq 'Test') # more hacks
160 && $latanum =~ /^\d{3}$/
161 && $latadesc =~ /^[\w\s\-]+$/);
166 fatal("no lata found for latanum $latanum") unless exists($latas{$latanum});
168 # unsurprisingly, our idea of a LATA name doesn't always match their idea
169 # of the same. Specifically, they randomly expand the state portion and
170 # abbreviate it arbitrarily
172 my $ourdesc = $latas{$latanum};
174 # strip off the fixed state abbreviation portion in ours
175 $ourdesc =~ s/ ..$//;
177 # strip off the variable state abbreviation (or full name) portion in theirs
178 $latadesc =~ s/\s\w+$// unless uc($ourdesc) eq uc($latadesc); # yeah...long story :(
180 fatal("their LATA description '$latadesc' doesn't match our LATA description '$ourdesc'")
181 unless uc($ourdesc) eq uc($latadesc);
188 # XXX: no idea what the MSA is for Danbury, so discard it for now and deal with it manually/later
189 $msadesc = '' if $msadesc eq 'Danbury';
192 $msadesc = 'Portland OR' if ($msadesc eq 'Portland' && $state eq 'OR');
193 $msadesc = 'Portland ME' if ($msadesc eq 'Portland' && $state eq 'ME');
195 # not everything in their file has a MSA
196 if ( $msadesc =~ /^[\w\s]+$/ ) {
198 # their idea of a MSA differs from our idea of it
199 if ( exists($msamap{$msadesc}) ) {
200 $msanum = $msamap{$msadesc};
203 my @msa = grep { msatest($msadesc,$_->description) } @msas;
204 fatal("multiple MSA matches for '$msadesc'") if(scalar(@msa) > 1);
205 $msanum = $msa[0]->msanum if scalar(@msa) == 1;
206 $msamap{$msadesc} = $msanum if $msanum != -1;
208 fatal("msa $msadesc not found") if $msanum == -1;
209 warn "$msadesc matched msanum $msanum for line $linenum\n" if $debug;
215 if ( exists $rate_center{$rate_center} ) {
216 fatal("rate center abbreviation for '$rate_center' doesn't exist or doesn't match '$rate_center_abbrev'")
217 unless ( exists $rate_center_abbrev{$rate_center} &&
218 $rate_center_abbrev{$rate_center} eq $rate_center_abbrev);
220 print "creating new rate center '$rate_center' '$rate_center_abbrev'\n";
221 my $rc = new FS::rate_center{ description => $rate_center };
222 my $error = $rc->insert;
223 fatal("can't insert rate center '$rate_center' '$rate_center_abbrev': $error")
225 $rate_center{$rate_center} = $rc->ratecenternum;
226 $rate_center_abbrev{$rate_center} = $rate_center_abbrev;
228 my $ratecenternum = $rate_center{$rate_center};
231 my $order = order($ordernum,$submitted,$confirmed,$received,$customer);
232 my $order_item = order_item($order,$npa,$latanum,$state,$msanum,$ratecenternum);
233 my $phone_avail = phone_avail($order,$state,$did,$rate_center,$latanum,$msanum);
234 provision($did,$customer,$phone_avail) if $customer ne 'Stock';
236 warn "Pass $linenum\n" if $debug;
239 print "Done $linenum time=$time\n" if ($linenum % 100 == 0);
243 my ($order,$state,$did,$rate_center,$latanum,$msanum)
244 = (shift,shift,shift,shift,shift,shift);
245 $did =~ /^(\d{3})(\d{3})(\d{4})$/;
250 exportnum => $internal_diddb_exportnum,
256 name => $rate_center,
257 rate_center_abbrev => $rate_center_abbrev{$rate_center},
258 ordernum => $order->ordernum,
261 $hash{'msanum'} = $msanum if $msanum != -1;
263 my $pa = new FS::phone_avail{ %hash };
264 my $error = $pa->insert;
265 fatal("can't insert phone_avail: $error") if $error;
271 my($order,$npa,$latanum,$state,$msanum,$ratecenternum)
272 = (shift,shift,shift,shift,shift,shift);
274 $msa{'msanum'} = $msanum if $msanum != -1;
276 my @order_item = $order->did_order_item;
277 foreach my $order_item ( @order_item ) {
278 if($order_item->npa == $npa
279 && $order_item->latanum == $latanum
280 && $order_item->state eq $state
281 && $order_item->ratecenternum == $ratecenternum
282 && (!$order_item->msanum || $order_item->msanum == $msanum) ) {
283 fatal("Multiple order items") if $oi;
289 $oi->quantity($oi->quantity+1);
290 my $error = $oi->replace;
291 fatal("can't replace order item: $error") if $error;
293 $oi = new FS::did_order_item{ ordernum => $order->ordernum,
298 ratecenternum => $ratecenternum,
300 my $error = $oi->insert;
301 fatal("can't insert order item: $error") if $error;
304 fatal("wtf2") unless $oi;
310 my($vendor_order_id,$submitted,$confirmed,$received,$customer)
311 = (shift,shift,shift,shift,shift);
314 if ( $customer ne 'Stock' ) {
315 if ( exists($custname2num{$customer}) ) {
316 $cust{'custnum'} = $custname2num{$customer};
318 print "new customer case for '$customer'\n";
319 my @cust_main = smart_search('search' => $customer);
320 fatal(scalar(@cust_main) . " customers found for $customer")
321 unless scalar(@cust_main) == 1;
322 my $cust_main = $cust_main[0];
324 $cust{'custnum'} = $cust_main->custnum;
325 $custname2num{$customer} = $cust_main->custnum;
326 $cust2pkg{$cust_main->custnum} = {};
328 my @pkgs = $cust_main->ncancelled_pkgs;
329 fatal("no packages") unless scalar(@pkgs);
331 foreach my $pkg ( @pkgs ) {
332 my @avail_part_svc = $pkg->available_part_svc;
334 foreach my $avail_part_svc ( @avail_part_svc ) {
335 if ($avail_part_svc->svcdb eq 'svc_phone') {
336 push @svcpart, $avail_part_svc->svcpart;
339 fatal("multiple svc_phone services") if scalar(@svcpart) > 1;
340 fatal("multiple packages with svc_phone services")
341 if (exists $cust2pkg{$cust_main->custnum}->{pkgnum}
342 && scalar(@svcpart));
343 if(scalar(@svcpart) == 1) {
344 $cust2pkg{$cust_main->custnum}->{pkgnum} = $pkg->pkgnum;
345 $cust2pkg{$cust_main->custnum}->{svcpart} = $svcpart[0];
350 unless (exists $cust2pkg{$cust_main->custnum}->{pkgnum}
351 && exists $cust2pkg{$cust_main->custnum}->{svcpart});
356 if( exists $did_order{$vendor_order_id} ) {
357 $o = $did_order{$vendor_order_id};
358 fatal("vendor order #$vendor_order_id - order data differs from one item to another")
359 unless ( ($o->submitted == $submitted
360 || $o->vendor_order_id == 293011) # yet another bad data hack
361 && $o->confirmed == $confirmed
362 && $o->received == $received);
363 fatal("customer mismatch for vendor order #$vendor_order_id")
364 unless ( ($o->custnum && $cust{'custnum'}
365 && $o->custnum == $cust{'custnum'})
366 || (!$o->custnum && !exists($cust{'custnum'})) );
368 $o = new FS::did_order{ vendornum => $did_vendor_id,
369 vendor_order_id => $vendor_order_id,
370 submitted => $submitted,
371 confirmed => $confirmed,
372 received => $received,
374 my $error = $o->insert;
375 fatal("can't insert vendor order #$vendor_order_id: $error") if $error;
376 $did_order{$vendor_order_id} = $o;
379 fatal("wtf") unless $o;
384 my($did,$customer,$phone_avail) = (shift,shift,shift);
386 local $FS::svc_Common::noexport_hack = 1;
387 # because of the above, we now need to do the internal did db
388 # export's job ourselves (set the svcnum for the DID in phone_avail)
390 fatal("customer not found") unless exists $cust2pkg{$custname2num{$customer}};
392 my $svc_phone = new FS::svc_phone({
393 pkgnum => $cust2pkg{$custname2num{$customer}}->{pkgnum},
394 svcpart => $cust2pkg{$custname2num{$customer}}->{svcpart},
399 # XXX: THIS LINE CAUSES PERFORMANCE TO DEGRADE AND THE SCRIPT NEVER FINISHES! WHY!?
400 # -unattaching the exports has no effect
401 # -after each successive call, the time taken to complete 100 rows becomes greater
402 # -commenting out this call results in a constant time taken to complete 100 rows
403 # -after 10K rows we get a random error that makes no sense
404 my $error = $svc_phone->insert;
406 fatal("can't insert svc_phone: $error") if $error;
408 $phone_avail->svcnum($svc_phone->svcnum);
409 $error = $phone_avail->replace;
410 fatal("can't replace phone_avail: $error") if $error;
417 $dbh->rollback if $oldAutoCommit;
421 my $csv = new Text::CSV;
422 open (CSV, "<", $file) or die $!;
423 print "Starting main loop time=".time."\n";
425 if ( $linenum == 1 ) { # skip header
430 if( $skipto > $linenum ) { # debug stuff
435 last if $limit > 0 && $limit <= $linenum;
437 # kept getting these errors for many lines:
438 # "EIQ - Binary character inside quoted field, binary off"
439 $_ =~ s/[^[:ascii:]]//g;
441 if ($csv->parse($_)) {
442 my @columns = $csv->fields();
443 suffer($linenum,@columns);
445 my $err = $csv->error_diag . "(" . $csv->error_input . ")";
446 print "WARNING: failed to parse line $linenum: " . $csv->error_diag
447 . " (" . $csv->error_input . ")\n";
453 fatal("COMMIT ABORTED DUE TO DRY RUN BEING ON") if $dry;
454 $dbh->commit or die $dbh->errstr if $oldAutoCommit;