summaryrefslogtreecommitdiff
path: root/FS/bin/freeside-cdr-a2billing-import
blob: aa7fa4a61e22676a8129d8d3bab427e27af45379 (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
#!/usr/bin/perl

use strict;
use vars qw( $DEBUG );
use Date::Parse 'str2time';
use Date::Format 'time2str';
use FS::UID qw(adminsuidsetup dbh);
use FS::cdr;
use DBI;
use Getopt::Std;

my %opt;
getopts('H:U:P:D:T:s:e:c:', \%opt);
my $user = shift or die &usage;

my $dsn = 'dbi:mysql';
$dsn .= ":database=$opt{D}" if $opt{D};
$dsn .= ":host=$opt{H}" if $opt{H};

my $mysql = DBI->connect($dsn, $opt{U}, $opt{P}) 
  or die $DBI::errstr;

my ($start, $end) = ('', '');
if ( $opt{s} ) {
  $start = str2time($opt{s}) or die "can't parse start date $opt{s}\n";
  $start = time2str('%Y-%m-%d', $start);
}
if ( $opt{e} ) {
  $end = str2time($opt{e}) or die "can't parse end date $opt{e}\n";
  $end = time2str('%Y-%m-%d', $end);
}

adminsuidsetup $user;

my $fsdbh = FS::UID::dbh;

# check for existence of freesidestatus
my $table = $opt{T} || 'cc_call';
my $status = $mysql->selectall_arrayref("SHOW COLUMNS FROM $table WHERE Field = 'freesidestatus'");
if( ! @$status ) {
  print "Adding freesidestatus column...\n";
  $mysql->do("ALTER TABLE $table ADD COLUMN freesidestatus varchar(32)")
    or die $mysql->errstr;
}
else {
  print "freesidestatus column present\n";
}

# Fields:
# id - primary key, sequential
# session_id - Local/<digits>-<digits> or SIP/<digits>-<digits>
# uniqueid - a decimal number, seems to be close to the unix timestamp
# card_id - probably the equipment port, 1 - 10
# nasipaddress - we don't care
# starttime, stoptime - timestamps
# sessiontime - duration, seconds
# calledstation - dst
# sessionbill - upstream_price
# id_tariffgroup - null, 0, 1
# id_tariffplan - null, 0, 3, 4, 5, 6, 7, 8, 9
# id_ratecard - larger numbers
# (all of the id_* fields are foreign keys: cc_tariffgroup, cc_ratecard, etc.)
# id_trunk - we don't care
# sipiax - probably don't care
# src - src.  Usually a phone number, but not always.
# id_did - always null
# buycost - wholesale price? correlated with sessionbill
# id_card_package_offer - no idea
# real_sessiontime - close to sessiontime, except when it's null
# (When sessiontime = 0, real_sessiontime is either 0 or null, and 
# sessionbill is 0.  When sessiontime > 0, but real_sessiontime is null, 
# sessionbill is 0.  So real_sessiontime seems to be the billable time, and 
# is null when the call is non-billable.)
# dnid - sometimes equals calledstation, or calledstation without the leading 
# "1".  But not always.
# terminatecauseid - integer, 0 - 7
# destination - seems to be the NPA or NPA+NXX sometimes, or "0".

# terminatecauseid values:
my %disposition = (
  0 => '',
  1 => 'ANSWER', #the only one that's billable
  2 => 'BUSY',
  3 => 'NOANSWER',
  4 => 'CANCEL',
  5 => 'CONGESTION',
  6 => 'CHANUNAVAIL',
  7 => 'DONTCALL',
  8 => 'TORTURE', #???
  9 => 'INVALIDARGS',
);

my @cols = (
  "$table.id as id", 'cc_card.username as username',
  qw( sessionid
      starttime stoptime sessiontime real_sessiontime
      terminatecauseid
      calledstation src
      id_tariffplan id_ratecard sessionbill
    )
);

my $sql = 'SELECT '.join(',', @cols). " FROM $table".
  " LEFT JOIN cc_card ON ( $table.card_id = cc_card.id ) ".
  ' WHERE freesidestatus IS NULL' .
  ($start && " AND starttime >= '$start'") .
  ($end   && " AND starttime <  '$end'") ;
my $sth = $mysql->prepare($sql);
$sth->execute;
print "Importing ".$sth->rows." records...\n";

my $cdr_batch = new FS::cdr_batch({ 
    'cdrbatch' => 'mysql-import-'. time2str('%Y/%m/%d-%T',time),
  });
my $error = $cdr_batch->insert;
die $error if $error;
my $cdrbatchnum = $cdr_batch->cdrbatchnum;
my $imports = 0;
my $updates = 0;

my $row;
while ( $row = $sth->fetchrow_hashref ) {
  my $dst = $row->{calledstation};
  my $dst_ip_addr = '';
  if ($dst =~ m[^SIP/(\d+)@(.*)$] ) {
    $dst = $1;
    $dst_ip_addr = $2;
  }
  $dst =~ s/^1//;
  $row->{src} =~ s/^1//;
  my $cdr = FS::cdr->new ({
    uniqueid            => $row->{sessionid},
    cdrbatchnum         => $cdrbatchnum,
    startdate           => time2str($row->{starttime}),
    enddate             => time2str($row->{stoptime}),
    duration            => $row->{sessiontime},
    billsec             => $row->{real_sessiontime},
    dst                 => $dst,
    src                 => $row->{src},
    dst_ip_addr         => $dst_ip_addr,
    dstchannel          => $row->{calledstation},
    charged_party       => $row->{username},
    upstream_rateplanid => $row->{id_tariffplan},
    upstream_rateid     => $row->{id_ratecard}, # I think?
    upstream_price      => $row->{sessionbill},
  });
  $cdr->cdrtypenum($opt{c}) if $opt{c};

  my $error = $cdr->insert;
  if($error) {
    print "failed import: $error\n";
  } else {
    $imports++;
    my $updated = $mysql->do(
                    "UPDATE $table SET freesidestatus = 'done' WHERE id = ?",
                    undef,
                    $row->{'id'}
                  );
    $updates += $updated;
    print "failed to set status: ".$mysql->errstr."\n" unless $updated;
  }
}
print "Done.\nImported $imports CDRs, marked $updates as done in source database.\n";
$mysql->disconnect;

sub usage {
  "Usage: 
  freeside-cdr-a2billing-import
      [ -H host ]
      -D database
      -U user
      -P password
      [ -s start ] [ -e end ] [ -c cdrtypenum ]
      freesideuser
";
}

=head1 NAME

freeside-cdr-a2billing-import - Download CDRs from an A2Billing MySQL database

=head1 SYNOPSIS

  freeside-cdr-a2billing-import [ -H host ] -D database -U user -P password
    [ -T tablename ]
    [ -s start ] [ -e end ] [ -c cdrtypenum ]
    freesideuser

-H: database hostname

-D: database name

-U: database username

-P: database password

-T: table to import, defaults to cc_call

-s: start date, e.g. 4/20/2015

-e: end date, e.g. 12/25/2015

-c: cdrtypenum to set, defaults to none

freesideuser: freeside username

=head1 DESCRIPTION

=head1 BUGS

=head1 SEE ALSO

L<FS::cdr>

=cut

1;