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