1 package FS::part_pkg::voip_cdr;
4 use vars qw(@ISA $DEBUG %info);
9 use FS::Record qw(qsearchs qsearch);
10 use FS::part_pkg::flat;
16 @ISA = qw(FS::part_pkg::prorate);
20 tie my %rating_method, 'Tie::IxHash',
21 'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
22 '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.',
23 'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
26 tie my %recur_method, 'Tie::IxHash',
27 'anniversary' => 'Charge the recurring fee at the frequency specified above',
28 'prorate' => 'Charge a prorated fee the first time (selectable billing date)',
29 'subscription' => 'Charge the full fee for the first partial period (selectable billing date)',
32 #tie my %cdr_location, 'Tie::IxHash',
33 # 'internal' => 'Internal: CDR records imported into the internal CDR table',
34 # 'external' => 'External: CDR records queried directly from an external '.
35 # 'Asterisk (or other?) CDR table',
38 tie my %temporalities, 'Tie::IxHash',
39 'upcoming' => "Upcoming (future)",
40 'preceding' => "Preceding (past)",
44 'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
45 'shortname' => 'VoIP/telco CDR rating (standard)',
47 'setup_fee' => { 'name' => 'Setup fee for this package',
50 'recur_fee' => { 'name' => 'Base recurring fee for this package',
54 #false laziness w/flat.pm
55 'recur_temporality' => { 'name' => 'Charge recurring fee for period',
57 'select_options' => \%temporalities,
60 'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
61 ' of service at cancellation',
65 'cutoff_day' => { 'name' => 'Billing Day (1 - 28) for prorating or '.
70 'recur_method' => { 'name' => 'Recurring fee method',
72 #'options' => \%recur_method,
74 'select_options' => \%recur_method,
77 'rating_method' => { 'name' => 'Region rating method',
79 'options' => \%rating_method,
82 'ratenum' => { 'name' => 'Rate plan',
84 'select_table' => 'rate',
85 'select_key' => 'ratenum',
86 'select_label' => 'ratename',
89 'ignore_unrateable' => { 'name' => 'Ignore calls without a rate in the rate tables. By default, the system will throw a fatal error upon encountering unrateable calls.',
93 'default_prefix' => { 'name' => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
97 'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
101 'domestic_prefix' => { 'name' => 'Destination prefix for domestic CDR records',
105 # 'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
106 # 'type' => 'checkbox',
109 'international_prefix' => { 'name' => 'Destination prefix for international CDR records',
113 'disable_tollfree' => { 'name' => 'Disable automatic toll-free processing',
114 'type' => 'checkbox',
117 'use_amaflags' => { 'name' => 'Do not charge for CDRs where the amaflags field is not set to "2" ("BILL"/"BILLING").',
118 'type' => 'checkbox',
121 'use_disposition' => { 'name' => 'Do not charge for CDRs where the disposition flag is not set to "ANSWERED".',
122 'type' => 'checkbox',
125 'use_disposition_taqua' => { 'name' => 'Do not charge for CDRs where the disposition is not set to "100" (Taqua).',
126 'type' => 'checkbox',
129 'use_carrierid' => { 'name' => 'Do not charge for CDRs where the Carrier ID is not set to: ',
132 'use_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is not set to: ',
135 'skip_dcontext' => { 'name' => 'Do not charge for CDRs where the dcontext is set to any of these (comma-separated) values:',
138 'skip_dstchannel_prefix' => { 'name' => 'Do not charge for CDRs where the dstchannel starts with:',
141 'skip_dst_length_less' => { 'name' => 'Do not charge for CDRs where the destination is less than this many digits:',
144 'skip_lastapp' => { 'name' => 'Do not charge for CDRs where the lastapp matches this value',
147 'use_duration' => { 'name' => 'Calculate usage based on the duration field instead of the billsec field',
148 'type' => 'checkbox',
151 '411_rewrite' => { 'name' => 'Rewrite these (comma-separated) destination numbers to 411 for rating purposes (also ignore any carrierid check): ',
154 'output_format' => { 'name' => 'CDR invoice display format',
156 'select_options' => { FS::cdr::invoice_formats() },
157 'default' => 'default', #XXX test
160 'usage_section' => { 'name' => 'Section in which to place separate usage charges',
163 'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
164 'type' => 'checkbox',
167 'bill_every_call' => { 'name' => 'Generate an invoice immediately for every call. Useful for prepaid.',
168 'type' => 'checkbox',
171 'count_available_phones' => { 'name' => 'Consider for tax purposes the number of lines to be svc_phones that may be provisioned rather than those that actually are.',
172 'type' => 'checkbox',
175 #XXX also have option for an external db
176 # 'cdr_location' => { 'name' => 'CDR database location'
177 # 'type' => 'select',
178 # 'select_options' => \%cdr_location,
179 # 'select_callback' => {
181 # 'enable' => [ 'datasrc', 'username', 'password' ],
184 # 'disable' => [ 'datasrc', 'username', 'password' ],
188 # 'datasrc' => { 'name' => 'DBI data source for external CDR table',
191 # 'username' => { 'name' => 'External database username',
194 # 'password' => { 'name' => 'External database password',
200 setup_fee recur_fee recur_temporality unused_credit
201 recur_method cutoff_day
202 rating_method ratenum ignore_unrateable
205 domestic_prefix international_prefix
207 use_amaflags use_disposition
208 use_disposition_taqua use_carrierid use_cdrtypenum
209 skip_dcontext skip_dstchannel_prefix
210 skip_dst_length_less skip_lastapp
213 output_format summarize_usage usage_section
215 count_available_phones
222 my($self, $cust_pkg ) = @_;
223 $self->option('setup_fee');
226 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
229 my($cust_pkg, $sdate, $details, $param ) = @_;
231 #my $last_bill = $cust_pkg->last_bill;
232 my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
235 if $self->option('recur_temporality', 1) eq 'preceding'
236 && ( $last_bill eq '' || $last_bill == 0 );
238 my $ratenum = $cust_pkg->part_pkg->option('ratenum');
240 my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
242 my %included_min = ();
246 my $downstream_cdr = '';
248 my $rating_method = $self->option('rating_method') || 'prefix';
249 my $intl = $self->option('international_prefix') || '011';
250 my $domestic_prefix = $self->option('domestic_prefix');
251 my $disable_tollfree = $self->option('disable_tollfree');
252 my $ignore_unrateable = $self->option('ignore_unrateable', 'Hush!');
253 my $use_duration = $self->option('use_duration');
255 my $output_format = $self->option('output_format', 'Hush!')
256 || ( $rating_method eq 'upstream_simple'
262 if ( $self->option('411_rewrite') ) {
263 my $dirass = $self->option('411_rewrite');
265 @dirass = split(',', $dirass);
268 #for check_chargable, so we don't keep looking up options inside the loop
271 eval "use Text::CSV_XS;";
273 my $csv = new Text::CSV_XS;
275 foreach my $cust_svc (
276 grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
280 $cust_svc->get_cdrs_for_update(
281 'disable_src' => $self->option('disable_src'),
282 'default_prefix' => $self->option('default_prefix'),
283 ) # $last_bill, $$sdate )
286 warn "rating CDR $cdr\n".
287 join('', map { " $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
291 my( $rate_region, $regionnum );
295 my @call_details = ();
296 if ( $rating_method eq 'prefix' ) {
299 if ( length($cdr->dst) && grep { $cdr->dst eq $_ } @dirass ){
304 my $reason = $self->check_chargable( $cdr,
305 'da_rewrote' => $da_rewrote,
306 'option_cache' => \%opt_cache,
311 warn "not charging for CDR ($reason)\n" if $DEBUG;
317 # look up rate details based on called station id
318 # (or calling station id for toll free calls)
321 my( $to_or_from, $number );
322 if ( $cdr->is_tollfree && ! $disable_tollfree )
324 $to_or_from = 'from';
326 } else { #regular call
331 warn "parsing call $to_or_from $number\n" if $DEBUG;
333 #remove non-phone# stuff and whitespace
336 # $dest =~ s/^(\w+):// and $proto = $1; #sip:
338 # $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
340 #determine the country code
342 if ( $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
343 || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
347 my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
348 #first look for 1 digit country code
349 if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
351 $number = $u1.$u2.$rest;
352 } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
355 } else { #3 digit country code
356 $countrycode = $three;
361 $countrycode = $domestic_prefix || '1';
362 $number =~ s/^$countrycode//;# if length($number) > 10;
365 warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
366 $pretty_destnum = "+$countrycode $number";
368 my $rate = qsearchs('rate', { 'ratenum' => $ratenum })
369 or die "ratenum $ratenum not found!";
371 $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
372 'phonenum' => $number,
375 if ( $rate_detail ) {
377 $rate_region = $rate_detail->dest_region;
378 $regionnum = $rate_region->regionnum;
379 warn " found rate for regionnum $regionnum ".
380 "and rate detail $rate_detail\n"
383 } elsif ( $ignore_unrateable ) {
387 #code below will throw a warning & skip
391 die "FATAL: no rate_detail found in ".
392 $rate->ratenum. ":". $rate->ratename. " rate plan ".
393 "for +$countrycode $number (CDR acctid ". $cdr->acctid. "); ".
394 "add a rate or set ignore_unrateable flag on the package def\n";
399 } elsif ( $rating_method eq 'upstream' ) { #XXX this was convergent, not currently used. very much becoming the odd one out. remove?
401 if ( $cdr->cdrtypenum == 1 ) { #rate based on upstream rateid
403 $rate_detail = $cdr->cdr_upstream_rate->rate_detail;
405 $regionnum = $rate_detail->dest_regionnum;
406 $rate_region = $rate_detail->dest_region;
408 $pretty_destnum = $cdr->dst;
410 warn " found rate for regionnum $regionnum and ".
411 "rate detail $rate_detail\n"
414 } else { #pass upstream price through
416 $charge = sprintf('%.2f', $cdr->upstream_price);
420 #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
421 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
425 $cdr->description, #$rate_region->regionname,
430 } elsif ( $rating_method eq 'upstream_simple' ) {
432 #XXX $charge = sprintf('%.2f', $cdr->upstream_price);
433 $charge = sprintf('%.3f', $cdr->upstream_price);
436 @call_details = ($cdr->downstream_csv( 'format' => $output_format,
440 $classnum = $cdr->calltypenum;
443 die "don't know how to rate CDRs using method: $rating_method\n";
447 # find the price and add detail to the invoice
450 # if $rate_detail is not found, skip this CDR... i.e.
451 # don't add it to invoice, don't set its status to done,
452 # don't call downstream_csv or something on it...
453 # but DO emit a warning...
454 #if ( ! $rate_detail && ! scalar(@call_details) ) {}
455 if ( ! $rate_detail && $charge eq '' ) {
457 warn "no rate_detail found for CDR.acctid: ". $cdr->acctid.
460 } else { # there *is* a rate_detail (or call_details), proceed...
462 unless ( @call_details || ( $charge ne '' && $charge == 0 ) ) {
464 $included_min{$regionnum} = $rate_detail->min_included
465 unless exists $included_min{$regionnum};
467 my $granularity = $rate_detail->sec_granularity;
469 # length($cdr->billsec) ? $cdr->billsec : $cdr->duration;
470 my $seconds = $use_duration ? $cdr->duration : $cdr->billsec;
472 $seconds += $granularity - ( $seconds % $granularity )
473 if $seconds # don't granular-ize 0 billsec calls (bills them)
474 && $granularity; # 0 is per call
475 my $minutes = sprintf("%.1f", $seconds / 60);
476 $minutes =~ s/\.0$// if $granularity == 60;
478 # per call rather than per minute
479 $minutes = 1 unless $granularity;
481 $included_min{$regionnum} -= $minutes;
483 if ( $included_min{$regionnum} < 0 ) {
484 my $charge_min = 0 - $included_min{$regionnum}; #XXX should preserve
486 $included_min{$regionnum} = 0;
487 $charge = sprintf('%.2f', ( $rate_detail->min_charge * $charge_min )
488 + 0.00000001 ); #so 1.005 rounds to 1.01
492 # this is why we need regionnum/rate_region....
493 warn " (rate region $rate_region)\n" if $DEBUG;
496 $cdr->downstream_csv( 'format' => $output_format,
497 'granularity' => $granularity,
498 'minutes' => $minutes,
500 'pretty_dst' => $pretty_destnum,
501 'dst_regionname' => $rate_region->regionname,
505 $classnum = $rate_detail->classnum;
510 #just use FS::cust_bill_pkg_detail objects?
513 #if ( $self->option('rating_method') eq 'upstream_simple' ) {
514 if ( scalar(@call_details) == 1 ) {
515 $call_details = [ 'C', $call_details[0], $charge, $classnum ];
516 } else { #only used for $rating_method eq 'upstream' now
517 $csv->combine(@call_details);
518 $call_details = [ 'C', $csv->string, $charge, $classnum ];
520 warn " adding details on charge to invoice: [ ".
521 join(', ', @{$call_details} ). " ]"
522 if ( $DEBUG && ref($call_details) );
523 push @$details, $call_details; #\@call_details,
526 # if the customer flag is on, call "downstream_csv" or something
527 # like it to export the call downstream!
528 # XXX price plan option to pick format, or something...
529 $downstream_cdr .= $cdr->downstream_csv( 'format' => 'convergent' )
532 my $error = $cdr->set_status_and_rated_price('done', $charge);
533 die $error if $error;
541 unshift @$details, [ 'C', FS::cdr::invoice_header($output_format) ]
542 if @$details && $rating_method ne 'upstream';
544 if ( $spool_cdr && length($downstream_cdr) ) {
546 use FS::UID qw(datasrc);
547 my $dir = '/usr/local/etc/freeside/export.'. datasrc. '/cdr';
548 mkdir $dir, 0700 unless -d $dir;
549 $dir .= '/'. $cust_pkg->custnum.
550 mkdir $dir, 0700 unless -d $dir;
551 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
553 push @{ $param->{'precommit_hooks'} },
555 #lock the downstream spool file and append the records
556 use Fcntl qw(:flock);
558 my $spool = new IO::File ">>$filename"
559 or die "can't open $filename: $!\n";
560 flock( $spool, LOCK_EX)
561 or die "can't lock $filename: $!\n";
563 or die "can't seek to end of $filename: $!\n";
564 print $spool $downstream_cdr;
565 flock( $spool, LOCK_UN );
569 } #if ( $spool_cdr && length($downstream_cdr) )
571 if ($param->{'increment_next_bill'}) {
572 my $recur_method = $self->option('recur_method', 1) || 'anniversary';
574 if ( $recur_method eq 'prorate' ) {
576 $charges += $self->SUPER::calc_recur(@_);
580 $charges += $self->option('recur_fee');
582 if ( $recur_method eq 'subscription' ) {
584 my $cutoff_day = $self->option('cutoff_day', 1) || 1;
585 my ($day, $mon, $year) = ( localtime($$sdate) )[ 3..5 ];
587 if ( $day < $cutoff_day ) {
588 if ( $mon == 0 ) { $mon=11; $year--; }
592 $$sdate = timelocal(0, 0, 0, $cutoff_day, $mon, $year);
594 }#$recur_method eq 'subscription'
595 }#$recur_method eq 'prorate'
596 }#increment_next_bill
601 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
602 sub check_chargable {
603 my( $self, $cdr, %flags ) = @_;
605 #should have some better way of checking these options from a hash
611 use_disposition_taqua
615 skip_dstchannel_prefix
619 foreach my $opt (grep !exists($flags{option_cache}->{$_}), @opt ) {
620 $flags{option_cache}->{$opt} = $self->option($opt, 1);
622 my %opt = %{ $flags{option_cache} };
624 return 'amaflags != 2'
625 if $opt{'use_amaflags'} && $cdr->amaflags != 2;
627 return 'disposition != ANSWERED'
628 if $opt{'use_disposition'} && $cdr->disposition ne 'ANSWERED';
630 return "disposition != 100"
631 if $opt{'use_disposition_taqua'} && $cdr->disposition != 100;
633 return "carrierid != $opt{'use_carrierid'}"
634 if length($opt{'use_carrierid'})
635 && $cdr->carrierid ne $opt{'use_carrierid'} #ne otherwise 0 matches ''
636 && ! $flags{'da_rewrote'};
638 return "cdrtypenum != $opt{'use_cdrtypenum'}"
639 if length($opt{'use_cdrtypenum'})
640 && $cdr->cdrtypenum ne $opt{'use_cdrtypenum'}; #ne otherwise 0 matches ''
642 return "dcontext IN ( $opt{'skip_dcontext'} )"
643 if $opt{'skip_dcontext'} =~ /\S/
644 && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $opt{'skip_dcontext'});
646 my $len_prefix = length($opt{'skip_dstchannel_prefix'});
647 return "dstchannel starts with $opt{'skip_dstchannel_prefix'}"
649 && substr($cdr->dstchannel,0,$len_prefix) eq $opt{'skip_dstchannel_prefix'};
651 my $dst_length = $opt{'skip_dst_length_less'};
652 return "destination less than $dst_length digits"
653 if $dst_length && length($cdr->dst) < $dst_length;
655 return "lastapp is $opt{'skip_lastapp'}"
656 if length($opt{'skip_lastapp'}) && $cdr->lastapp eq $opt{'skip_lastapp'};
658 #all right then, rate it
667 my($self, $cust_pkg) = @_;
668 $self->option('recur_fee');
671 # This equates svc_phone records; perhaps svc_phone should have a field
672 # to indicate it represents a line
674 my($self, $cust_pkg ) = @_;
676 if ( $self->option('count_available_phones', 1)) {
677 map { $count += ( $_->quantity || 0 ) }
678 grep { $_->part_svc->svcdb eq 'svc_phone' }
679 $cust_pkg->part_pkg->pkg_svc;
682 scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);