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',
31 'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
32 'shortname' => 'VoIP/telco CDR rating (standard)',
34 'setup_fee' => { 'name' => 'Setup fee for this package',
37 'recur_fee' => { 'name' => 'Base recurring fee for this package',
40 'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
41 ' of service at cancellation',
44 'ratenum' => { 'name' => 'Rate plan',
46 'select_table' => 'rate',
47 'select_key' => 'ratenum',
48 'select_label' => 'ratename',
50 'rating_method' => { 'name' => 'Region rating method',
52 'options' => \%rating_method,
55 'default_prefix' => { 'name' => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
59 'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
63 'domestic_prefix' => { 'name' => 'Destination prefix for domestic CDR records',
67 # 'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
68 # 'type' => 'checkbox',
71 'international_prefix' => { 'name' => 'Destination prefix for international CDR records',
75 'use_amaflags' => { 'name' => 'Do not charge for CDRs where the amaflags field is not set to "2" ("BILL"/"BILLING").',
79 'use_disposition' => { 'name' => 'Do not charge for CDRs where the disposition flag is not set to "ANSWERED".',
83 'output_format' => { 'name' => 'Simple output format',
85 'select_options' => { FS::cdr::invoice_formats() },
88 'separate_usage' => { 'name' => 'Separate usage charges from recurring charges',
92 'usage_section' => { 'name' => 'Section in which to place separate usage charges',
95 'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
99 #XXX also have option for an external db
100 # 'cdr_location' => { 'name' => 'CDR database location'
101 # 'type' => 'select',
102 # 'select_options' => \%cdr_location,
103 # 'select_callback' => {
105 # 'enable' => [ 'datasrc', 'username', 'password' ],
108 # 'disable' => [ 'datasrc', 'username', 'password' ],
112 # 'datasrc' => { 'name' => 'DBI data source for external CDR table',
115 # 'username' => { 'name' => 'External database username',
118 # 'password' => { 'name' => 'External database password',
124 setup_fee recur_fee unused_credit
125 rating_method ratenum
128 domestic_prefix international_prefix
129 use_amaflags use_disposition output_format
130 separate_usage summarize_usage usage_section
137 my($self, $cust_pkg ) = @_;
138 $self->option('setup_fee');
144 $charges = $self->calc_usage(@_)
145 unless $self->option('separate_usage', 'Hush!');
146 $self->option('recur_fee') + $charges;
149 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
151 my($self, $cust_pkg, $sdate, $details, $param ) = @_;
153 my $last_bill = $cust_pkg->last_bill;
155 my $ratenum = $cust_pkg->part_pkg->option('ratenum');
157 my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
159 my %included_min = ();
163 my $downstream_cdr = '';
165 my $output_format = $self->option('output_format', 'Hush!')
168 eval "use Text::CSV_XS;";
170 my $csv = new Text::CSV_XS;
172 foreach my $cust_svc (
173 grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
177 $cust_svc->get_cdrs_for_update( 'disable_src' => $self->option('disable_src'),
178 'default_prefix' => $self->option('default_prefix'),
179 ) # $last_bill, $$sdate )
182 warn "rating CDR $cdr\n".
183 join('', map { " $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
187 my( $rate_region, $regionnum );
191 my @call_details = ();
192 if ( $self->option('rating_method') eq 'prefix'
193 || ! $self->option('rating_method')
197 if ( $self->option('use_amaflags') && $cdr->amaflags != 2 ) {
199 warn "not charging for CDR (amaflags != 2)\n" if $DEBUG;
202 } elsif ( $self->option('use_disposition')
203 && $cdr->disposition ne 'ANSWERED' ) {
205 warn "not charging for CDR (disposition != ANSWERED)\n" if $DEBUG;
211 # look up rate details based on called station id
212 # (or calling station id for toll free calls)
215 my( $to_or_from, $number );
216 if ( $cdr->dst =~ /^(\+?1)?8([02-8])\1/ ) { #tollfree call
217 $to_or_from = 'from';
219 } else { #regular call
224 #remove non-phone# stuff and whitespace
227 # $dest =~ s/^(\w+):// and $proto = $1; #sip:
229 # $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
231 my $intl = $self->option('international_prefix') || '011';
233 #determine the country code
235 if ( $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
236 || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
240 my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
241 #first look for 1 digit country code
242 if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
244 $number = $u1.$u2.$rest;
245 } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
248 } else { #3 digit country code
249 $countrycode = $three;
254 $countrycode = $self->option('domestic_prefix') || '1';
255 $number =~ s/^$countrycode//;# if length($number) > 10;
258 warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
259 $pretty_destnum = "+$countrycode $number";
261 #find a rate prefix, first look at most specific (4 digits) then 3, etc.,
262 # finally trying the country code only
263 my $rate_prefix = '';
264 for my $len ( reverse(1..6) ) {
265 $rate_prefix = qsearchs('rate_prefix', {
266 'countrycode' => $countrycode,
267 #'npa' => { op=> 'LIKE', value=> substr($number, 0, $len) }
268 'npa' => substr($number, 0, $len),
271 $rate_prefix ||= qsearchs('rate_prefix', {
272 'countrycode' => $countrycode,
277 die "Can't find rate for call $to_or_from +$countrycode $number\n"
280 $regionnum = $rate_prefix->regionnum;
281 $rate_detail = qsearchs('rate_detail', {
282 'ratenum' => $ratenum,
283 'dest_regionnum' => $regionnum,
286 $rate_region = $rate_prefix->rate_region;
288 warn " found rate for regionnum $regionnum ".
289 "and rate detail $rate_detail\n"
294 } elsif ( $self->option('rating_method') eq 'upstream' ) {
296 if ( $cdr->cdrtypenum == 1 ) { #rate based on upstream rateid
298 $rate_detail = $cdr->cdr_upstream_rate->rate_detail;
300 $regionnum = $rate_detail->dest_regionnum;
301 $rate_region = $rate_detail->dest_region;
303 $pretty_destnum = $cdr->dst;
305 warn " found rate for regionnum $regionnum and ".
306 "rate detail $rate_detail\n"
309 } else { #pass upstream price through
311 $charge = sprintf('%.2f', $cdr->upstream_price);
315 #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
316 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
320 $cdr->description, #$rate_region->regionname,
325 } elsif ( $self->option('rating_method') eq 'upstream_simple' ) {
327 #XXX $charge = sprintf('%.2f', $cdr->upstream_price);
328 $charge = sprintf('%.3f', $cdr->upstream_price);
331 @call_details = ($cdr->downstream_csv( 'format' => $output_format ));
334 die "don't know how to rate CDRs using method: ".
335 $self->option('rating_method'). "\n";
339 # find the price and add detail to the invoice
342 # if $rate_detail is not found, skip this CDR... i.e.
343 # don't add it to invoice, don't set its status to NULL,
344 # don't call downstream_csv or something on it...
345 # but DO emit a warning...
346 #if ( ! $rate_detail && ! scalar(@call_details) ) {
347 if ( ! $rate_detail && $charge eq '' ) {
349 warn "no rate_detail found for CDR.acctid: ". $cdr->acctid.
352 } else { # there *is* a rate_detail (or call_details), proceed...
354 unless ( @call_details || ( $charge ne '' && $charge == 0 ) ) {
356 $included_min{$regionnum} = $rate_detail->min_included
357 unless exists $included_min{$regionnum};
359 my $granularity = $rate_detail->sec_granularity;
360 my $seconds = $cdr->billsec; # length($cdr->billsec) ? $cdr->billsec : $cdr->duration;
361 $seconds += $granularity - ( $seconds % $granularity )
362 if $seconds # don't granular-ize 0 billsec calls (bills them)
363 && $granularity; # 0 is per call
364 my $minutes = sprintf("%.1f", $seconds / 60);
365 $minutes =~ s/\.0$// if $granularity == 60;
367 # per call rather than per minute
368 $minutes = 1 unless $granularity;
370 $included_min{$regionnum} -= $minutes;
372 if ( $included_min{$regionnum} < 0 ) {
373 my $charge_min = 0 - $included_min{$regionnum};
374 $included_min{$regionnum} = 0;
375 $charge = sprintf('%.2f', $rate_detail->min_charge * $charge_min );
379 # this is why we need regionnum/rate_region....
380 warn " (rate region $rate_region)\n" if $DEBUG;
383 #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
384 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
385 $granularity ? $minutes.'m' : $minutes.' call',
388 $rate_region->regionname,
391 $classnum = $rate_detail->classnum;
396 #just use FS::cust_bill_pkg_detail objects?
398 if ( $self->option('rating_method') eq 'upstream_simple' ) {
399 $call_details = [ 'C', $call_details[0], $charge, $classnum ];
401 $csv->combine(@call_details);
402 $call_details = [ 'C', $csv->string, $charge, $classnum ];
404 warn " adding details on charge to invoice: [ ".
405 join(', ', @{$call_details} ). " ]"
406 if ( $DEBUG && ref($call_details) );
407 push @$details, $call_details; #\@call_details,
410 # if the customer flag is on, call "downstream_csv" or something
411 # like it to export the call downstream!
412 # XXX price plan option to pick format, or something...
413 $downstream_cdr .= $cdr->downstream_csv( 'format' => 'convergent' )
416 my $error = $cdr->set_status_and_rated_price('done', $charge);
417 die $error if $error;
423 unshift @$details, [ 'C', FS::cdr::invoice_header( $output_format) ]
424 if (@$details && $self->option('rating_method') eq 'upstream_simple' );
428 if ( $spool_cdr && length($downstream_cdr) ) {
430 use FS::UID qw(datasrc);
431 my $dir = '/usr/local/etc/freeside/export.'. datasrc. '/cdr';
432 mkdir $dir, 0700 unless -d $dir;
433 $dir .= '/'. $cust_pkg->custnum.
434 mkdir $dir, 0700 unless -d $dir;
435 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
437 push @{ $param->{'precommit_hooks'} },
439 #lock the downstream spool file and append the records
440 use Fcntl qw(:flock);
442 my $spool = new IO::File ">>$filename"
443 or die "can't open $filename: $!\n";
444 flock( $spool, LOCK_EX)
445 or die "can't lock $filename: $!\n";
447 or die "can't seek to end of $filename: $!\n";
448 print $spool $downstream_cdr;
449 flock( $spool, LOCK_UN );
453 } #if ( $spool_cdr && length($downstream_cdr) )
464 my($self, $cust_pkg) = @_;
465 $self->option('recur_fee');
468 # This equates svc_phone records; perhaps svc_phone should have a field
469 # to indicate it represents a line
471 my($self, $cust_pkg ) = @_;
472 scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
475 sub append_cust_bill_pkgs {
477 my($cust_pkg, $sdate, $details, $param ) = @_;
479 unless $self->option('separate_usage', 'Hush!');
482 my $charges = $self->calc_usage($cust_pkg, $sdate, \@details, $param);
485 unless $charges; # unless @details?
487 my @cust_bill_pkg = ();
489 my $want_summary = $self->option('summarize_usage', 'Hush!') &&
490 $self->option('usage_section', 'Hush!');
492 push @cust_bill_pkg, new FS::cust_bill_pkg {
493 'pkgnum' => $cust_pkg->pkgnum,
496 'recur' => sprintf( "%.2f", $charges), # hmmm
498 'quantity' => $cust_pkg->quantity,
500 'edate' => $cust_pkg->bill, # already fiddled
501 'itemdesc' => 'Usage charges', # configurable?
506 push @cust_bill_pkg, new FS::cust_bill_pkg {
507 'pkgnum' => $cust_pkg->pkgnum,
510 'recur' => sprintf( "%.2f", $charges), # hmmm
512 'quantity' => $cust_pkg->quantity,
514 'edate' => $cust_pkg->bill, # already fiddled
515 'itemdesc' => 'Usage charges', # configurable?
516 'section' => $self->option('usage_section', 'Hush!'),
517 'details' => \@details,
518 'post_total' => ( $want_summary ? 'Y' : '' ),
522 return [ @cust_bill_pkg ];