1 package FS::part_pkg::voip_cdr;
4 use vars qw(@ISA $DEBUG %info);
8 use FS::Record qw(qsearchs qsearch);
9 use FS::part_pkg::flat;
13 @ISA = qw(FS::part_pkg::flat);
17 tie my %rating_method, 'Tie::IxHash',
18 'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
19 'upstream' => 'Rate calls based on upstream data: If the call type is "1", map the upstream rate ID directly to an internal rate (rate_detail), otherwise, pass the upstream price through directly.',
20 'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
23 #tie my %cdr_location, 'Tie::IxHash',
24 # 'internal' => 'Internal: CDR records imported into the internal CDR table',
25 # 'external' => 'External: CDR records queried directly from an external '.
26 # 'Asterisk (or other?) CDR table',
30 'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
31 'shortname' => 'VoIP/telco CDR rating (standard)',
33 'setup_fee' => { 'name' => 'Setup fee for this package',
36 'recur_fee' => { 'name' => 'Base recurring fee for this package',
39 'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
40 ' of service at cancellation',
43 'ratenum' => { 'name' => 'Rate plan',
45 'select_table' => 'rate',
46 'select_key' => 'ratenum',
47 'select_label' => 'ratename',
49 'rating_method' => { 'name' => 'Region rating method',
51 'options' => \%rating_method,
54 'default_prefix' => { 'name' => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
58 'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
62 'domestic_prefix' => { 'name' => 'Destination prefix for domestic CDR records',
66 # 'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
67 # 'type' => 'checkbox',
70 'international_prefix' => { 'name' => 'Destination prefix for international CDR records',
74 'use_amaflags' => { 'name' => 'Do not charge for CDRs where the amaflags field is not set to "2" ("BILL"/"BILLING").',
78 'use_disposition' => { 'name' => 'Do not charge for CDRs where the disposition flag is not set to "ANSWERED".',
82 #XXX also have option for an external db
83 # 'cdr_location' => { 'name' => 'CDR database location'
85 # 'select_options' => \%cdr_location,
86 # 'select_callback' => {
88 # 'enable' => [ 'datasrc', 'username', 'password' ],
91 # 'disable' => [ 'datasrc', 'username', 'password' ],
95 # 'datasrc' => { 'name' => 'DBI data source for external CDR table',
98 # 'username' => { 'name' => 'External database username',
101 # 'password' => { 'name' => 'External database password',
107 setup_fee recur_fee unused_credit
108 rating_method ratenum
111 domestic_prefix international_prefix
112 use_amaflags use_disposition
119 my($self, $cust_pkg ) = @_;
120 $self->option('setup_fee');
123 #false laziness w/voip_sqlradacct... resolve it if that one ever gets used again
125 my($self, $cust_pkg, $sdate, $details, $param ) = @_;
127 my $last_bill = $cust_pkg->last_bill;
129 my $ratenum = $cust_pkg->part_pkg->option('ratenum');
131 my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
133 my %included_min = ();
137 my $downstream_cdr = '';
139 foreach my $cust_svc (
140 grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
144 $cust_svc->get_cdrs_for_update() # $last_bill, $$sdate )
147 warn "rating CDR $cdr\n".
148 join('', map { " $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
152 my( $rate_region, $regionnum );
155 my @call_details = ();
156 if ( $self->option('rating_method') eq 'prefix'
157 || ! $self->option('rating_method')
161 if ( $self->option('use_amaflags') && $cdr->amaflags != 2 ) {
163 warn "not charging for CDR (amaflags != 2)\n" if $DEBUG;
166 } elsif ( $self->option('use_disposition')
167 && $cdr->disposition ne 'ANSWERED' ) {
169 warn "not charging for CDR (disposition != ANSWERED)\n" if $DEBUG;
175 # look up rate details based on called station id
176 # (or calling station id for toll free calls)
179 my( $to_or_from, $number );
180 if ( $cdr->dst =~ /^(\+?1)?8([02-8])\1/ ) { #tollfree call
181 $to_or_from = 'from';
183 } else { #regular call
188 #remove non-phone# stuff and whitespace
191 # $dest =~ s/^(\w+):// and $proto = $1; #sip:
193 # $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
195 my $intl = $self->option('international_prefix') || '011';
197 #determine the country code
199 if ( $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
200 || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
204 my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
205 #first look for 1 digit country code
206 if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
208 $number = $u1.$u2.$rest;
209 } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
212 } else { #3 digit country code
213 $countrycode = $three;
218 $countrycode = $self->option('domestic_prefix') || '1';
219 $number =~ s/^$countrycode//;# if length($number) > 10;
222 warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
223 $pretty_destnum = "+$countrycode $number";
225 #find a rate prefix, first look at most specific (4 digits) then 3, etc.,
226 # finally trying the country code only
227 my $rate_prefix = '';
228 for my $len ( reverse(1..6) ) {
229 $rate_prefix = qsearchs('rate_prefix', {
230 'countrycode' => $countrycode,
231 #'npa' => { op=> 'LIKE', value=> substr($number, 0, $len) }
232 'npa' => substr($number, 0, $len),
235 $rate_prefix ||= qsearchs('rate_prefix', {
236 'countrycode' => $countrycode,
241 die "Can't find rate for call $to_or_from +$countrycode $number\n"
244 $regionnum = $rate_prefix->regionnum;
245 $rate_detail = qsearchs('rate_detail', {
246 'ratenum' => $ratenum,
247 'dest_regionnum' => $regionnum,
250 $rate_region = $rate_prefix->rate_region;
252 warn " found rate for regionnum $regionnum ".
253 "and rate detail $rate_detail\n"
258 } elsif ( $self->option('rating_method') eq 'upstream' ) {
260 if ( $cdr->cdrtypenum == 1 ) { #rate based on upstream rateid
262 $rate_detail = $cdr->cdr_upstream_rate->rate_detail;
264 $regionnum = $rate_detail->dest_regionnum;
265 $rate_region = $rate_detail->dest_region;
267 $pretty_destnum = $cdr->dst;
269 warn " found rate for regionnum $regionnum and ".
270 "rate detail $rate_detail\n"
273 } else { #pass upstream price through
275 $charge = sprintf('%.2f', $cdr->upstream_price);
279 #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
280 time2str("%c", $cdr->calldate_unix), #XXX this should probably be a config option dropdown so they can select US vs- rest of world dates or whatnot
284 $cdr->description, #$rate_region->regionname,
289 } elsif ( $self->option('rating_method') eq 'upstream_simple' ) {
291 #XXX $charge = sprintf('%.2f', $cdr->upstream_price);
292 $charge = sprintf('%.3f', $cdr->upstream_price);
295 @call_details = ( $cdr->downstream_csv( 'format' => 'voxlinesystems' ));
298 die "don't know how to rate CDRs using method: ".
299 $self->option('rating_method'). "\n";
303 # find the price and add detail to the invoice
306 # if $rate_detail is not found, skip this CDR... i.e.
307 # don't add it to invoice, don't set its status to NULL,
308 # don't call downstream_csv or something on it...
309 # but DO emit a warning...
310 #if ( ! $rate_detail && ! scalar(@call_details) ) {
311 if ( ! $rate_detail && $charge eq '' ) {
313 warn "no rate_detail found for CDR.acctid: ". $cdr->acctid.
316 } else { # there *is* a rate_detail (or call_details), proceed...
318 unless ( @call_details || ( $charge ne '' && $charge == 0 ) ) {
320 $included_min{$regionnum} = $rate_detail->min_included
321 unless exists $included_min{$regionnum};
323 my $granularity = $rate_detail->sec_granularity;
324 my $seconds = $cdr->billsec; # length($cdr->billsec) ? $cdr->billsec : $cdr->duration;
325 $seconds += $granularity - ( $seconds % $granularity )
326 if $seconds # don't granular-ize 0 billsec calls (bills them)
327 && $granularity; # 0 is per call
328 my $minutes = sprintf("%.1f", $seconds / 60);
329 $minutes =~ s/\.0$// if $granularity == 60;
331 # per call rather than per minute
332 $minutes = 1 unless $granularity;
334 $included_min{$regionnum} -= $minutes;
336 if ( $included_min{$regionnum} < 0 ) {
337 my $charge_min = 0 - $included_min{$regionnum};
338 $included_min{$regionnum} = 0;
339 $charge = sprintf('%.2f', $rate_detail->min_charge * $charge_min );
343 # this is why we need regionnum/rate_region....
344 warn " (rate region $rate_region)\n" if $DEBUG;
347 #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
348 time2str("%c", $cdr->calldate_unix), #XXX this should probably be a config option dropdown so they can select US vs- rest of world dates or whatnot
349 $granularity ? $minutes.'m' : $minutes.' call',
352 $rate_region->regionname,
359 if ( $self->option('rating_method') eq 'upstream_simple' ) {
360 $call_details = [ 'C', $call_details[0] ];
362 $call_details = join(' - ', @call_details );
364 warn " adding details on charge to invoice: $call_details"
366 push @$details, $call_details; #\@call_details,
369 # if the customer flag is on, call "downstream_csv" or something
370 # like it to export the call downstream!
371 # XXX price plan option to pick format, or something...
372 $downstream_cdr .= $cdr->downstream_csv( 'format' => 'convergent' )
375 my $error = $cdr->set_status_and_rated_price('done', $charge);
376 die $error if $error;
382 unshift @$details, [ 'C', "Date,Time,Name,Destination,Duration,Price" ]
383 if (@$details && $self->option('rating_method') eq 'upstream_simple' );
387 if ( $spool_cdr && length($downstream_cdr) ) {
389 use FS::UID qw(datasrc);
390 my $dir = '/usr/local/etc/freeside/export.'. datasrc. '/cdr';
391 mkdir $dir, 0700 unless -d $dir;
392 $dir .= '/'. $cust_pkg->custnum.
393 mkdir $dir, 0700 unless -d $dir;
394 my $filename = time2str("$dir/CDR%Y%m%d-spool.CSV", time); #XXX invoice date instead? would require changing the order things are generated in cust_main::bill insert cust_bill first - with transactions it could be done though
396 push @{ $param->{'precommit_hooks'} },
398 #lock the downstream spool file and append the records
399 use Fcntl qw(:flock);
401 my $spool = new IO::File ">>$filename"
402 or die "can't open $filename: $!\n";
403 flock( $spool, LOCK_EX)
404 or die "can't lock $filename: $!\n";
406 or die "can't seek to end of $filename: $!\n";
407 print $spool $downstream_cdr;
408 flock( $spool, LOCK_UN );
412 } #if ( $spool_cdr && length($downstream_cdr) )
414 $self->option('recur_fee') + $charges;
423 my($self, $cust_pkg) = @_;
424 $self->option('recur_fee');
427 # This equates svc_phone records; perhaps svc_phone should have a field
428 # to indicate it represents a line
430 my($self, $cust_pkg ) = @_;
431 scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);