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