work around missing id, RT#83146
[freeside.git] / bin / rate-login.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 # default is to charge per second; edit this if needed
9 my $granularity = 1;
10
11 getopts('');
12
13 $FS::UID::AutoCommit = 0;
14 my $dbh = dbh;
15
16 my $file = shift or usage();
17 open my $in, '<', $file or die "$file: $!\n";
18 my $csv = Text::CSV->new({ binary => 1, auto_diag => 2 });
19 # set header row
20 $csv->column_names($csv->getline($in));
21
22 #my $error;
23
24 my $rate = new FS::rate {
25   'ratename' => 'INTERNATIONAL',
26 };
27 my $r_error = $rate->insert;
28 die $r_error if $r_error;
29 my $ratenum = $rate->ratenum;
30
31 my %rate_region = ();
32
33 my( $rr, $rp ) = (0,0);
34
35 while (my $row = $csv->getline_hr($in)) {
36   print $csv->string;
37
38   my $key = $row->{country}.'|'.$row->{rate};
39
40   unless ( $rate_region{$key} ) {
41
42     my $rate_region = new FS::rate_region {
43       'regionname' => $row->{country},
44     };
45     my $rr_error = $rate_region->insert;
46     die $rr_error if $rr_error;
47     $rate_region{$key} = $rate_region;
48
49     my $rate_detail = new FS::rate_detail {
50       'ratenum'         => $ratenum,
51       'dest_regionnum'  => $rate_region->regionnum,
52       'min_charge'      => $row->{rate},
53       'sec_granularity' => $granularity,
54       'min_included'    => 0,
55     };
56     my $rd_error = $rate_detail->insert;
57     die $rd_error if $rd_error;
58
59     $rr++;
60
61   }
62
63   my($countrycode, $npa);
64   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
65     ( $countrycode, $npa ) = ( $1, $2 );
66   } elsif ( length($row->{prefix}) <= 3 ) {
67     $countrycode = $row->{prefix};
68     $npa = '';
69   } else {
70     $countrycode = substr($row->{prefix}, 0, 3);
71     $npa = substr($row->{prefix}, 3);
72   }
73
74   my $rate_prefix = new FS::rate_prefix {
75     'regionnum'   => $rate_region{$key}->regionnum,
76     'countrycode' => $countrycode,
77     'npa'         => $npa,
78   };
79   my $rp_error = $rate_prefix->insert;
80   die $rp_error if $rp_error;
81   
82   $rp++;
83 }
84
85 dbh->commit;
86 print "Inserted $rp prefixes in $rr regions\n";
87
88 1;
89
90 sub usage {
91   die "Usage: rate-login.import <user> <file>.csv\n\n";
92 }
93