planet telecom rate import, RT#83146
[freeside.git] / bin / cdr-voipswitch.import
1 #!/usr/bin/perl
2
3 #false laziness w/other cdr-*.import scripts, especially the other MySQL ones
4 # -mysql (asterisk
5 # -opensips
6 # -a2billing
7 # -voipnow
8
9 use strict;
10 use Date::Parse 'str2time';
11 use Date::Format 'time2str';
12 use FS::UID qw(adminsuidsetup dbh);
13 use FS::cdr;
14 use DBI;
15 use Getopt::Std;
16
17 my %opt;
18 getopts('H:U:P:D:T:s:e:c:', \%opt);
19 my $user = shift or die &usage;
20
21 my $dsn = 'dbi:mysql';
22 $dsn .= ":database=$opt{D}" if $opt{D};
23 $dsn .= ":host=$opt{H}" if $opt{H};
24
25 my $mysql = DBI->connect($dsn, $opt{U}, $opt{P}) 
26   or die $DBI::errstr;
27
28 my ($start, $end) = ('', '');
29 if ( $opt{s} ) {
30   $start = str2time($opt{s}) or die "can't parse start date $opt{s}\n";
31   $start = time2str('%Y-%m-%d', $start);
32 }
33 if ( $opt{e} ) {
34   $end = str2time($opt{e}) or die "can't parse end date $opt{e}\n";
35   $end = time2str('%Y-%m-%d', $end);
36 }
37
38 adminsuidsetup $user;
39
40 # check for existence of freesidestatus
41 my $table = 'calls'; # $opt{T} || 'calls';
42 my $status = $mysql->selectall_arrayref("SHOW COLUMNS FROM $table WHERE Field = 'freesidestatus'");
43 if( ! @$status ) {
44   print "Adding freesidestatus column...\n";
45   $mysql->do("ALTER TABLE $table ADD COLUMN freesidestatus varchar(32)")
46     or die $mysql->errstr;
47 }
48 else {
49   print "freesidestatus column present\n";
50 }
51
52 my @cols = (qw( 
53   id_call id_client ip_number caller_id called_number call_start call_end
54   route_type id_tariff cost duration tariff_prefix client_type id_route pdd
55   costR1 costR2 costR3 costD id_reseller tariffdesc id_cc ratio client_pdd
56   orig_call_id term_call_id id_callback_call id_cn dialing_plan_prefix
57   call_rate effective_duration dtmf call_data tariff_data id_dial_plan
58 ));
59
60 #effective_duration/billsec appears from the documentation to be post-minimum time and granularity, calculated on the switch (see p4-5).  would probably have weired effects if we then tried to do the same in freeside.
61
62 #so, probably either set the switch minimal_time and resolution to 1 sec and do the minimum and granularity calculation in freeside, OR, the other way around, if client prefers to set minimal_time and resolution in the switch, then the freeside rating should be no minimum, no (1 second) granularity
63
64 #(if you're rating and not just passing through cost->upstream_price)
65
66 #id_call             - cdrid
67 #id_client           - (w/client_type) charged_party
68 #ip_number           - src_ip_addr
69 #caller_id           - src (or clid?)
70 #called_number       - dst
71 #call_start          - startdate
72 #call_end            - enddate
73 #route_type          - channel
74 #id_tariff           - upstream_rateplanid
75 #cost                - upstream_price
76 #duration            - duration
77 #tariff_prefix
78 #client_type         - (w/id_client) charged_party
79 #id_route
80 #pdd
81 #costR1
82 #costR2
83 #costR3
84 #costD
85 #id_reseller
86 #tariffdesc          - upstream_dst_regionname
87 #id_cc               - uniqueid
88 #ratio
89 #client_pdd
90 #orig_call_id        - clid or is this src?
91 #term_call_id        - need this?
92 #id_callback_call
93 #id_cn
94 #dialing_plan_prefix
95 #call_rate           - upstream_rate?
96 #effective_duration  - billsec
97 #dtmf                - lastdata
98 #call_data           - disposition
99
100 # (these last two appear to be undocumented)
101 #tariff_data        -
102 #id_dial_plan
103
104 my $sql = 'SELECT '.join(',', @cols). " FROM $table ".
105   ' WHERE freesidestatus IS NULL' .
106   ($start && " AND call_start >= '$start'") .
107   ($end   && " AND call_start <  '$end'") ;
108
109 my $sth = $mysql->prepare($sql);
110 $sth->execute;
111 print "Importing ".$sth->rows." records...\n";
112
113 my $cdr_batch = new FS::cdr_batch({ 
114     'cdrbatch' => 'mysql-import-'. time2str('%Y/%m/%d-%T',time),
115   });
116 my $error = $cdr_batch->insert;
117 die $error if $error;
118 my $cdrbatchnum = $cdr_batch->cdrbatchnum;
119 my $imported = 0;
120
121 my $row;
122 while ( $row = $sth->fetchrow_hashref ) {
123
124   my $ip = $row->{ip_number};
125   if ( $ip =~ /^([\d\.]+)\/([\d\.]*)/ ) {
126     $ip = $1;
127     #$nat_ip = $2;
128   }
129
130   my $cdr = FS::cdr->new({
131       cdrid                   => $row->{id_call},
132       charged_party           => sprintf('%.2d', $row->{client_type}).
133                                  $row->{id_client},
134       src_ip_addr             => $ip,
135       src                     => $row->{caller_id},
136       dst                     => $row->{called_number},
137       startdate               => str2time($row->{call_start}),
138       enddate                 => str2time($row->{call_end}),
139       channel                 => $row->{route_type},
140       upstream_rateplanid     => $row->{id_tariff},
141       upstream_price          => $row->{cost},
142       duration                => $row->{duration},
143       upstream_dst_regionname => $row->{tariffdesc},
144       uniqueid                => $row->{id_cc},
145       orig_call_id            => $row->{clid},
146       billsec                 => $row->{effective_duration},
147       #lastdata                => $row->{dtmf},
148       disposition             => $row->{call_data},
149
150       cdrbatchnum   => $cdrbatchnum,
151     }
152   );
153   $cdr->cdrtypenum($opt{c}) if $opt{c};
154   
155   #print $row->{id_call},"\n" if $opt{v};
156   my $error = $cdr->insert;
157   if ($error) {
158     #die $row->{id_call} . ": failed import: $error\n";
159     print $row->{id_call} . ": failed import: $error\n";
160   } else {
161     $imported++;
162
163     my $updated = $mysql->do(
164       "UPDATE $table SET freesidestatus = 'done' WHERE id_call = ?",
165       undef,
166       $row->{'id_call'}
167     );
168     #$updates += $updated;
169     die "failed to set status: ".$mysql->errstr."\n" unless $updated;
170   }
171
172 }
173 print "Done.\n";
174 print "Imported $imported CDRs.\n" if $imported;
175 $mysql->disconnect;
176
177 sub usage {
178   "Usage: \n  cdr-voipswitch.import\n\t[ -H host ]\n\t-D database\n\t-U user\n\t-P password\n\t[ -s start ] [ -e end ] [ -c cdrtypenum ] \n\tfreesideuser\n";
179 }
180
181