83e0fa7db337d2ee54fb086312100f965514f4f0
[freeside.git] / bin / rate-ptelecom.import
1 #!/usr/bin/perl
2
3 use strict;
4 use Text::CSV_XS;
5 use FS::Misc::Getopt;
6 use FS::Record qw( dbh );
7 use FS::rate;
8 use FS::rate_region;
9 use FS::rate_detail;
10
11 our %opt;
12 getopts('d');
13
14 $FS::UID::AutoCommit = 0;
15 my $dbh = dbh;
16
17 ###
18 # import rate ("profiles")
19 ###
20
21 my $file = shift or usage();
22 open my $in, '<', $file or die "$file: $!\n";
23 my $csv = Text::CSV->new({ binary => 1, auto_diag => 2 });
24
25 my $rp = 0;
26 my %granularity = ();
27 #my %currency = ();
28
29 my %rate = ();
30 while (my $row = $csv->getline($in)) {
31
32   my $profilekey  = $row->[1];
33   my $name        = $row->[2];
34   my $granularity = $row->[5];
35   my $currency    = $row->[18];
36   my $rate = new FS::rate {
37     'ratename'     => "$currency: $name",
38     'agent_rateid' => $profilekey,
39   };
40   my $error = $rate->insert;
41   die $error if $error;
42
43   $granularity{$rate->ratenum} = $granularity;
44
45   $rate{$profilekey} = $rate;
46
47   $rp++;
48 }
49
50 ###
51 # import rate_region and rate_detail ("destination rates")
52 ###
53
54 my $rfile = shift or usage();
55 open my $rin, '<', $rfile or die "$rfile: $!\n";
56
57 my $header = <$rin>;
58
59 my $rr = 0;
60 my $rd = 0;
61 my %rate_region;
62 while( my $row = $csv->getline($rin) ) {
63
64   my( $profilekey, $currency, $destid, $profilerate, $destkey ) = @$row;
65
66
67   my $rate = $rate{$profilekey};
68   my $ratecurrency = (split(':', $rate->ratename) )[0];
69   die "currency mismatch" unless $currency eq $ratecurrency;
70
71   unless ( $rate_region{ $destkey } ) {
72
73     if ( $destid =~ /^(.*)\n\1$/ ) {
74       $destid = $1;
75       #warn $destid;
76     }
77
78     my $rate_region = new FS::rate_region {
79       'regionname' => "$destkey: $destid",
80     };
81     my $error = $rate_region->insert;
82     die $error if $error;
83     warn "$destkey: $destid\n";
84
85     $rate_region{$destkey} = $rate_region;
86     $rr++;
87   }
88
89   my $rate_detail = new FS::rate_detail {
90     'ratenum'         => $rate->ratenum,
91     'dest_regionnum'  => $rate_region{$destkey}->regionnum,
92     'min_charge'      => $profilerate,
93     'sec_granularity' => $granularity{ $rate->ratenum },
94     'min_included'    => 0,
95   };
96   my $error = $rate_detail->insert;
97   die $error if $error;
98
99   $rd++;
100
101 }
102
103 ###
104 # ??? import rate_prefix ("destinations?")
105 ###
106
107 #???
108
109 if ( $opt{d} ) {
110   dbh->rollback;
111   print STDERR "(dry run) ";
112 } else {
113   dbh->commit;
114 }
115
116 print "Inserted $rd rates for $rr regions in $rp rate plans\n";
117
118 1;
119
120 sub usage {
121   die "Usage: rate-ptelecom.import [ -d ] <user> profiles.csv rates.csv\n"
122 }
123