summaryrefslogtreecommitdiff
path: root/FS/FS/part_export/pbxware.pm
blob: e535e6ed05649b6485537121e37a7d88f1294dbe (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
package FS::part_export::pbxware;

use base qw( FS::part_export );
use strict;

use Tie::IxHash;
use LWP::UserAgent;
use Cpanel::JSON::XS;
use HTTP::Request::Common;
use Digest::MD5 qw(md5_hex);
use FS::Record qw(dbh);
use FS::cdr_batch;

our $me = '[pbxware]';
our $DEBUG = 0;
# our $DEBUG = 1; # log requests
# our $DEBUG = 2; # log requests and content of replies

tie my %options, 'Tie::IxHash',
  'apikey'   => { label => 'API key' },
  'debug'    => { label => 'Enable debugging', type => 'checkbox', value => 1 },
  'ext'      => { label => 'PBXware "ext" field in CDR download request', },
  'cdrtype'  => { label => 'PBXware "cdrtype" field in CDR download request', },
  'trunkdst' => { label => 'PBXware "trunkdst" field in CDR download request', },
;

our %info = (
  'svc'         => [qw(svc_phone)],
  'desc'        => 'Retrieve CDRs from Bicom PBXware',
  'options'     => \%options,
  'notes' => <<'END'
<P>Export to <a href="www.bicomsystems.com/pbxware-3-8">Bicom PBXware</a> 
softswitch.</P>
<P><I>This export does not yet provision services.</I> Currently you will need
to provision trunks and extensions through PBXware. The export only downloads 
CDRs.</P>
<P>Set the export machine to the name or IP address of your PBXware server,
and the API key to your alphanumeric key.</P>
END
);

sub export_insert {}
sub export_delete {}
sub export_replace {}
sub export_suspend {}
sub export_unsuspend {}

################
# CALL DETAILS #
################

=item import_cdrs START, END

Retrieves CDRs for calls in the date range from START to END and inserts them
as a new CDR batch. On success, returns a new cdr_batch object. On failure,
returns an error message. If there are no new CDRs, returns nothing.

=cut

# map their column names to cdr fields
# (warning: API docs are not quite accurate here)
our %column_map = (
  'Tenant'      => 'accountcode',
  'From'        => 'src',
  'To'          => 'dst',
  'Date/Time'   => 'startdate',
  'Duration'    => 'duration',
  'Billing'     => 'billsec',
  'Cost'        => 'upstream_price', # might not be used
  'Status'      => 'disposition',
);

sub import_cdrs {
  my ($self, $start, $end) = @_;
  $start ||= 0; # all CDRs ever
  $end ||= time;
  $DEBUG ||= $self->option('debug');

  my $oldAutoCommit = $FS::UID::AutoCommit;
  local $FS::UID::AutoCommit = 0;

  my $sd = DateTime->from_epoch(epoch => $start)->set_time_zone('local');
  my $ed = DateTime->from_epoch(epoch => $end)->set_time_zone('local');

  my $error;

  # Send a query.
  #
  # Other options supported:
  # - trunk, ext: filter by source trunk and extension
  # - trunkdst, extdst: filter by dest trunk and extension
  # - server: filter by server id
  # - status: filter by call status (answered, unanswered, busy, failed)
  # - cdrtype: filter by call direction

  my %opt = (
    start     => $sd->strftime('%b-%d-%Y'),
    starttime => $sd->strftime('%H:%M:%S'),
    end       => $ed->strftime('%b-%d-%Y'),
    endtime   => $ed->strftime('%H:%M:%S'),
  );

  $opt{$_} = $self->option($_)
    for grep length( $self->option($_) ), qw( ext cdrtype trunkdst );

  # unlike Certain Other VoIP providers, this one does proper pagination if
  # the result set is too big to fit in a single chunk.
  my $page = 1;
  my $more = 1;
  my $cdr_batch;

  do {
    my $result = $self->api_request('pbxware.cdr.download', \%opt);
    if ($result->{success} !~ /^success/i) {
      dbh->rollback if $oldAutoCommit;
      return "$me $result->{success} (downloading CDRs)";
    }

    if ($result->{records} > 0 and !$cdr_batch) {
      # then create one
      my $cdrbatchname = 'pbxware-' . $self->exportnum . '-' . $ed->epoch;
      $cdr_batch = FS::cdr_batch->new({ cdrbatch => $cdrbatchname });
      $error = $cdr_batch->insert;
      if ( $error ) {
        dbh->rollback if $oldAutoCommit;
        return "$me $error (creating batch)";
      }
    }

    my @names = map { $column_map{$_} } @{ $result->{header} };
    my $rows = $result->{csv}; # not really CSV
    CDR: while (my $row = shift @$rows) {
      # Detect duplicates. Pages are returned most-recent first, so if a 
      # new CDR comes in between page fetches, the last row from the previous
      # page will get duplicated. This is normal; we just need to skip it.
      #
      # if this turns out to be too slow, we can keep a cache of the last 
      # page's IDs or something.
      my $uniqueid = md5_hex(join(',',@$row));
      if ( FS::cdr->row_exists('uniqueid = ?', $uniqueid) ) {
        warn "skipped duplicate row in page $page\n" if $DEBUG;
        next CDR;
      }

      my %hash = (
        cdrbatchnum => $cdr_batch->cdrbatchnum,
        uniqueid    => $uniqueid,
      );
      @hash{@names} = @$row;
      # strip non-numeric junk that sometimes gets appended to these (it 
      # causes problems creating Freeside detail records)
      foreach (qw(src dst)) {
        $hash{$_} =~ s/\D*$//;
      }

      my $cdr = FS::cdr->new(\%hash);
      $error = $cdr->insert;
      if ( $error ) {
        dbh->rollback if $oldAutoCommit;
        return "$me $error (inserting CDR: $row)";
      }
    }

    $more = $result->{next_page};
    $page++;
    $opt{page} = $page;

  } while ($more);

  dbh->commit if $oldAutoCommit;
  return $cdr_batch;
}

sub api_request {
  my $self = shift;
  my ($method, $content) = @_;
  $DEBUG ||= 1 if $self->option('debug');

# kludge to curb excessive paranoia in LWP 6.0+
local $ENV{'PERL_LWP_SSL_VERIFY_HOSTNAME'} = 0;

  my $url = 'https://' . $self->machine;
  my $request = POST($url,
    [ %$content,
      'apikey' => $self->option('apikey'),
      'action' => $method
    ]
  );
  warn "$me $method\n" if $DEBUG;
  warn $request->as_string."\n" if $DEBUG;

  my $ua = LWP::UserAgent->new;
  my $response = $ua->request($request);
  if ( !$response->is_success ) {
    return { success => $response->content };
  } 
  
  local $@;
  my $decoded_response = eval { decode_json($response->content) };
  if ( $@ ) {
    die "Error parsing response:\n" . $response->content . "\n\n";
  } 
  return $decoded_response;
} 

1;