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;
14 @ISA = qw(FS::part_pkg::flat);
18 tie my %rating_method, 'Tie::IxHash',
19 'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
20 '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.',
21 'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
24 #tie my %cdr_location, 'Tie::IxHash',
25 # 'internal' => 'Internal: CDR records imported into the internal CDR table',
26 # 'external' => 'External: CDR records queried directly from an external '.
27 # 'Asterisk (or other?) CDR table',
30 tie my %temporalities, 'Tie::IxHash',
31 'upcoming' => "Upcoming (future)",
32 'preceding' => "Preceding (past)",
36 'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
37 'shortname' => 'VoIP/telco CDR rating (standard)',
39 'setup_fee' => { 'name' => 'Setup fee for this package',
42 'recur_fee' => { 'name' => 'Base recurring fee for this package',
46 #false laziness w/flat.pm
47 'recur_temporality' => { 'name' => 'Charge recurring fee for period',
49 'select_options' => \%temporalities,
52 'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
53 ' of service at cancellation',
56 'ratenum' => { 'name' => 'Rate plan',
58 'select_table' => 'rate',
59 'select_key' => 'ratenum',
60 'select_label' => 'ratename',
62 'rating_method' => { 'name' => 'Region rating method',
64 'options' => \%rating_method,
67 'default_prefix' => { 'name' => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
71 'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
75 'domestic_prefix' => { 'name' => 'Destination prefix for domestic CDR records',
79 # 'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
80 # 'type' => 'checkbox',
83 'international_prefix' => { 'name' => 'Destination prefix(es) for international CDR records. Separate multiple options with commas.',
87 'use_amaflags' => { 'name' => 'Do not charge for CDRs where the amaflags field is not set to "2" ("BILL"/"BILLING").',
91 'use_disposition' => { 'name' => 'Do not charge for CDRs where the disposition flag is not set to "ANSWERED".',
95 'use_disposition_taqua' => { 'name' => 'Do not charge for CDRs where the disposition is not set to "100" (Taqua).',
99 'use_carrierid' => { 'name' => 'Do not charge for CDRs where the Carrier ID is not set to: ',
102 'use_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is not set to: ',
105 '411_rewrite' => { 'name' => 'Rewrite these (comma-separated) destination numbers to 411 for rating purposes: ',
108 'output_format' => { 'name' => 'Simple output format',
110 'select_options' => { FS::cdr::invoice_formats() },
113 'usage_section' => { 'name' => 'Section in which to place separate usage charges',
116 'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
117 'type' => 'checkbox',
120 #XXX also have option for an external db
121 # 'cdr_location' => { 'name' => 'CDR database location'
122 # 'type' => 'select',
123 # 'select_options' => \%cdr_location,
124 # 'select_callback' => {
126 # 'enable' => [ 'datasrc', 'username', 'password' ],
129 # 'disable' => [ 'datasrc', 'username', 'password' ],
133 # 'datasrc' => { 'name' => 'DBI data source for external CDR table',
136 # 'username' => { 'name' => 'External database username',
139 # 'password' => { 'name' => 'External database password',
145 setup_fee recur_fee recur_temporality unused_credit
146 rating_method ratenum
149 domestic_prefix international_prefix
150 use_amaflags use_disposition
151 use_disposition_taqua use_carrierid use_cdrtypenum
153 output_format summarize_usage usage_section
160 my($self, $cust_pkg ) = @_;
161 $self->option('setup_fee');
164 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
166 my($self, $cust_pkg, $sdate, $details, $param ) = @_;
168 #my $last_bill = $cust_pkg->last_bill;
169 my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
172 if $self->option('recur_temporality', 1) eq 'preceding' && $last_bill == 0;
174 my $ratenum = $cust_pkg->part_pkg->option('ratenum');
176 my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
178 my %included_min = ();
182 my $downstream_cdr = '';
184 my $output_format = $self->option('output_format', 'Hush!')
187 eval "use Text::CSV_XS;";
189 my $csv = new Text::CSV_XS;
191 foreach my $cust_svc (
192 grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
196 $cust_svc->get_cdrs_for_update( 'disable_src' => $self->option('disable_src'),
197 'default_prefix' => $self->option('default_prefix'),
198 ) # $last_bill, $$sdate )
201 warn "rating CDR $cdr\n".
202 join('', map { " $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
206 my( $rate_region, $regionnum );
210 my @call_details = ();
211 if ( $self->option('rating_method') eq 'prefix'
212 || ! $self->option('rating_method')
216 #should have some better way of checking these options than a long
218 my $notchg = "not charging for CDR";
220 if ( $self->option('use_amaflags') && $cdr->amaflags != 2 ) {
222 warn "$notchg (amaflags != 2)\n" if $DEBUG;
225 } elsif ( $self->option('use_disposition')
226 && $cdr->disposition ne 'ANSWERED' ) {
228 warn "$notchg (disposition != ANSWERED)\n" if $DEBUG;
231 } elsif ( $self->option('use_disposition_taqua')
232 && $cdr->disposition != 100 ) {
234 warn "$notchg (disposition != 100)\n" if $DEBUG;
237 } elsif ( $self->option('use_carrierid')
238 && $cdr->carrierid != $self->option('use_carrierid') ) {
240 warn "$notchg (carrierid != ". $self->option('use_carrierid'). ")\n"
244 } elsif ( $self->option('use_cdrtypenum')
245 && $cdr->cdrtypenum != $self->option('use_cdrtypenum') ) {
247 warn "$notchg (cdrtypenum != ". $self->option('use_cdrtypenum'). ")\n"
254 # look up rate details based on called station id
255 # (or calling station id for toll free calls)
258 if ( $self->option('411_rewrite') ) {
259 my @dirass = split(/\s*,\s*/, $self->option('411_rewrite'));
260 $cdr->dst('411') if grep $cdr->dst eq $_, @dirass;
263 my( $to_or_from, $number );
264 if ( $cdr->dst =~ /^(\+?1)?8([02-8])\1/ ) { #tollfree call
265 $to_or_from = 'from';
267 } else { #regular call
272 #remove non-phone# stuff and whitespace
275 # $dest =~ s/^(\w+):// and $proto = $1; #sip:
277 # $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
279 my $intl = $self->option('international_prefix') || '011';
281 if ( $intl =~ /,/ ) {
282 @intl = split(/\s*,\s*/, $intl);
286 #determine the country code
288 if ( grep { $number =~ /^$_(((\d)(\d))(\d))(\d+)$/ } @intl
289 || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
293 my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
294 #first look for 1 digit country code
295 if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
297 $number = $u1.$u2.$rest;
298 } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
301 } else { #3 digit country code
302 $countrycode = $three;
307 $countrycode = $self->option('domestic_prefix') || '1';
308 $number =~ s/^$countrycode//;# if length($number) > 10;
311 warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
312 $pretty_destnum = "+$countrycode $number";
314 #find a rate prefix, first look at most specific (4 digits) then 3, etc.,
315 # finally trying the country code only
316 my $rate_prefix = '';
317 for my $len ( reverse(1..6) ) {
318 $rate_prefix = qsearchs('rate_prefix', {
319 'countrycode' => $countrycode,
320 #'npa' => { op=> 'LIKE', value=> substr($number, 0, $len) }
321 'npa' => substr($number, 0, $len),
324 $rate_prefix ||= qsearchs('rate_prefix', {
325 'countrycode' => $countrycode,
330 die "Can't find rate for call $to_or_from +$countrycode $number\n"
333 $regionnum = $rate_prefix->regionnum;
334 $rate_detail = qsearchs('rate_detail', {
335 'ratenum' => $ratenum,
336 'dest_regionnum' => $regionnum,
339 $rate_region = $rate_prefix->rate_region;
341 warn " found rate for regionnum $regionnum ".
342 "and rate detail $rate_detail\n"
347 } elsif ( $self->option('rating_method') eq 'upstream' ) {
349 if ( $cdr->cdrtypenum == 1 ) { #rate based on upstream rateid
351 $rate_detail = $cdr->cdr_upstream_rate->rate_detail;
353 $regionnum = $rate_detail->dest_regionnum;
354 $rate_region = $rate_detail->dest_region;
356 $pretty_destnum = $cdr->dst;
358 warn " found rate for regionnum $regionnum and ".
359 "rate detail $rate_detail\n"
362 } else { #pass upstream price through
364 $charge = sprintf('%.2f', $cdr->upstream_price);
368 #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
369 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
373 $cdr->description, #$rate_region->regionname,
378 } elsif ( $self->option('rating_method') eq 'upstream_simple' ) {
380 #XXX $charge = sprintf('%.2f', $cdr->upstream_price);
381 $charge = sprintf('%.3f', $cdr->upstream_price);
384 @call_details = ($cdr->downstream_csv( 'format' => $output_format ));
387 die "don't know how to rate CDRs using method: ".
388 $self->option('rating_method'). "\n";
392 # find the price and add detail to the invoice
395 # if $rate_detail is not found, skip this CDR... i.e.
396 # don't add it to invoice, don't set its status to NULL,
397 # don't call downstream_csv or something on it...
398 # but DO emit a warning...
399 #if ( ! $rate_detail && ! scalar(@call_details) ) {
400 if ( ! $rate_detail && $charge eq '' ) {
402 warn "no rate_detail found for CDR.acctid: ". $cdr->acctid.
405 } else { # there *is* a rate_detail (or call_details), proceed...
407 unless ( @call_details || ( $charge ne '' && $charge == 0 ) ) {
409 $included_min{$regionnum} = $rate_detail->min_included
410 unless exists $included_min{$regionnum};
412 my $granularity = $rate_detail->sec_granularity;
413 my $seconds = $cdr->billsec; # length($cdr->billsec) ? $cdr->billsec : $cdr->duration;
414 $seconds += $granularity - ( $seconds % $granularity )
415 if $seconds # don't granular-ize 0 billsec calls (bills them)
416 && $granularity; # 0 is per call
417 my $minutes = sprintf("%.1f", $seconds / 60);
418 $minutes =~ s/\.0$// if $granularity == 60;
420 # per call rather than per minute
421 $minutes = 1 unless $granularity;
423 $included_min{$regionnum} -= $minutes;
425 if ( $included_min{$regionnum} < 0 ) {
426 my $charge_min = 0 - $included_min{$regionnum};
427 $included_min{$regionnum} = 0;
428 $charge = sprintf('%.2f', $rate_detail->min_charge * $charge_min );
432 # this is why we need regionnum/rate_region....
433 warn " (rate region $rate_region)\n" if $DEBUG;
436 #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
437 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
438 $granularity ? $minutes.'m' : $minutes.' call',
441 $rate_region->regionname,
444 $classnum = $rate_detail->classnum;
449 #just use FS::cust_bill_pkg_detail objects?
451 if ( $self->option('rating_method') eq 'upstream_simple' ) {
452 $call_details = [ 'C', $call_details[0], $charge, $classnum ];
454 $csv->combine(@call_details);
455 $call_details = [ 'C', $csv->string, $charge, $classnum ];
457 warn " adding details on charge to invoice: [ ".
458 join(', ', @{$call_details} ). " ]"
459 if ( $DEBUG && ref($call_details) );
460 push @$details, $call_details; #\@call_details,
463 # if the customer flag is on, call "downstream_csv" or something
464 # like it to export the call downstream!
465 # XXX price plan option to pick format, or something...
466 $downstream_cdr .= $cdr->downstream_csv( 'format' => 'convergent' )
469 my $error = $cdr->set_status_and_rated_price('done', $charge);
470 die $error if $error;
476 unshift @$details, [ 'C', FS::cdr::invoice_header( $output_format) ]
477 if (@$details && $self->option('rating_method') eq 'upstream_simple' );
481 if ( $spool_cdr && length($downstream_cdr) ) {
483 use FS::UID qw(datasrc);
484 my $dir = '/usr/local/etc/freeside/export.'. datasrc. '/cdr';
485 mkdir $dir, 0700 unless -d $dir;
486 $dir .= '/'. $cust_pkg->custnum.
487 mkdir $dir, 0700 unless -d $dir;
488 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
490 push @{ $param->{'precommit_hooks'} },
492 #lock the downstream spool file and append the records
493 use Fcntl qw(:flock);
495 my $spool = new IO::File ">>$filename"
496 or die "can't open $filename: $!\n";
497 flock( $spool, LOCK_EX)
498 or die "can't lock $filename: $!\n";
500 or die "can't seek to end of $filename: $!\n";
501 print $spool $downstream_cdr;
502 flock( $spool, LOCK_UN );
506 } #if ( $spool_cdr && length($downstream_cdr) )
508 $self->option('recur_fee') + $charges;
517 my($self, $cust_pkg) = @_;
518 $self->option('recur_fee');
521 # This equates svc_phone records; perhaps svc_phone should have a field
522 # to indicate it represents a line
524 my($self, $cust_pkg ) = @_;
525 scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);