summaryrefslogtreecommitdiff
path: root/bin/rate-login.import
blob: a77d0bdd226f47a4719773d37b039f9569b572a8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/perl

use strict;
use Text::CSV;
use FS::Misc::Getopt;
use FS::Record qw( dbh );

# default is to charge per second; edit this if needed
my $granularity = 1;

getopts('');

$FS::UID::AutoCommit = 0;
my $dbh = dbh;

my $file = shift or usage();
open my $in, '<', $file or die "$file: $!\n";
my $csv = Text::CSV->new({ binary => 1, auto_diag => 2 });
# set header row
$csv->column_names($csv->getline($in));

#my $error;

my $rate = new FS::rate {
  'ratename' => 'INTERNATIONAL',
};
my $r_error = $rate->insert;
die $r_error if $r_error;
my $ratenum = $rate->ratenum;

my %rate_region = ();

my( $rr, $rp ) = (0,0);

while (my $row = $csv->getline_hr($in)) {
  print $csv->string;

  my $key = $row->{country}.'|'.$row->{rate};

  unless ( $rate_region{$key} ) {

    my $rate_region = new FS::rate_region {
      'regionname' => $row->{country},
    };
    my $rr_error = $rate_region->insert;
    die $rr_error if $rr_error;
    $rate_region{$key} = $rate_region;

    my $rate_detail = new FS::rate_detail {
      'ratenum'         => $ratenum,
      'dest_regionnum'  => $rate_region->regionnum,
      'min_charge'      => $row->{rate},
      'sec_granularity' => $granularity,
      'min_included'    => 0,
    };
    my $rd_error = $rate_detail->insert;
    die $rd_error if $rd_error;

    $rr++;

  }

  my($countrycode, $npa);
  if ( $row->{prefix} =~ /^(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
    ( $countrycode, $npa ) = ( $1, $2 );
  } elsif ( length($row->{prefix}) <= 3 ) {
    $countrycode = $row->{prefix};
    $npa = '';
  } else {
    $countrycode = substr($row->{prefix}, 0, 3);
    $npa = substr($row->{prefix}, 3);
  }

  my $rate_prefix = new FS::rate_prefix {
    'regionnum'   => $rate_region{$key}->regionnum,
    'countrycode' => $countrycode,
    'npa'         => $npa,
  };
  my $rp_error = $rate_prefix->insert;
  die $rp_error if $rp_error;
  
  $rp++;
}

dbh->commit;
print "Inserted $rp prefixes in $rr regions\n";

1;

sub usage {
  die "Usage: rate-login.import <user> <file>.csv\n\n";
}