1 package FS::part_pkg::voip_cdr;
2 use base qw( FS::part_pkg::recur_Common );
5 use vars qw( $DEBUG %info );
6 use List::Util qw(first min);
11 use FS::Record qw(qsearchs qsearch);
19 tie my %cdr_svc_method, 'Tie::IxHash',
20 'svc_phone.phonenum' => 'Phone numbers (svc_phone.phonenum)',
21 'svc_pbx.title' => 'PBX name (svc_pbx.title)',
22 'svc_pbx.svcnum' => 'Freeside service # (svc_pbx.svcnum)',
25 tie my %rating_method, 'Tie::IxHash',
26 'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
27 # '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.',
28 'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
29 'single_price' => 'A single price per minute for all calls.',
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)",
43 tie my %granularity, 'Tie::IxHash', FS::rate_detail::granularities();
45 # previously "1" was "ignore"
46 tie my %unrateable_opts, 'Tie::IxHash',
47 '' => 'Exit with a fatal error',
48 1 => 'Ignore and continue',
49 2 => 'Flag for later review',
52 tie my %detail_formats, 'Tie::IxHash',
54 FS::cdr::invoice_formats()
58 'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
59 'shortname' => 'VoIP/telco CDR rating (standard)',
60 'inherit_fields' => [ 'prorate_Mixin', 'global_Mixin' ],
62 'suspend_bill' => { 'name' => 'Continue recurring billing while suspended',
65 #false laziness w/flat.pm
66 'recur_temporality' => { 'name' => 'Charge recurring fee for period',
68 'select_options' => \%temporalities,
71 'cutoff_day' => { 'name' => 'Billing Day (1 - 28) for prorating or '.
75 'recur_method' => { 'name' => 'Recurring fee method',
77 #'options' => \%recur_method,
79 'select_options' => \%FS::part_pkg::recur_Common::recur_method,
82 'cdr_svc_method' => { 'name' => 'CDR service matching method',
84 'options' => \%cdr_svc_method,
87 'rating_method' => { 'name' => 'Rating method',
89 'options' => \%rating_method,
92 'ratenum' => { 'name' => 'Rate plan',
94 'select_table' => 'rate',
95 'select_key' => 'ratenum',
96 'select_label' => 'ratename',
99 'intrastate_ratenum' => { 'name' => 'Optional alternate intrastate rate plan',
101 'select_table' => 'rate',
102 'select_key' => 'ratenum',
103 'select_label' => 'ratename',
104 'disable_empty' => 0,
108 'min_included' => { 'name' => 'Minutes included when using the "single price per minute" rating method or when using the "prefix" rating method ("region group" billing)',
111 'min_charge' => { 'name' => 'Charge per minute when using "single price per minute" rating method',
114 'sec_granularity' => { 'name' => 'Granularity when using "single price per minute" rating method',
116 'select_options' => \%granularity,
119 'ignore_unrateable' => { 'name' => 'Handling of calls without a rate in the rate table',
121 'select_options' => \%unrateable_opts,
124 'default_prefix' => { 'name' => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
128 'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
132 'domestic_prefix' => { 'name' => 'Destination prefix for domestic CDR records',
136 # 'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
137 # 'type' => 'checkbox',
140 'international_prefix' => { 'name' => 'Destination prefix for international CDR records',
144 'disable_tollfree' => { 'name' => 'Disable automatic toll-free processing',
145 'type' => 'checkbox',
148 'use_amaflags' => { 'name' => 'Only charge for CDRs where the amaflags field is set to "2" ("BILL"/"BILLING").',
149 'type' => 'checkbox',
152 'use_carrierid' => { 'name' => 'Only charge for CDRs where the Carrier ID is set to any of these (comma-separated) values: ',
155 'use_cdrtypenum' => { 'name' => 'Only charge for CDRs where the CDR Type is set to: ',
158 'ignore_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is set to: ',
161 'ignore_disposition' => { 'name' => 'Do not charge for CDRs where the Disposition is set to any of these (comma-separated) values: ',
164 'disposition_in' => { 'name' => 'Only charge for CDRs where the Disposition is set to any of these (comma-separated) values: ',
167 'skip_dst_prefix' => { 'name' => 'Do not charge for CDRs where the destination number starts with any of these values: ',
170 'skip_dcontext' => { 'name' => 'Do not charge for CDRs where the dcontext is set to any of these (comma-separated) values: ',
173 'skip_dstchannel_prefix' => { 'name' => 'Do not charge for CDRs where the dstchannel starts with:',
176 'skip_src_length_more' => { 'name' => 'Do not charge for CDRs where the source is more than this many digits:',
179 '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',
180 'type' => 'checkbox',
183 'accountcode_tollfree_ratenum' => {
184 'name' => 'Optional alternate rate plan when accountcode is toll free: ',
186 'select_table' => 'rate',
187 'select_key' => 'ratenum',
188 'select_label' => 'ratename',
189 'disable_empty' => 0,
193 'skip_dst_length_less' => { 'name' => 'Do not charge for CDRs where the destination is less than this many digits:',
196 'noskip_dst_length_accountcode_tollfree' => { 'name' => 'Do charge for CDRs where dst is less than the specified digits, when accountcode is toll free',
197 'type' => 'checkbox',
200 'skip_lastapp' => { 'name' => 'Do not charge for CDRs where the lastapp matches this value: ',
203 'skip_max_callers' => { 'name' => 'Do not charge for CDRs where max_callers is less than or equal to this value: ',
206 'use_duration' => { 'name' => 'Calculate usage based on the duration field instead of the billsec field',
207 'type' => 'checkbox',
210 '411_rewrite' => { 'name' => 'Rewrite these (comma-separated) destination numbers to 411 for rating purposes (also ignore any carrierid check): ',
213 #false laziness w/cdr_termination.pm
214 'output_format' => { 'name' => 'CDR display format for invoices',
216 'select_options' => \%detail_formats,
217 'default' => 'default', #XXX test
220 'selfservice_format' =>
221 { 'name' => 'CDR display format for selfservice',
223 'select_options' => \%detail_formats,
224 'default' => 'default'
226 'selfservice_inbound_format' =>
227 { 'name' => 'Inbound CDR display format for selfservice',
229 'select_options' => \%detail_formats,
233 'usage_section' => { 'name' => 'Section in which to place usage charges (whether separated or not): ',
236 'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
237 'type' => 'checkbox',
240 'usage_mandate' => { 'name' => 'Always put usage details in separate section',
241 'type' => 'checkbox',
245 'bill_every_call' => { 'name' => 'Generate an invoice immediately for every call (as well any setup fee, upon first payment). Useful for prepaid.',
246 'type' => 'checkbox',
249 'bill_inactive_svcs' => { 'name' => 'Bill for all phone numbers that were active during the billing period',
250 'type' => 'checkbox',
253 '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.',
254 'type' => 'checkbox',
257 #XXX also have option for an external db
258 # 'cdr_location' => { 'name' => 'CDR database location'
259 # 'type' => 'select',
260 # 'select_options' => \%cdr_location,
261 # 'select_callback' => {
263 # 'enable' => [ 'datasrc', 'username', 'password' ],
266 # 'disable' => [ 'datasrc', 'username', 'password' ],
270 # 'datasrc' => { 'name' => 'DBI data source for external CDR table',
273 # 'username' => { 'name' => 'External database username',
276 # 'password' => { 'name' => 'External database password',
283 recur_method cutoff_day ),
284 FS::part_pkg::prorate_Mixin::fieldorder,
287 rating_method ratenum intrastate_ratenum
288 min_charge min_included sec_granularity
292 domestic_prefix international_prefix
296 use_cdrtypenum ignore_cdrtypenum
297 ignore_disposition disposition_in
298 skip_dcontext skip_dst_prefix
299 skip_dstchannel_prefix skip_src_length_more
300 noskip_src_length_accountcode_tollfree
301 accountcode_tollfree_ratenum
303 noskip_dst_length_accountcode_tollfree
309 selfservice_format selfservice_inbound_format
310 usage_mandate summarize_usage usage_section
311 bill_every_call bill_inactive_svcs
312 count_available_phones suspend_bill
320 my $str = $self->SUPER::price_info;
321 $str .= " plus usage" if $str;
327 my($cust_pkg, $sdate, $details, $param ) = @_;
331 $charges += $self->calc_usage(@_);
332 $charges += $self->calc_recur_Common(@_);
340 my($cust_pkg, $sdate, $details, $param ) = @_;
342 $self->calc_usage(@_);
345 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
349 my($cust_pkg, $sdate, $details, $param ) = @_;
351 #my $last_bill = $cust_pkg->last_bill;
352 my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
355 if $self->recur_temporality eq 'preceding'
356 && ( $last_bill eq '' || $last_bill == 0 );
358 my $ratenum = $cust_pkg->part_pkg->option('ratenum');
360 my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
362 my %included_min = (); #region groups w/prefix rating
364 my $included_min = $self->option('min_included', 1) || 0; #single price rating
368 # my $downstream_cdr = '';
370 my $cdr_svc_method = $self->option('cdr_svc_method',1)||'svc_phone.phonenum';
371 my $rating_method = $self->option('rating_method') || 'prefix';
372 my $intl = $self->option('international_prefix') || '011';
373 my $domestic_prefix = $self->option('domestic_prefix');
374 my $disable_tollfree = $self->option('disable_tollfree');
375 my $ignore_unrateable = $self->option('ignore_unrateable', 'Hush!');
376 my $use_duration = $self->option('use_duration');
377 my $region_group = ($rating_method eq 'prefix' && ($self->option('min_included',1) || 0) > 0);
378 my $region_group_included_min = $region_group ? $self->option('min_included') : 0;
380 my $output_format = $self->option('output_format', 'Hush!')
381 || ( $rating_method eq 'upstream_simple'
387 if ( $self->option('411_rewrite') ) {
388 my $dirass = $self->option('411_rewrite');
390 @dirass = split(',', $dirass);
393 my %interval_cache = (); # for timed rates
395 #for check_chargable, so we don't keep looking up options inside the loop
398 my $csv = new Text::CSV_XS;
400 my($svc_table, $svc_field) = split('\.', $cdr_svc_method);
403 if( $self->option('bill_inactive_svcs',1) ) {
404 #XXX in this mode do we need to restrict the set of CDRs by date also?
405 @cust_svc = $cust_pkg->h_cust_svc($$sdate, $last_bill);
408 @cust_svc = $cust_pkg->cust_svc;
410 @cust_svc = grep { $_->part_svc->svcdb eq $svc_table } @cust_svc;
412 foreach my $cust_svc (@cust_svc) {
415 if( $self->option('bill_inactive_svcs',1) ) {
416 $svc_x = $cust_svc->h_svc_x($$sdate, $last_bill);
419 $svc_x = $cust_svc->svc_x;
422 'disable_src' => $self->option('disable_src'),
423 'default_prefix' => $self->option('default_prefix'),
424 'cdrtypenum' => $self->option('use_cdrtypenum'),
427 ); # $last_bill, $$sdate )
428 $options{'by_svcnum'} = 1 if $svc_field eq 'svcnum';
430 my @invoice_details_sort;
433 $svc_x->get_cdrs( %options )
436 warn "rating CDR $cdr\n".
437 join('', map { " $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
441 my( $rate_region, $regionnum );
453 my @call_details = ();
454 if ( $rating_method eq 'prefix' ) {
457 # this will result in those CDRs being marked as done... is that
459 if ( length($cdr->dst) && grep { $cdr->dst eq $_ } @dirass ){
464 my $reason = $self->check_chargable( $cdr,
465 'da_rewrote' => $da_rewrote,
466 'option_cache' => \%opt_cache,
471 warn "not charging for CDR ($reason)\n" if $DEBUG;
473 # this will result in those CDRs being marked as done... is that
479 # look up rate details based on called station id
480 # (or calling station id for toll free calls)
484 if ( $cdr->is_tollfree && ! $disable_tollfree )
486 $to_or_from = 'from';
488 } else { #regular call
493 warn "parsing call $to_or_from $number\n" if $DEBUG;
495 #remove non-phone# stuff and whitespace
498 # $dest =~ s/^(\w+):// and $proto = $1; #sip:
500 # $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
502 #determine the country code
504 if ( $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
505 || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
509 my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
510 #first look for 1 digit country code
511 if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
513 $number = $u1.$u2.$rest;
514 } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
517 } else { #3 digit country code
518 $countrycode = $three;
523 $countrycode = length($domestic_prefix) ? $domestic_prefix : '1';
524 $number =~ s/^$countrycode//;# if length($number) > 10;
527 warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
528 $pretty_destnum = "+$countrycode $number";
529 #asterisks here causes inserting the detail to barf, so:
530 $pretty_destnum =~ s/\*//g;
532 my $eff_ratenum = $cdr->is_tollfree('accountcode')
533 ? $cust_pkg->part_pkg->option('accountcode_tollfree_ratenum')
536 my $intrastate_ratenum = $cust_pkg->part_pkg->option('intrastate_ratenum');
537 if ( $intrastate_ratenum && !$cdr->is_tollfree ) {
538 $ratename = 'Interstate'; #until proven otherwise
539 # this is relatively easy only because:
540 # -assume all numbers are valid NANP numbers NOT in a fully-qualified format
541 # -disregard toll-free
542 # -disregard private or unknown numbers
543 # -there is exactly one record in rate_prefix for a given NPANXX
544 # -default to interstate if we can't find one or both of the prefixes
545 my $dstprefix = $cdr->dst;
546 $dstprefix =~ /^(\d{6})/;
547 $dstprefix = qsearchs('rate_prefix', { 'countrycode' => '1',
550 my $srcprefix = $cdr->src;
551 $srcprefix =~ /^(\d{6})/;
552 $srcprefix = qsearchs('rate_prefix', { 'countrycode' => '1',
555 if ($srcprefix && $dstprefix
556 && $srcprefix->state && $dstprefix->state
557 && $srcprefix->state eq $dstprefix->state) {
558 $eff_ratenum = $intrastate_ratenum;
559 $ratename = 'Intrastate'; # XXX possibly just use the ratename?
563 $eff_ratenum ||= $ratenum;
564 $rate = qsearchs('rate', { 'ratenum' => $eff_ratenum })
565 or die "ratenum $eff_ratenum not found!";
567 my @ltime = localtime($cdr->startdate);
568 $weektime = $ltime[0] +
569 $ltime[1]*60 + #minutes
570 $ltime[2]*3600 + #hours
571 $ltime[6]*86400; #days since sunday
572 # if there's no timed rate_detail for this time/region combination,
573 # dest_detail returns the default. There may still be a timed rate
574 # that applies after the starttime of the call, so be careful...
575 $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
576 'phonenum' => $number,
577 'weektime' => $weektime,
578 'cdrtypenum' => $cdr->cdrtypenum,
581 if ( $rate_detail ) {
583 $rate_region = $rate_detail->dest_region;
584 $regionnum = $rate_region->regionnum;
585 $regionname = $rate_region->regionname;
586 warn " found rate for regionnum $regionnum ".
587 "and rate detail $rate_detail\n"
590 if ( !exists($interval_cache{$regionnum}) ) {
592 sort { $a->stime <=> $b->stime }
593 map { $_->rate_time->intervals }
594 qsearch({ 'table' => 'rate_detail',
595 'hashref' => { 'ratenum' => $rate->ratenum },
596 'extra_sql' => 'AND ratetimenum IS NOT NULL',
599 $interval_cache{$regionnum} = \@intervals;
600 warn " cached ".scalar(@intervals)." interval(s)\n"
604 } elsif ( $ignore_unrateable ) {
608 #code below will throw a warning & skip
612 die "FATAL: no rate_detail found in ".
613 $rate->ratenum. ":". $rate->ratename. " rate plan ".
614 "for +$countrycode $number (CDR acctid ". $cdr->acctid. "); ".
615 "add a rate or set ignore_unrateable flag on the package def\n";
620 } elsif ( $rating_method eq 'upstream_simple' ) {
622 #XXX $charge = sprintf('%.2f', $cdr->upstream_price);
623 $charge = sprintf('%.3f', $cdr->upstream_price);
625 warn "Incrementing \$charges by $charge. Now $charges\n" if $DEBUG;
627 @call_details = ($cdr->downstream_csv( 'format' => $output_format,
631 $classnum = $cdr->calltypenum;
633 } elsif ( $rating_method eq 'single_price' ) {
635 # a little false laziness w/below
636 # $rate_detail = new FS::rate_detail({sec_granularity => ... }) ?
638 my $granularity = length($self->option('sec_granularity'))
639 ? $self->option('sec_granularity')
642 $seconds = $use_duration ? $cdr->duration : $cdr->billsec;
644 $seconds += $granularity - ( $seconds % $granularity )
645 if $seconds # don't granular-ize 0 billsec calls (bills them)
646 && $granularity # 0 is per call
647 && $seconds % $granularity;
648 my $minutes = $granularity ? ($seconds / 60) : 1;
650 my $charge_min = $minutes;
652 $included_min -= $minutes;
653 if ( $included_min > 0 ) {
656 $charge_min = 0 - $included_min;
660 $charge = sprintf('%.4f', ( $self->option('min_charge') * $charge_min )
661 + 0.0000000001 ); #so 1.00005 rounds to 1.0001
663 warn "Incrementing \$charges by $charge. Now $charges\n" if $DEBUG;
666 @call_details = ($cdr->downstream_csv( 'format' => $output_format,
668 'seconds' => ($use_duration ?
671 'granularity' => $granularity,
676 die "don't know how to rate CDRs using method: $rating_method\n";
680 # find the price and add detail to the invoice
683 # if $rate_detail is not found, skip this CDR... i.e.
684 # don't add it to invoice, don't set its status to done,
685 # don't call downstream_csv or something on it...
686 # but DO emit a warning...
687 #if ( ! $rate_detail && ! scalar(@call_details) ) {}
688 if ( ! $rate_detail && $charge eq '' ) {
690 if ( $ignore_unrateable == 2 ) {
691 # mark the CDR as unrateable
692 my $error = $cdr->set_status_and_rated_price(
697 die $error if $error;
699 elsif ( $ignore_unrateable == 1 ) {
701 warn "no rate_detail found for CDR.acctid: ". $cdr->acctid.
703 } #if $ignore_unrateable
705 } else { # there *is* a rate_detail (or call_details), proceed...
706 # About this section:
707 # We don't round _anything_ (except granularizing)
708 # until the final $charge = sprintf("%.2f"...).
710 unless ( @call_details || ( $charge ne '' && $charge == 0 ) ) {
712 my $seconds_left = $use_duration ? $cdr->duration : $cdr->billsec;
713 # charge for the first (conn_sec) seconds
714 $seconds = min($seconds_left, $rate_detail->conn_sec);
715 $seconds_left -= $seconds;
716 $weektime += $seconds;
717 $charge = $rate_detail->conn_charge;
720 while($seconds_left) {
721 my $ratetimenum = $rate_detail->ratetimenum; # may be empty
723 # find the end of the current rate interval
724 if(@{ $interval_cache{$regionnum} } == 0) {
725 # There are no timed rates in this group, so just stay
726 # in the default rate_detail for the entire duration.
727 # Set an "end" of 1 past the end of the current call.
728 $etime = $weektime + $seconds_left + 1;
730 elsif($ratetimenum) {
731 # This is a timed rate, so go to the etime of this interval.
732 # If it's followed by another timed rate, the stime of that
733 # interval should match the etime of this one.
734 my $interval = $rate_detail->rate_time->contains($weektime);
735 $etime = $interval->etime;
738 # This is a default rate, so use the stime of the next
739 # interval in the sequence.
740 my $next_int = first { $_->stime > $weektime }
741 @{ $interval_cache{$regionnum} };
743 $etime = $next_int->stime;
746 # weektime is near the end of the week, so decrement
747 # it by a full week and use the stime of the first
749 $weektime -= (3600*24*7);
750 $etime = $interval_cache{$regionnum}->[0]->stime;
754 my $charge_sec = min($seconds_left, $etime - $weektime);
756 $seconds_left -= $charge_sec;
758 $included_min{$regionnum}{$ratetimenum} = $rate_detail->min_included
759 unless exists $included_min{$regionnum}{$ratetimenum};
761 my $granularity = $rate_detail->sec_granularity;
764 if ( $granularity ) { # charge per minute
765 # Round up to the nearest $granularity
766 if ( $charge_sec and $charge_sec % $granularity ) {
767 $charge_sec += $granularity - ($charge_sec % $granularity);
769 $minutes = $charge_sec / 60; #don't round this
776 $seconds += $charge_sec;
778 $region_group_included_min -= $minutes
779 if $region_group && $rate_detail->region_group;
781 $included_min{$regionnum}{$ratetimenum} -= $minutes;
782 if ( ($region_group_included_min <= 0 || !$rate_detail->region_group)
783 && $included_min{$regionnum}{$ratetimenum} <= 0 ) {
784 my $charge_min = 0 - $included_min{$regionnum}{$ratetimenum}; #XXX should preserve
786 $included_min{$regionnum}{$ratetimenum} = 0;
787 $charge += ($rate_detail->min_charge * $charge_min); #still not rounded
789 elsif( $region_group_included_min > 0 && $region_group
790 && $rate_detail->region_group ) {
791 $included_min{$regionnum}{$ratetimenum} = 0
794 # choose next rate_detail
795 $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
796 'phonenum' => $number,
797 'weektime' => $etime,
798 'cdrtypenum' => $cdr->cdrtypenum })
800 # we have now moved forward to $etime
803 } #while $seconds_left
804 # this is why we need regionnum/rate_region....
805 warn " (rate region $rate_region)\n" if $DEBUG;
807 $classnum = $rate_detail->classnum;
808 $charge = sprintf('%.2f', $charge + 0.000001); # NOW round it.
809 warn "Incrementing \$charges by $charge. Now $charges\n" if $DEBUG;
812 if ( !$self->sum_usage ) {
814 $cdr->downstream_csv( 'format' => $output_format,
815 'granularity' => $rate_detail->sec_granularity,
816 'seconds' => ($use_duration ?
820 'pretty_dst' => $pretty_destnum,
821 'dst_regionname' => $regionname,
825 } #if(there is a rate_detail)
827 #if ( $charge > 0 ) {
828 # generate a detail record for every call; filter out $charge = 0
831 my $phonenum = $svc_x->phonenum;
833 if ( scalar(@call_details) == 1 ) {
836 detail => $call_details[0],
838 classnum => $classnum,
839 phonenum => $phonenum,
840 accountcode => $cdr->accountcode,
841 startdate => $cdr->startdate,
842 duration => $seconds,
843 regionname => $regionname,
845 } else { #only used for $rating_method eq 'upstream' now
846 # and for sum_ formats
847 $csv->combine(@call_details);
850 detail => $csv->string,
852 classnum => $classnum,
853 phonenum => $phonenum,
854 accountcode => $cdr->accountcode,
855 startdate => $cdr->startdate,
856 duration => $seconds,
857 regionname => $regionname,
860 $call_details->{'ratename'} = $ratename;
862 push @invoice_details_sort, [ $call_details, $cdr->calldate_unix ];
865 # if the customer flag is on, call "downstream_csv" or something
866 # like it to export the call downstream!
867 # XXX price plan option to pick format, or something...
868 #$downstream_cdr .= $cdr->downstream_csv( 'format' => 'XXX format' )
871 my $error = $cdr->set_status_and_rated_price( 'done',
875 die $error if $error;
881 if ( !$self->sum_usage ) {
883 my @sorted_invoice_details =
884 sort { @{$a}[1] <=> @{$b}[1] } @invoice_details_sort;
885 foreach my $sorted_call_detail ( @sorted_invoice_details ) {
886 my $d = $sorted_call_detail->[0];
887 push @$details, $d if $d->{amount} > 0;
890 else { #$self->sum_usage
891 push @$details, $self->sum_detail($svc_x, \@invoice_details_sort);
895 unshift @$details, { format => 'C',
897 $cust_pkg->mt(FS::cdr::invoice_header($output_format))
899 if @$details && $rating_method ne 'upstream';
904 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
905 sub check_chargable {
906 my( $self, $cdr, %flags ) = @_;
908 #should have some better way of checking these options from a hash
920 skip_dstchannel_prefix
921 skip_src_length_more noskip_src_length_accountcode_tollfree
922 skip_dst_length_less noskip_dst_length_accountcode_tollfree
926 foreach my $opt (grep !exists($flags{option_cache}->{$_}), @opt ) {
927 $flags{option_cache}->{$opt} = $self->option($opt, 1);
929 my %opt = %{ $flags{option_cache} };
931 return 'amaflags != 2'
932 if $opt{'use_amaflags'} && $cdr->amaflags != 2;
934 return "disposition NOT IN ( $opt{'disposition_in'} )"
935 if $opt{'disposition_in'} =~ /\S/
936 && !grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $opt{'disposition_in'});
938 return "disposition IN ( $opt{'ignore_disposition'} )"
939 if $opt{'ignore_disposition'} =~ /\S/
940 && grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $opt{'ignore_disposition'});
942 foreach(split(/\s*,\s*/, $opt{'skip_dst_prefix'})) {
943 return "dst starts with '$_'"
944 if length($_) && substr($cdr->dst,0,length($_)) eq $_;
947 return "carrierid NOT IN ( $opt{'use_carrierid'} )"
948 if $opt{'use_carrierid'} =~ /\S/
949 && ! $flags{'da_rewrote'} #why?
950 && !grep { $cdr->carrierid eq $_ } split(/\s*,\s*/, $opt{'use_carrierid'}); #eq otherwise 0 matches ''
952 # unlike everything else, use_cdrtypenum is applied in FS::svc_x::get_cdrs.
953 return "cdrtypenum != $opt{'use_cdrtypenum'}"
954 if length($opt{'use_cdrtypenum'})
955 && $cdr->cdrtypenum ne $opt{'use_cdrtypenum'}; #ne otherwise 0 matches ''
957 return "cdrtypenum == $opt{'ignore_cdrtypenum'}"
958 if length($opt{'ignore_cdrtypenum'})
959 && $cdr->cdrtypenum eq $opt{'ignore_cdrtypenum'}; #eq otherwise 0 matches ''
961 return "dcontext IN ( $opt{'skip_dcontext'} )"
962 if $opt{'skip_dcontext'} =~ /\S/
963 && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $opt{'skip_dcontext'});
965 my $len_prefix = length($opt{'skip_dstchannel_prefix'});
966 return "dstchannel starts with $opt{'skip_dstchannel_prefix'}"
968 && substr($cdr->dstchannel,0,$len_prefix) eq $opt{'skip_dstchannel_prefix'};
970 my $dst_length = $opt{'skip_dst_length_less'};
971 return "destination less than $dst_length digits"
972 if $dst_length && length($cdr->dst) < $dst_length
973 && ! ( $opt{'noskip_dst_length_accountcode_tollfree'}
974 && $cdr->is_tollfree('accountcode')
977 return "lastapp is $opt{'skip_lastapp'}"
978 if length($opt{'skip_lastapp'}) && $cdr->lastapp eq $opt{'skip_lastapp'};
980 my $src_length = $opt{'skip_src_length_more'};
983 if ( $opt{'noskip_src_length_accountcode_tollfree'} ) {
985 if ( $cdr->is_tollfree('accountcode') ) {
986 return "source less than or equal to $src_length digits"
987 if length($cdr->src) <= $src_length;
989 return "source more than $src_length digits"
990 if length($cdr->src) > $src_length;
994 return "source more than $src_length digits"
995 if length($cdr->src) > $src_length;
1000 return "max_callers <= $opt{skip_max_callers}"
1001 if length($opt{'skip_max_callers'})
1002 and length($cdr->max_callers)
1003 and $cdr->max_callers <= $opt{'skip_max_callers'};
1005 #all right then, rate it
1013 # This equates svc_phone records; perhaps svc_phone should have a field
1014 # to indicate it represents a line
1016 my($self, $cust_pkg ) = @_;
1018 if ( $self->option('count_available_phones', 1)) {
1019 map { $count += ( $_->quantity || 0 ) }
1020 grep { $_->part_svc->svcdb eq 'svc_phone' }
1021 $cust_pkg->part_pkg->pkg_svc;
1024 scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
1029 # tells whether cust_bill_pkg_detail should return a single line for
1033 $self->option('output_format') =~ /^sum_/;
1039 my $invoice_details = shift || [];
1040 return () if !@$invoice_details;
1041 my $details_by_rate = {};
1042 # combine the entire set of CDRs
1043 foreach ( @$invoice_details ) {
1045 my $sum = $details_by_rate->{ $d->{ratename} } ||= {
1048 classnum => '', #XXX
1050 phonenum => $svc_x->phonenum,
1051 accountcode => '', #XXX
1052 startdate => '', #XXX
1056 $sum->{amount} += $d->{amount};
1057 $sum->{duration} += $d->{duration};
1061 foreach my $ratename ( sort keys(%$details_by_rate) ) {
1062 my $sum = $details_by_rate->{$ratename};
1063 next if $sum->{count} == 0;
1064 my $total_cdr = FS::cdr->new({
1065 'billsec' => $sum->{duration},
1066 'src' => $sum->{phonenum},
1068 $sum->{detail} = $total_cdr->downstream_csv(
1069 format => $self->option('output_format'),
1070 seconds => $sum->{duration},
1071 charge => sprintf('%.2f',$sum->{amount}),
1072 ratename => $ratename,
1073 phonenum => $sum->{phonenum},
1074 count => $sum->{count},
1076 push @details, $sum;
1081 # and whether cust_bill should show a detail line for the service label
1082 # (separate from usage details)
1083 sub hide_svc_detail {
1085 $self->option('output_format') =~ /^sum_/;