fix ticketing system error on bootstrap of new install
[freeside.git] / bin / import-did-inventory
1 #!/usr/bin/perl
2
3 use strict;
4 use warnings;
5 use Text::CSV;
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;
10 use FS::lata;
11 use FS::msa;
12 use FS::cust_main;
13 use FS::cust_main::Search qw(smart_search);
14 use FS::did_order;
15 use FS::did_order_item;
16 use FS::rate_center;
17 use FS::phone_avail;
18 use FS::did_vendor;
19 use FS::svc_phone;
20 use Data::Dumper;
21 use Time::HiRes qw(usleep ualarm gettimeofday tv_interval);
22
23 print "started time=".time."\n";
24
25 #### SET THESE! #################################
26 my $file = '/home/levinse/dids4.csv';
27 my $did_vendor_id = 1; 
28 my $dry = 0; 
29 my $internal_diddb_exportnum = 1; # IMPORTANT: set this to the correct exportnum or everything will go in wrong into phone_avail
30
31 # optionally set this one (probably not)
32 my %custname2num = (); # MyCust => 12345,
33 ################################################
34
35 my $user = shift;
36 adminsuidsetup $user;
37
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';
44
45 my $oldAutoCommit = $FS::UID::AutoCommit;
46 local $FS::UID::AutoCommit = 0;
47 my $dbh = dbh;
48 my $max_date = time;
49 my $min_date = 1262304000; # January 1st 2010
50 my %did_order = ();
51 my %rate_center = ();
52 my %rate_center_abbrev = ();
53 my %cust2pkg = ();
54 my %msamap = ( 
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,
60  'Cambridge' => 14460,
61  'Boise' => 14260,
62  'New York' => 35620,
63  'Aberdeen' => 10100,
64  'Bloomington' => 14020,
65  'Las Vegas' => 29820,
66  'Madison' => 31540,
67  'Miami' => 33100,
68  'Jackson' => 27140,
69  'St Cloud' => 41060,
70  'Stratford' => 14860,
71  
72 # more hax upon hax (the above are unique, no issues)
73  'Portland OR' => 38900, 
74  'Portland ME' => 38860, 
75 );
76 my $skipto = 0; 
77 my $limit = 0;
78 my $linenum = 1;
79 my $debug = 0;
80
81 # cache LATA and MSA tables in one query for performance
82 my @latas = qsearch('lata', {});
83 my %latas = map { $_->latanum => $_->description } @latas;
84
85 my @msas = qsearch('msa', {});
86 my %msas = map { $_->msanum => $_->description } @msas;
87
88 # now add in the brain-dead LATA hacks
89 $latas{636} = 'BRAINERD-FARGO ND';
90 $latas{920} = 'CONNECTICUT';
91 $latas{334} = 'AUBURN-HUNTINGTON IN';
92 $latas{232} = 'NORTHEAST - PA';
93 $latas{460} = 'SOUTHEAST FL GR-EA';
94 $latas{952} = 'TAMPA FLORIDA';
95 $latas{524} = 'KANSAS CITY';
96
97 my $parser = new DateTime::Format::Natural( 'time_zone' => 'local' );
98 sub parsedt {
99     my ($dt,$min,$max) = (shift,shift,shift);
100     $dt = "$dt 00:00:00";
101     my $epoch = $parser->parse_datetime($dt);
102     warn "dt='$dt' min=$min max=$max epoch=$epoch\n";
103     return $epoch->epoch 
104         if ($parser->success && $epoch->epoch >= $min && $epoch->epoch <= $max);
105     fatal("invalid date $dt (min=$min, max=$max)");
106 }
107
108 sub msatest {
109     my ($their,$our) = (shift,shift);
110     my $a = $our;
111     $a =~ s/,.*?$//;
112     return 1 if $a eq $their;
113     return 1 if ($our =~ /^([\w\s]+)-/ && $1 eq $their);
114     0;
115 }
116
117 sub trim {
118     my $str = shift;
119     $str =~ s/^\s+|\s+$//g;
120     $str;
121 }
122
123 sub suffer {
124     my $linenum = shift;
125     my @columns = @_;
126
127     my $did = trim($columns[0]);
128     my $npa = trim($columns[1]);
129     my $state = trim($columns[2]);
130     my $rate_center_abbrev = trim($columns[3]);
131     my $rate_center = trim($columns[4]);
132     my $customer = trim($columns[5]);
133     my $submitted = parsedt(trim($columns[7]),$min_date,$max_date);
134
135     my $ordernum = trim($columns[8]);
136     return if $ordernum eq 'Unknown'; 
137
138     my $confirmed = parsedt(trim($columns[9]),$submitted,$max_date);
139
140     # sometimes, we're in a non-Y2K-compliant bullshit format, differing from
141     # all the other dates. Other times, we randomly change formats multiple times
142     # in the middle of the file for absolutely no reason...wtf
143     my $received = trim($columns[10]); 
144     if ( $received =~ /^(\d{1,2})\/(\d{1,2})\/(\d{2})$/ ) {
145         $received = $2."/".$1."/20".$3;
146     } elsif ( $received !~ /^\d{2}\/\d{2}\/\d{4}$/ ) {
147         fatal("invalid received date $received");
148     }
149     if ( $ordernum == 300383 ) { # another hack due to bad data
150         $received = parsedt($received,1,$max_date) 
151     } else {
152         $received = parsedt($received,$confirmed,$max_date);
153     }
154
155     my $latanum = trim($columns[12]);
156     my $latadesc = trim($columns[13]);
157     my $msadesc = trim($columns[14]);
158
159     fatal("invalid DID and/or NPA or NPA doesn't match DID")
160         unless ($did =~ /^(\d{3})\d{7}$/ && $npa == $1);
161     fatal("invalid state, order #, LATA #, or LATA description")
162         unless ($state =~ /^[A-Z]{2}$/  && ($ordernum =~ /^\d+$/ || $ordernum eq 'Test') # more hacks
163                                         && $latanum =~ /^\d{3}$/ 
164                                         && $latadesc =~ /^[\w\s\-]+$/);
165
166
167     ### LATA ###
168
169     fatal("no lata found for latanum $latanum") unless exists($latas{$latanum});
170
171     # unsurprisingly, our idea of a LATA name doesn't always match their idea 
172     # of the same. Specifically, they randomly expand the state portion and
173     # abbreviate it arbitrarily
174
175     my $ourdesc = $latas{$latanum};
176
177     # strip off the fixed state abbreviation portion in ours
178     $ourdesc =~ s/ ..$//;
179     
180     # strip off the variable state abbreviation (or full name) portion in theirs
181     $latadesc =~ s/\s\w+$// unless uc($ourdesc) eq uc($latadesc); # yeah...long story :(
182
183     fatal("their LATA description '$latadesc' doesn't match our LATA description '$ourdesc'")
184         unless (uc($ourdesc) eq uc($latadesc) || $latanum == 460);
185
186
187     ### MSA ###
188
189     my $msanum = -1;
190     
191     # XXX: no idea what the MSA is for Danbury, so discard it for now and deal with it manually/later
192     $msadesc = '' if $msadesc eq 'Danbury';
193
194     # hax on hax
195     $msadesc = 'Portland OR' if ($msadesc eq 'Portland' && $state eq 'OR');
196     $msadesc = 'Portland ME' if ($msadesc eq 'Portland' && $state eq 'ME');
197
198     # not everything in their file has a MSA
199     if ( $msadesc =~ /^[\w\s]+$/ ) {
200
201         # their idea of a MSA differs from our idea of it
202         if ( exists($msamap{$msadesc}) ) {
203             $msanum = $msamap{$msadesc};
204         }
205         else {
206             my @msa = grep { msatest($msadesc,$_->description) } @msas;
207             fatal("multiple MSA matches for '$msadesc'") if(scalar(@msa) > 1);
208             $msanum = $msa[0]->msanum if scalar(@msa) == 1;
209             $msamap{$msadesc} = $msanum if $msanum != -1;
210         }
211         fatal("msa $msadesc not found") if $msanum == -1;
212         warn "$msadesc matched msanum $msanum for line $linenum\n" if $debug;
213     }
214
215
216     ### RATE CENTER ###
217     
218     if ( exists $rate_center{$rate_center} ) {
219         fatal("rate center abbreviation for '$rate_center' doesn't exist or doesn't match '$rate_center_abbrev'")
220             unless ( exists $rate_center_abbrev{$rate_center} &&
221                       $rate_center_abbrev{$rate_center} eq $rate_center_abbrev);
222     } else {
223         print "creating new rate center '$rate_center' '$rate_center_abbrev'\n";
224         my $rc = new FS::rate_center{ description => $rate_center };
225         my $error = $rc->insert;
226         fatal("can't insert rate center '$rate_center' '$rate_center_abbrev': $error") 
227             if $error;
228         $rate_center{$rate_center} = $rc->ratecenternum;
229         $rate_center_abbrev{$rate_center} = $rate_center_abbrev;
230     }
231     my $ratecenternum = $rate_center{$rate_center};
232    
233
234     my $order = order($ordernum,$submitted,$confirmed,$received,$customer);
235     my $order_item = order_item($order,$npa,$latanum,$state,$msanum,$ratecenternum);
236     my $phone_avail = phone_avail($order,$state,$did,$rate_center,$latanum,$msanum);
237     provision($did,$customer,$phone_avail) if $customer ne 'Stock';
238     
239     warn "Pass $linenum\n" if $debug;
240
241     my $time = time;
242     print "Done $linenum time=$time\n" if ($linenum % 100 == 0);
243 }
244
245 sub phone_avail {
246     my ($order,$state,$did,$rate_center,$latanum,$msanum) 
247                                         = (shift,shift,shift,shift,shift,shift);
248     $did =~ /^(\d{3})(\d{3})(\d{4})$/;
249     my $npa = $1;
250     my $nxx = $2;
251     my $station = $3;
252     my %hash = (
253         exportnum   => $internal_diddb_exportnum,
254         countrycode => '1',
255         state       => $state,
256         npa         => $npa,
257         nxx         => $nxx,
258         station     => $station,
259         name        => $rate_center,
260         rate_center_abbrev => $rate_center_abbrev{$rate_center},
261         ordernum    => $order->ordernum,
262         latanum     => $latanum,
263     );
264     $hash{'msanum'} = $msanum if $msanum != -1;
265     
266     my $pa = new FS::phone_avail{ %hash };
267     my $error = $pa->insert;
268     fatal("can't insert phone_avail: $error") if $error;
269
270     $pa;
271 }
272
273 sub order_item {
274     my($order,$npa,$latanum,$state,$msanum,$ratecenternum) 
275                                         = (shift,shift,shift,shift,shift,shift);
276     my %msa = ();
277     $msa{'msanum'} = $msanum if $msanum != -1;
278     my $oi;
279     my @order_item = $order->did_order_item; 
280     foreach my $order_item ( @order_item ) {
281         if($order_item->npa == $npa 
282             && $order_item->latanum == $latanum 
283             && $order_item->state eq $state 
284             && $order_item->ratecenternum == $ratecenternum
285             && (!$order_item->msanum || $order_item->msanum == $msanum)  ) {
286             fatal("Multiple order items") if $oi;
287             $oi = $order_item;
288         }
289     }
290     
291     if($oi) {
292         $oi->quantity($oi->quantity+1);
293         my $error = $oi->replace;
294         fatal("can't replace order item: $error") if $error;
295     } else {
296         $oi = new FS::did_order_item{ ordernum   => $order->ordernum,
297                                      npa        => $npa,
298                                      latanum    => $latanum,
299                                      state      => $state,
300                                      quantity   => 1,
301                                      ratecenternum => $ratecenternum,
302                                      %msa, };
303         my $error = $oi->insert;
304         fatal("can't insert order item: $error") if $error;
305     }
306
307     fatal("wtf2") unless $oi;
308
309     $oi;
310 }
311
312 sub order {
313     my($vendor_order_id,$submitted,$confirmed,$received,$customer) 
314                                             = (shift,shift,shift,shift,shift);
315     
316     my %cust = ();
317     if ( $customer ne 'Stock' ) {
318         if ( exists($custname2num{$customer}) ) {
319             $cust{'custnum'} = $custname2num{$customer};
320         } else {
321             print "new customer case for '$customer'\n";
322             my @cust_main = smart_search('search' => $customer);
323             fatal(scalar(@cust_main) . " customers found for $customer") 
324                 unless scalar(@cust_main) == 1;
325             my $cust_main = $cust_main[0];
326             
327             $cust{'custnum'} = $cust_main->custnum;
328             $custname2num{$customer} = $cust_main->custnum; 
329             $cust2pkg{$cust_main->custnum} = {};
330             
331             my @pkgs = $cust_main->ncancelled_pkgs;
332             fatal("no packages") unless scalar(@pkgs);
333
334             foreach my $pkg ( @pkgs ) {
335                 my @avail_part_svc = $pkg->available_part_svc;
336                 my @svcpart;
337                 foreach my $avail_part_svc ( @avail_part_svc ) {
338                     if ($avail_part_svc->svcdb eq 'svc_phone') {
339                         push @svcpart, $avail_part_svc->svcpart;
340                     }
341                 }
342                 fatal("multiple svc_phone services") if scalar(@svcpart) > 1;
343                 fatal("multiple packages with svc_phone services") 
344                     if (exists $cust2pkg{$cust_main->custnum}->{pkgnum}
345                             && scalar(@svcpart));
346                 if(scalar(@svcpart) == 1) {
347                     $cust2pkg{$cust_main->custnum}->{pkgnum} = $pkg->pkgnum;
348                     $cust2pkg{$cust_main->custnum}->{svcpart} = $svcpart[0];
349                 }
350             }
351
352             fatal("no pkg/svc") 
353                 unless (exists $cust2pkg{$cust_main->custnum}->{pkgnum}
354                         && exists $cust2pkg{$cust_main->custnum}->{svcpart});
355         }
356     }
357
358     my $o;
359     if( exists $did_order{$vendor_order_id} ) {
360         $o = $did_order{$vendor_order_id};
361 #       warn "$submitted $confirmed $received $vendor_order_id".Dumper($o);
362         fatal("vendor order #$vendor_order_id - order data differs from one item to another")
363             unless ( ( abs($o->submitted-$submitted) < 5
364                         || $o->vendor_order_id == 293011) # yet another bad data hack
365                     && abs($o->confirmed-$confirmed) < 5
366                     && abs($o->received-$received) < 5 
367                    );
368 #        fatal("customer mismatch for vendor order #$vendor_order_id")
369 #           unless (    ($o->custnum && $cust{'custnum'} 
370 #                        && ($o->custnum == $cust{'custnum'} 
371 #                         || $vendor_order_id eq '293745' || $vendor_order_id eq '300001')
372 #                     )
373 #                    ||
374 #                   (!$o->custnum && !exists($cust{'custnum'}))
375 #             );
376     } else {
377         $o = new FS::did_order{ vendornum       => $did_vendor_id,
378                                 vendor_order_id => $vendor_order_id,
379                                 submitted       => $submitted,
380                                 confirmed       => $confirmed,
381                                 received        => $received,
382                                 %cust,          };
383         my $error = $o->insert;
384         fatal("can't insert vendor order #$vendor_order_id: $error") if $error;
385         $did_order{$vendor_order_id} = $o;
386     }
387
388     fatal("wtf") unless $o;
389     $o;
390 }
391
392 sub provision {
393     my($did,$customer,$phone_avail) = (shift,shift,shift);
394
395     local $FS::svc_Common::noexport_hack = 1;
396     # because of the above, we now need to do the internal did db
397     # export's job ourselves (set the svcnum for the DID in phone_avail)
398
399     fatal("customer not found") unless exists $cust2pkg{$custname2num{$customer}};
400
401     my $svc_phone = new FS::svc_phone({
402             pkgnum  => $cust2pkg{$custname2num{$customer}}->{pkgnum},
403             svcpart => $cust2pkg{$custname2num{$customer}}->{svcpart},
404             countrycode => 1,
405             phonenum    => $did,
406         });
407     
408     # XXX: THIS LINE CAUSES PERFORMANCE TO DEGRADE
409     # -unattaching the exports has no effect
410     # -after each successive call, the time taken to complete 100 rows becomes greater
411     # -commenting out this call results in a constant time taken to complete 100 rows
412     my $error = $svc_phone->insert;
413
414     fatal("can't insert svc_phone: $error") if $error;
415
416     $phone_avail->svcnum($svc_phone->svcnum);
417     $error = $phone_avail->replace;
418     fatal("can't replace phone_avail: $error") if $error;
419
420     '';
421 }
422
423 sub fatal {
424     my $msg = shift;
425     $dbh->rollback if $oldAutoCommit;
426     die $msg;
427 }
428
429 my $csv = new Text::CSV;
430 open (CSV, "<", $file) or die $!;
431 print "Starting main loop time=".time."\n";
432 while (<CSV>) {
433     if ( $linenum == 1 ) { # skip header
434         $linenum++;
435         next;
436     }
437
438     if( $skipto > $linenum ) { # debug stuff
439         $linenum++;
440         next;
441     }
442
443     last if $limit > 0 && $limit <= $linenum;
444
445     # kept getting these errors for many lines:
446     # "EIQ - Binary character inside quoted field, binary off"
447     $_ =~ s/[^[:ascii:]]//g;
448
449     if ($csv->parse($_)) {
450         my @columns = $csv->fields();
451         suffer($linenum,@columns);
452     } else {
453         my $err = $csv->error_diag . "(" . $csv->error_input . ")";
454         print "WARNING: failed to parse line $linenum: " . $csv->error_diag
455             . " (" . $csv->error_input . ")\n";
456     }
457     $linenum++;
458 }
459 close CSV;
460
461 fatal("COMMIT ABORTED DUE TO DRY RUN BEING ON") if $dry;
462 $dbh->commit or die $dbh->errstr if $oldAutoCommit;