PBXware CDRs: strip trailing non-numeric stuff from src/dst numbers, #34575
[freeside.git] / FS / FS / part_export / pbxware.pm
1 package FS::part_export::pbxware;
2
3 use base qw( FS::part_export );
4 use strict;
5
6 use Tie::IxHash;
7 use LWP::UserAgent;
8 use JSON;
9 use HTTP::Request::Common;
10 use Digest::MD5 qw(md5_hex);
11 use FS::Record qw(dbh);
12 use FS::cdr_batch;
13
14 our $me = '[pbxware]';
15 our $DEBUG = 0;
16 # our $DEBUG = 1; # log requests
17 # our $DEBUG = 2; # log requests and content of replies
18
19 tie my %options, 'Tie::IxHash',
20   'apikey'  => { label => 'API key' },
21   'debug'   => { label => 'Enable debugging', type => 'checkbox', value => 1 },
22 ; # best. API. ever.
23
24 our %info = (
25   'svc'         => [qw(svc_phone)],
26   'desc'        => 'Retrieve CDRs from Bicom PBXware',
27   'options'     => \%options,
28   'notes' => <<'END'
29 <P>Export to <a href="www.bicomsystems.com/pbxware-3-8">Bicom PBXware</a> 
30 softswitch.</P>
31 <P><I>This export does not provision services.</I> Currently you will need
32 to provision trunks and extensions through PBXware. The export only downloads 
33 CDRs.</P>
34 <P>Set the export machine to the name or IP address of your PBXware server,
35 and the API key to your alphanumeric key.</P>
36 END
37 );
38
39 sub export_insert {}
40 sub export_delete {}
41 sub export_replace {}
42 sub export_suspend {}
43 sub export_unsuspend {}
44
45 ################
46 # CALL DETAILS #
47 ################
48
49 =item import_cdrs START, END
50
51 Retrieves CDRs for calls in the date range from START to END and inserts them
52 as a new CDR batch. On success, returns a new cdr_batch object. On failure,
53 returns an error message. If there are no new CDRs, returns nothing.
54
55 =cut
56
57 # map their column names to cdr fields
58 # (warning: API docs are not quite accurate here)
59 our %column_map = (
60   'Tenant'      => 'accountcode',
61   'From'        => 'src',
62   'To'          => 'dst',
63   'Date/Time'   => 'startdate',
64   'Duration'    => 'duration',
65   'Billing'     => 'billsec',
66   'Cost'        => 'upstream_price', # might not be used
67   'Status'      => 'disposition',
68 );
69
70 sub import_cdrs {
71   my ($self, $start, $end) = @_;
72   $start ||= 0; # all CDRs ever
73   $end ||= time;
74   $DEBUG ||= $self->option('debug');
75
76   my $oldAutoCommit = $FS::UID::AutoCommit;
77   local $FS::UID::AutoCommit = 0;
78
79   my $sd = DateTime->from_epoch(epoch => $start)->set_time_zone('local');
80   my $ed = DateTime->from_epoch(epoch => $end)->set_time_zone('local');
81
82   my $error;
83
84   # Send a query.
85   #
86   # Other options supported:
87   # - trunk, ext: filter by source trunk and extension
88   # - trunkdst, extdst: filter by dest trunk and extension
89   # - server: filter by server id
90   # - status: filter by call status (answered, unanswered, busy, failed)
91   # - cdrtype: filter by call direction
92
93   my %opt = (
94     start     => $sd->strftime('%b-%d-%Y'),
95     starttime => $sd->strftime('%H:%M:%S'),
96     end       => $ed->strftime('%b-%d-%Y'),
97     endtime   => $ed->strftime('%H:%M:%S'),
98   );
99   # unlike Certain Other VoIP providers, this one does proper pagination if
100   # the result set is too big to fit in a single chunk.
101   my $page = 1;
102   my $more = 1;
103   my $cdr_batch;
104
105   do {
106     my $result = $self->api_request('pbxware.cdr.download', \%opt);
107     if ($result->{success} !~ /^success/i) {
108       dbh->rollback if $oldAutoCommit;
109       return "$me $result->{success} (downloading CDRs)";
110     }
111
112     if ($result->{records} > 0 and !$cdr_batch) {
113       # then create one
114       my $cdrbatchname = 'pbxware-' . $self->exportnum . '-' . $ed->epoch;
115       $cdr_batch = FS::cdr_batch->new({ cdrbatch => $cdrbatchname });
116       $error = $cdr_batch->insert;
117       if ( $error ) {
118         dbh->rollback if $oldAutoCommit;
119         return "$me $error (creating batch)";
120       }
121     }
122
123     my @names = map { $column_map{$_} } @{ $result->{header} };
124     my $rows = $result->{csv}; # not really CSV
125     CDR: while (my $row = shift @$rows) {
126       # Detect duplicates. Pages are returned most-recent first, so if a 
127       # new CDR comes in between page fetches, the last row from the previous
128       # page will get duplicated. This is normal; we just need to skip it.
129       #
130       # if this turns out to be too slow, we can keep a cache of the last 
131       # page's IDs or something.
132       my $uniqueid = md5_hex(join(',',@$row));
133       if ( FS::cdr->row_exists('uniqueid = ?', $uniqueid) ) {
134         warn "skipped duplicate row in page $page\n" if $DEBUG > 1;
135         next CDR;
136       }
137
138       my %hash = (
139         cdrbatchnum => $cdr_batch->cdrbatchnum,
140         uniqueid    => $uniqueid,
141       );
142       @hash{@names} = @$row;
143       # strip non-numeric junk that sometimes gets appended to these (it 
144       # causes problems creating Freeside detail records)
145       foreach (qw(src dst)) {
146         $hash{$_} =~ s/\D*$//;
147       }
148
149       my $cdr = FS::cdr->new(\%hash);
150       $error = $cdr->insert;
151       if ( $error ) {
152         dbh->rollback if $oldAutoCommit;
153         return "$me $error (inserting CDR: $row)";
154       }
155     }
156
157     $more = $result->{next_page};
158     $page++;
159     $opt{page} = $page;
160
161   } while ($more);
162
163   dbh->commit if $oldAutoCommit;
164   return $cdr_batch;
165 }
166
167 sub api_request {
168   my $self = shift;
169   my ($method, $content) = @_;
170   $DEBUG ||= 1 if $self->option('debug');
171   my $url = 'https://' . $self->machine;
172   my $request = POST($url,
173     [ %$content,
174       'apikey' => $self->option('apikey'),
175       'action' => $method
176     ]
177   );
178   warn "$me $method\n" if $DEBUG;
179   warn $request->as_string."\n" if $DEBUG > 1;
180
181   my $ua = LWP::UserAgent->new;
182   my $response = $ua->request($request);
183   if ( !$response->is_success ) {
184     return { success => $response->content };
185   } 
186   
187   local $@;
188   my $decoded_response = eval { decode_json($response->content) };
189   if ( $@ ) {
190     die "Error parsing response:\n" . $response->content . "\n\n";
191   } 
192   return $decoded_response;
193
194
195 1;