1 package FS::part_pkg::voip_cdr;
2 use base qw( FS::part_pkg::recur_Common );
5 use vars qw( $DEBUG %info );
10 use FS::Record qw(qsearchs qsearch);
18 tie my %cdr_svc_method, 'Tie::IxHash',
19 'svc_phone.phonenum' => 'Phone numbers (svc_phone.phonenum)',
20 'svc_pbx.title' => 'PBX name (svc_pbx.title)',
21 'svc_pbx.svcnum' => 'Freeside service # (svc_pbx.svcnum)',
24 tie my %rating_method, 'Tie::IxHash',
25 'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
26 # '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.',
27 'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
28 'single_price' => 'A single price per minute for all calls.',
31 #tie my %cdr_location, 'Tie::IxHash',
32 # 'internal' => 'Internal: CDR records imported into the internal CDR table',
33 # 'external' => 'External: CDR records queried directly from an external '.
34 # 'Asterisk (or other?) CDR table',
37 tie my %temporalities, 'Tie::IxHash',
38 'upcoming' => "Upcoming (future)",
39 'preceding' => "Preceding (past)",
42 tie my %granularity, 'Tie::IxHash', FS::rate_detail::granularities();
44 # previously "1" was "ignore"
45 tie my %unrateable_opts, 'Tie::IxHash',
46 '' => 'Exit with a fatal error',
47 1 => 'Ignore and continue',
48 2 => 'Flag for later review',
52 'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
53 'shortname' => 'VoIP/telco CDR rating (standard)',
54 'inherit_fields' => [ 'prorate_Mixin', 'global_Mixin' ],
56 'suspend_bill' => { 'name' => 'Continue recurring billing while suspended',
59 #false laziness w/flat.pm
60 'recur_temporality' => { 'name' => 'Charge recurring fee for period',
62 'select_options' => \%temporalities,
65 'cutoff_day' => { 'name' => 'Billing Day (1 - 28) for prorating or '.
69 'recur_method' => { 'name' => 'Recurring fee method',
71 #'options' => \%recur_method,
73 'select_options' => \%FS::part_pkg::recur_Common::recur_method,
76 'cdr_svc_method' => { 'name' => 'CDR service matching method',
78 'options' => \%cdr_svc_method,
81 'rating_method' => { 'name' => 'Rating method',
83 'options' => \%rating_method,
86 'ratenum' => { 'name' => 'Rate plan',
88 'select_table' => 'rate',
89 'select_key' => 'ratenum',
90 'select_label' => 'ratename',
93 'intrastate_ratenum' => { 'name' => 'Optional alternate intrastate rate plan',
95 'select_table' => 'rate',
96 'select_key' => 'ratenum',
97 'select_label' => 'ratename',
102 'min_included' => { 'name' => 'Minutes included when using the "single price per minute" rating method or when using the "prefix" rating method ("region group" billing)',
105 'min_charge' => { 'name' => 'Charge per minute when using "single price per minute" rating method',
108 'sec_granularity' => { 'name' => 'Granularity when using "single price per minute" rating method',
110 'select_options' => \%granularity,
113 'ignore_unrateable' => { 'name' => 'Handling of calls without a rate in the rate table',
115 'select_options' => \%unrateable_opts,
118 'default_prefix' => { 'name' => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
122 'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
126 'domestic_prefix' => { 'name' => 'Destination prefix for domestic CDR records',
130 # 'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
131 # 'type' => 'checkbox',
134 'international_prefix' => { 'name' => 'Destination prefix for international CDR records',
138 'disable_tollfree' => { 'name' => 'Disable automatic toll-free processing',
139 'type' => 'checkbox',
142 'use_amaflags' => { 'name' => 'Only charge for CDRs where the amaflags field is set to "2" ("BILL"/"BILLING").',
143 'type' => 'checkbox',
146 'use_carrierid' => { 'name' => 'Only charge for CDRs where the Carrier ID is set to: ',
149 'use_cdrtypenum' => { 'name' => 'Only charge for CDRs where the CDR Type is set to: ',
152 'ignore_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is set to: ',
155 'ignore_disposition' => { 'name' => 'Do not charge for CDRs where the Disposition is set to any of these (comma-separated) values: ',
158 'disposition_in' => { 'name' => 'Only charge for CDRs where the Disposition is set to any of these (comma-separated) values: ',
161 'skip_dst_prefix' => { 'name' => 'Do not charge for CDRs where the destination number starts with any of these values: ',
164 'skip_dcontext' => { 'name' => 'Do not charge for CDRs where the dcontext is set to any of these (comma-separated) values: ',
167 'skip_dstchannel_prefix' => { 'name' => 'Do not charge for CDRs where the dstchannel starts with:',
170 'skip_src_length_more' => { 'name' => 'Do not charge for CDRs where the source is more than this many digits:',
173 'noskip_src_length_accountcode_tollfree' => { 'name' => 'Do charge for CDRs where source is equal or greater than the specified digits, when accountcode is toll free',
174 'type' => 'checkbox',
177 'accountcode_tollfree_ratenum' => {
178 'name' => 'Optional alternate rate plan when accountcode is toll free: ',
180 'select_table' => 'rate',
181 'select_key' => 'ratenum',
182 'select_label' => 'ratename',
183 'disable_empty' => 0,
187 'skip_dst_length_less' => { 'name' => 'Do not charge for CDRs where the destination is less than this many digits:',
190 'noskip_dst_length_accountcode_tollfree' => { 'name' => 'Do charge for CDRs where dst is less than the specified digits, when accountcode is toll free',
191 'type' => 'checkbox',
194 'skip_lastapp' => { 'name' => 'Do not charge for CDRs where the lastapp matches this value: ',
197 'skip_max_callers' => { 'name' => 'Do not charge for CDRs where max_callers is less than or equal to this value: ',
200 'use_duration' => { 'name' => 'Calculate usage based on the duration field instead of the billsec field',
201 'type' => 'checkbox',
204 '411_rewrite' => { 'name' => 'Rewrite these (comma-separated) destination numbers to 411 for rating purposes (also ignore any carrierid check): ',
207 #false laziness w/cdr_termination.pm
208 'output_format' => { 'name' => 'CDR invoice display format',
210 'select_options' => { FS::cdr::invoice_formats() },
211 'default' => 'default', #XXX test
214 'usage_section' => { 'name' => 'Section in which to place usage charges (whether separated or not): ',
217 'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
218 'type' => 'checkbox',
221 'usage_mandate' => { 'name' => 'Always put usage details in separate section',
222 'type' => 'checkbox',
226 'bill_every_call' => { 'name' => 'Generate an invoice immediately for every call (as well any setup fee, upon first payment). Useful for prepaid.',
227 'type' => 'checkbox',
230 'bill_inactive_svcs' => { 'name' => 'Bill for all phone numbers that were active during the billing period',
231 'type' => 'checkbox',
234 '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.',
235 'type' => 'checkbox',
238 #XXX also have option for an external db? these days we suck them into ours
239 # 'cdr_location' => { 'name' => 'CDR database location'
240 # 'type' => 'select',
241 # 'select_options' => \%cdr_location,
242 # 'select_callback' => {
244 # 'enable' => [ 'datasrc', 'username', 'password' ],
247 # 'disable' => [ 'datasrc', 'username', 'password' ],
251 # 'datasrc' => { 'name' => 'DBI data source for external CDR table',
254 # 'username' => { 'name' => 'External database username',
257 # 'password' => { 'name' => 'External database password',
264 recur_method cutoff_day ),
265 FS::part_pkg::prorate_Mixin::fieldorder,
268 rating_method ratenum intrastate_ratenum
269 min_charge min_included sec_granularity
273 domestic_prefix international_prefix
277 use_cdrtypenum ignore_cdrtypenum
278 ignore_disposition disposition_in
279 skip_dcontext skip_dst_prefix
280 skip_dstchannel_prefix skip_src_length_more
281 noskip_src_length_accountcode_tollfree
282 accountcode_tollfree_ratenum
284 noskip_dst_length_accountcode_tollfree
289 output_format usage_mandate summarize_usage usage_section
290 bill_every_call bill_inactive_svcs
291 count_available_phones suspend_bill
299 my $str = $self->SUPER::price_info;
300 $str .= " plus usage" if $str;
306 my($cust_pkg, $sdate, $details, $param ) = @_;
310 $charges += $self->calc_usage(@_);
311 $charges += $self->calc_recur_Common(@_);
319 my($cust_pkg, $sdate, $details, $param ) = @_;
321 $self->calc_usage(@_);
324 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
328 my($cust_pkg, $sdate, $details, $param ) = @_;
330 #my $last_bill = $cust_pkg->last_bill;
331 my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
334 if $self->recur_temporality eq 'preceding'
335 && ( $last_bill eq '' || $last_bill == 0 );
339 my $included_min = $self->option('min_included', 1) || 0; #single price rating
341 my $cdr_svc_method = $self->option('cdr_svc_method',1)||'svc_phone.phonenum';
342 my $rating_method = $self->option('rating_method') || 'prefix';
343 my $region_group_included_min = $self->option('min_included',1) || 0;
344 my %region_group_included_min = ();
346 my $output_format = $self->option('output_format', 'Hush!')
347 || ( $rating_method eq 'upstream_simple'
352 my $use_duration = $self->option('use_duration');
354 my $csv = new Text::CSV_XS;
356 my($svc_table, $svc_field) = split('\.', $cdr_svc_method);
359 if( $self->option('bill_inactive_svcs',1) ) {
360 #XXX in this mode do we need to restrict the set of CDRs by date also?
361 @cust_svc = $cust_pkg->h_cust_svc($$sdate, $last_bill);
364 @cust_svc = $cust_pkg->cust_svc;
366 @cust_svc = grep { $_->part_svc->svcdb eq $svc_table } @cust_svc;
368 foreach my $cust_svc (@cust_svc) {
371 if( $self->option('bill_inactive_svcs',1) ) {
372 $svc_x = $cust_svc->h_svc_x($$sdate, $last_bill);
375 $svc_x = $cust_svc->svc_x;
379 'disable_src' => $self->option('disable_src'),
380 'default_prefix' => $self->option('default_prefix'),
381 'cdrtypenum' => $self->option('use_cdrtypenum'),
384 ); # $last_bill, $$sdate )
385 $options{'by_svcnum'} = 1 if $svc_field eq 'svcnum';
387 my @invoice_details_sort;
389 #first rate any outstanding CDRs not yet rated
391 $svc_x->get_cdrs( %options )
394 my $error = $cdr->rate(
396 'svcnum' => $svc_x->svcnum,
397 'single_price_included_min' => \$included_min,
398 'region_group_included_min' => \$region_group_included_min,
399 'region_group_included_min_hashref' => \%region_group_included_min,
401 die $error if $error; #??
405 #then add details to invoices & get a total
406 $options{'status'} = 'rated';
408 $svc_x->get_cdrs( %options )
412 my @call_details = ();
414 if ( $rating_method eq 'prefix' ) {
416 $classnum = $cdr->rated_classnum;
418 unless ( $self->sum_usage ) {
419 @call_details = ($cdr->downstream_csv(
420 'format' => $output_format,
421 'granularity' => $cdr->rated_granularity,
422 'seconds' =>($use_duration ? $cdr->duration : $cdr->billsec),
423 'charge' => $cdr->rated_price,
424 'pretty_dst' => $cdr->rated_pretty_dst,
425 'dst_regionname' => $cdr->rated_regionname,
430 } elsif ( $rating_method eq 'upstream_simple' ) {
432 $classnum = $cdr->calltypenum; #? meaningful these days?
434 @call_details = ($cdr->downstream_csv(
435 'format' => $output_format,
436 'charge' => $cdr->rated_price,
439 } elsif ( $rating_method eq 'single_price' ) {
441 my $granularity = length($self->option_cacheable('sec_granularity'))
442 ? $self->option_cacheable('sec_granularity')
445 @call_details = ($cdr->downstream_csv(
446 'format' => $output_format,
447 'charge' => $cdr->rated_price,
448 'seconds' => ($use_duration ? $cdr->duration : $cdr->billsec),
449 'granularity' => $granularity,
453 die "don't know how to rate CDRs using method: $rating_method\n";
456 $charges += $cdr->rated_price;
458 #if ( $cdr->rated_price > 0 ) {
459 # generate a detail record for every call; filter out
460 # $cdr->rated_price == 0 # later.
462 my $phonenum = $svc_x->phonenum;
464 if ( scalar(@call_details) == 1 ) {
467 detail => $call_details[0],
468 amount => $cdr->rated_price,
469 classnum => $classnum,
470 phonenum => $phonenum,
471 accountcode => $cdr->accountcode,
472 startdate => $cdr->startdate,
473 duration => $cdr->rated_seconds,
474 regionname => $cdr->rated_regionname,
476 } else { #only used for $rating_method eq 'upstream' now
477 # and for sum_ formats
478 $csv->combine(@call_details);
481 detail => $csv->string,
482 amount => $cdr->rated_price,
483 classnum => $classnum,
484 phonenum => $phonenum,
485 accountcode => $cdr->accountcode,
486 startdate => $cdr->startdate,
487 duration => $cdr->rated_seconds,
488 regionname => $cdr->rated_regionname,
491 $call_details->{'ratename'} = $cdr->rated_ratename;
493 push @invoice_details_sort, [ $call_details, $cdr->calldate_unix ];
496 my $error = $cdr->set_status('done');
497 die $error if $error; #??
501 if ( !$self->sum_usage ) {
503 my @sorted_invoice_details =
504 sort { @{$a}[1] <=> @{$b}[1] } @invoice_details_sort;
505 foreach my $sorted_call_detail ( @sorted_invoice_details ) {
506 my $d = $sorted_call_detail->[0];
507 push @$details, $d if $d->{amount} > 0;
510 else { #$self->sum_usage
511 push @$details, $self->sum_detail($svc_x, \@invoice_details_sort);
515 unshift @$details, { format => 'C',
516 detail => FS::cdr::invoice_header($output_format),
518 if @$details && $rating_method ne 'upstream';
523 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
524 sub check_chargable {
525 my( $self, $cdr, %flags ) = @_;
527 return 'amaflags != 2'
528 if $self->option_cacheable('use_amaflags') && $cdr->amaflags != 2;
530 return "disposition NOT IN ( $self->option_cacheable('disposition_in') )"
531 if $self->option_cacheable('disposition_in') =~ /\S/
532 && !grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $self->option_cacheable('disposition_in'));
534 return "disposition IN ( $self->option_cacheable('ignore_disposition') )"
535 if $self->option_cacheable('ignore_disposition') =~ /\S/
536 && grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $self->option_cacheable('ignore_disposition'));
538 foreach(split(/\s*,\s*/, $self->option_cacheable('skip_dst_prefix'))) {
539 return "dst starts with '$_'"
540 if length($_) && substr($cdr->dst,0,length($_)) eq $_;
543 return "carrierid != $self->option_cacheable('use_carrierid')"
544 if length($self->option_cacheable('use_carrierid'))
545 && $cdr->carrierid ne $self->option_cacheable('use_carrierid') #ne otherwise 0 matches ''
546 && ! $flags{'da_rewrote'};
548 # unlike everything else, use_cdrtypenum is applied in FS::svc_x::get_cdrs.
549 return "cdrtypenum != $self->option_cacheable('use_cdrtypenum')"
550 if length($self->option_cacheable('use_cdrtypenum'))
551 && $cdr->cdrtypenum ne $self->option_cacheable('use_cdrtypenum'); #ne otherwise 0 matches ''
553 return "cdrtypenum == $self->option_cacheable('ignore_cdrtypenum')"
554 if length($self->option_cacheable('ignore_cdrtypenum'))
555 && $cdr->cdrtypenum eq $self->option_cacheable('ignore_cdrtypenum'); #eq otherwise 0 matches ''
557 return "dcontext IN ( $self->option_cacheable('skip_dcontext') )"
558 if $self->option_cacheable('skip_dcontext') =~ /\S/
559 && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $self->option_cacheable('skip_dcontext'));
561 my $len_prefix = length($self->option_cacheable('skip_dstchannel_prefix'));
562 return "dstchannel starts with $self->option_cacheable('skip_dstchannel_prefix')"
564 && substr($cdr->dstchannel,0,$len_prefix) eq $self->option_cacheable('skip_dstchannel_prefix');
566 my $dst_length = $self->option_cacheable('skip_dst_length_less');
567 return "destination less than $dst_length digits"
568 if $dst_length && length($cdr->dst) < $dst_length
569 && ! ( $self->option_cacheable('noskip_dst_length_accountcode_tollfree')
570 && $cdr->is_tollfree('accountcode')
573 return "lastapp is $self->option_cacheable('skip_lastapp')"
574 if length($self->option_cacheable('skip_lastapp')) && $cdr->lastapp eq $self->option_cacheable('skip_lastapp');
576 my $src_length = $self->option_cacheable('skip_src_length_more');
579 if ( $self->option_cacheable('noskip_src_length_accountcode_tollfree') ) {
581 if ( $cdr->is_tollfree('accountcode') ) {
582 return "source less than or equal to $src_length digits"
583 if length($cdr->src) <= $src_length;
585 return "source more than $src_length digits"
586 if length($cdr->src) > $src_length;
590 return "source more than $src_length digits"
591 if length($cdr->src) > $src_length;
596 return "max_callers <= ". $self->option_cacheable('skip_max_callers')
597 if length($self->option_cacheable('skip_max_callers'))
598 and length($cdr->max_callers)
599 and $cdr->max_callers <= $self->option_cacheable('skip_max_callers');
601 #all right then, rate it
609 # This equates svc_phone records; perhaps svc_phone should have a field
610 # to indicate it represents a line
612 my($self, $cust_pkg ) = @_;
614 if ( $self->option('count_available_phones', 1)) {
615 map { $count += ( $_->quantity || 0 ) }
616 grep { $_->part_svc->svcdb eq 'svc_phone' }
617 $cust_pkg->part_pkg->pkg_svc;
620 scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
625 # tells whether cust_bill_pkg_detail should return a single line for
629 $self->option('output_format') =~ /^sum_/;
635 my $invoice_details = shift || [];
636 return () if !@$invoice_details;
637 my $details_by_rate = {};
638 # combine the entire set of CDRs
639 foreach ( @$invoice_details ) {
641 my $sum = $details_by_rate->{ $d->{ratename} } ||= {
646 phonenum => $svc_x->phonenum,
647 accountcode => '', #XXX
648 startdate => '', #XXX
652 $sum->{amount} += $d->{amount};
653 $sum->{duration} += $d->{duration};
657 foreach my $ratename ( sort keys(%$details_by_rate) ) {
658 my $sum = $details_by_rate->{$ratename};
659 next if $sum->{count} == 0;
660 my $total_cdr = FS::cdr->new({
661 'billsec' => $sum->{duration},
662 'src' => $sum->{phonenum},
664 $sum->{detail} = $total_cdr->downstream_csv(
665 format => $self->option('output_format'),
666 seconds => $sum->{duration},
667 charge => sprintf('%.2f',$sum->{amount}),
668 ratename => $ratename,
669 phonenum => $sum->{phonenum},
670 count => $sum->{count},
677 # and whether cust_bill should show a detail line for the service label
678 # (separate from usage details)
679 sub hide_svc_detail {
681 $self->option('output_format') =~ /^sum_/;