RT# 82949 - changes section name from fees to pricing, better opiton
[freeside.git] / bin / rate-ntlightnet.import
1 #!/usr/bin/perl
2
3 use strict;
4 use Text::CSV;
5 use FS::Misc::Getopt;
6 use FS::Record qw( dbh );
7
8 getopts('');
9
10 $FS::UID::AutoCommit = 0;
11 my $dbh = dbh;
12
13 my $file = shift or usage();
14 open my $in, '<', $file or die "$file: $!\n";
15 my $csv = Text::CSV->new({ binary => 1, auto_diag => 2 });
16 # set header row
17 $csv->column_names($csv->getline($in));
18
19 #my $error;
20
21 my $rate = new FS::rate {
22   'ratename' => 'Discount Rate Plan',
23 };
24 my $r_error = $rate->insert;
25 die $r_error if $r_error;
26 my $ratenum = $rate->ratenum;
27
28 my %rate_region = ();
29
30 my( $rr, $rp ) = (0,0);
31
32 while (my $row = $csv->getline_hr($in)) {
33   print $csv->string;
34
35   my $key = join('|', map $row->{$_}, 'Description', 'Rate' );
36
37   unless ( $rate_region{$key} ) {
38
39     my $rate_region = new FS::rate_region {
40       'regionname' => $row->{'Description'},
41     };
42     my $rr_error = $rate_region->insert;
43     die $rr_error if $rr_error;
44     $rate_region{$key} = $rate_region;
45
46     my $rate_detail = new FS::rate_detail {
47       'ratenum'         => $ratenum,
48       'dest_regionnum'  => $rate_region->regionnum,
49       'conn_charge'     => ( ( $row->{'Initial'} / 60 ) * $row->{'Rate'} ),
50       'conn_sec'        => $row->{'Initial'},
51       'min_charge'      => $row->{'Rate'},
52       'sec_granularity' => $row->{"Increment"},
53       'min_included'    => 0,
54     };
55     my $rd_error = $rate_detail->insert;
56     die $rd_error if $rd_error;
57
58     $rr++;
59
60   }
61
62   my($countrycode, $npa);
63   if ( $row->{Country} =~ /^(1|2[078]|3[0123469]|4[01356789]|5[12345678]|6[0123456]|7[67]|7|8[123469]|9[0123458])(\d*)$/ ) { #https://en.wikipedia.org/wiki/List_of_country_calling_codes
64     ( $countrycode, $npa ) = ( $1, $2 );
65   } elsif ( length($row->{Country}) <= 3 ) {
66     $countrycode = $row->{Country};
67     $npa = '';
68   } else {
69     $countrycode = substr($row->{Country}, 0, 3);
70     $npa = substr($row->{Country}, 3);
71   }
72
73   my $rate_prefix = new FS::rate_prefix {
74     'regionnum'   => $rate_region{$key}->regionnum,
75     'countrycode' => $countrycode,
76     'npa'         => $npa,
77   };
78   my $rp_error = $rate_prefix->insert;
79   die $rp_error if $rp_error;
80   
81   $rp++;
82 }
83
84 dbh->commit;
85 print "Inserted $rp prefixes in $rr regions\n";
86
87 1;
88
89 sub usage {
90   die "Usage: rate-ntlightnet.import <user> <file>.csv\n\n";
91 }
92