4 use vars qw( @ISA @EXPORT_OK $DEBUG $me
5 $conf $cdr_prerate %cdr_prerate_cdrtypenums
8 use List::Util qw(first min);
13 use List::Util qw( first min );
14 use FS::UID qw( dbh );
16 use FS::Record qw( qsearch qsearchs );
21 use FS::cdr_termination;
26 @ISA = qw(FS::Record);
27 @EXPORT_OK = qw( _cdr_date_parser_maker _cdr_min_parser_maker );
32 #ask FS::UID to run this stuff for us later
33 FS::UID->install_callback( sub {
36 my @cdr_prerate_cdrtypenums;
37 $cdr_prerate = $conf->exists('cdr-prerate');
38 @cdr_prerate_cdrtypenums = $conf->config('cdr-prerate-cdrtypenums')
40 %cdr_prerate_cdrtypenums = map { $_=>1 } @cdr_prerate_cdrtypenums;
45 FS::cdr - Object methods for cdr records
51 $record = new FS::cdr \%hash;
52 $record = new FS::cdr { 'column' => 'value' };
54 $error = $record->insert;
56 $error = $new_record->replace($old_record);
58 $error = $record->delete;
60 $error = $record->check;
64 An FS::cdr object represents an Call Data Record, typically from a telephony
65 system or provider of some sort. FS::cdr inherits from FS::Record. The
66 following fields are currently supported:
70 =item acctid - primary key
72 =item calldate - Call timestamp (SQL timestamp)
74 =item clid - Caller*ID with text
76 =item src - Caller*ID number / Source number
78 =item dst - Destination extension
80 =item dcontext - Destination context
82 =item channel - Channel used
84 =item dstchannel - Destination channel if appropriate
86 =item lastapp - Last application if appropriate
88 =item lastdata - Last application data
90 =item src_ip_addr - Source IP address (dotted quad, zero-filled)
92 =item dst_ip_addr - Destination IP address (same)
94 =item startdate - Start of call (UNIX-style integer timestamp)
96 =item answerdate - Answer time of call (UNIX-style integer timestamp)
98 =item enddate - End time of call (UNIX-style integer timestamp)
100 =item duration - Total time in system, in seconds
102 =item billsec - Total time call is up, in seconds
104 =item disposition - What happened to the call: ANSWERED, NO ANSWER, BUSY
106 =item amaflags - What flags to use: BILL, IGNORE etc, specified on a per channel basis like accountcode.
110 #ignore the "omit" and "documentation" AMAs??
111 #AMA = Automated Message Accounting.
112 #default: Sets the system default.
113 #omit: Do not record calls.
114 #billing: Mark the entry for billing
115 #documentation: Mark the entry for documentation.
117 =item accountcode - CDR account number to use: account
119 =item uniqueid - Unique channel identifier (Unitel/RSLCOM Event ID)
121 =item userfield - CDR user-defined field
123 =item cdr_type - CDR type - see L<FS::cdr_type> (Usage = 1, S&E = 7, OC&C = 8)
125 =item charged_party - Service number to be billed
127 =item upstream_currency - Wholesale currency from upstream
129 =item upstream_price - Wholesale price from upstream
131 =item upstream_rateplanid - Upstream rate plan ID
133 =item rated_price - Rated (or re-rated) price
135 =item distance - km (need units field?)
137 =item islocal - Local - 1, Non Local = 0
139 =item calltypenum - Type of call - see L<FS::cdr_calltype>
141 =item description - Description (cdr_type 7&8 only) (used for cust_bill_pkg.itemdesc)
143 =item quantity - Number of items (cdr_type 7&8 only)
145 =item carrierid - Upstream Carrier ID (see L<FS::cdr_carrier>)
149 #Telstra =1, Optus = 2, RSL COM = 3
151 =item upstream_rateid - Upstream Rate ID
153 =item svcnum - Link to customer service (see L<FS::cust_svc>)
155 =item freesidestatus - NULL, processing-tiered, rated, done, skipped, no-charge, failed
157 =item freesiderewritestatus - NULL, done, skipped
169 Creates a new CDR. To add the CDR to the database, see L<"insert">.
171 Note that this stores the hash reference, not a distinct copy of the hash it
172 points to. You can ask the object for a copy with the I<hash> method.
176 # the new method can be inherited from FS::Record, if a table method is defined
183 #XXX fill in some (more) nice names
185 'calldate' => 'Call date',
186 'clid' => 'Caller ID',
188 'dst' => 'Destination',
189 'dcontext' => 'Dest. context',
190 'channel' => 'Channel',
191 'dstchannel' => 'Destination channel',
194 'src_ip_addr' => 'Source IP',
195 'dst_ip_addr' => 'Dest. IP',
196 'startdate' => 'Start date',
197 'answerdate' => 'Answer date',
198 'enddate' => 'End date',
199 'duration' => 'Duration',
200 'billsec' => 'Billable seconds',
201 'disposition' => 'Disposition',
202 'amaflags' => 'AMA flags',
203 'accountcode' => 'Account code',
205 'userfield' => 'User field',
207 'charged_party' => 'Charged party',
208 #'upstream_currency' => '',
209 'upstream_price' => 'Upstream price',
210 #'upstream_rateplanid' => '',
211 #'ratedetailnum' => '',
212 'rated_price' => 'Rated price',
215 #'calltypenum' => '',
216 #'description' => '',
218 'carrierid' => 'Carrier ID',
219 #'upstream_rateid' => '',
220 'svcnum' => 'Freeside service',
221 'freesidestatus' => 'Freeside status',
222 'freesiderewritestatus' => 'Freeside rewrite status',
223 'cdrbatch' => 'Legacy batch',
224 'cdrbatchnum' => 'Batch',
233 Adds this record to the database. If there is an error, returns the error,
234 otherwise returns false.
238 # the insert method can be inherited from FS::Record
242 Delete this record from the database.
246 # the delete method can be inherited from FS::Record
248 =item replace OLD_RECORD
250 Replaces the OLD_RECORD with this one in the database. If there is an error,
251 returns the error, otherwise returns false.
255 # the replace method can be inherited from FS::Record
259 Checks all fields to make sure this is a valid CDR. If there is
260 an error, returns the error, otherwise returns false. Called by the insert
263 Note: Unlike most types of records, we don't want to "reject" a CDR and we want
264 to process them as quickly as possible, so we allow the database to check most
272 # we don't want to "reject" a CDR like other sorts of input...
274 # $self->ut_numbern('acctid')
275 ## || $self->ut_('calldate')
276 # || $self->ut_text('clid')
277 # || $self->ut_text('src')
278 # || $self->ut_text('dst')
279 # || $self->ut_text('dcontext')
280 # || $self->ut_text('channel')
281 # || $self->ut_text('dstchannel')
282 # || $self->ut_text('lastapp')
283 # || $self->ut_text('lastdata')
284 # || $self->ut_numbern('startdate')
285 # || $self->ut_numbern('answerdate')
286 # || $self->ut_numbern('enddate')
287 # || $self->ut_number('duration')
288 # || $self->ut_number('billsec')
289 # || $self->ut_text('disposition')
290 # || $self->ut_number('amaflags')
291 # || $self->ut_text('accountcode')
292 # || $self->ut_text('uniqueid')
293 # || $self->ut_text('userfield')
294 # || $self->ut_numbern('cdrtypenum')
295 # || $self->ut_textn('charged_party')
296 ## || $self->ut_n('upstream_currency')
297 ## || $self->ut_n('upstream_price')
298 # || $self->ut_numbern('upstream_rateplanid')
299 ## || $self->ut_n('distance')
300 # || $self->ut_numbern('islocal')
301 # || $self->ut_numbern('calltypenum')
302 # || $self->ut_textn('description')
303 # || $self->ut_numbern('quantity')
304 # || $self->ut_numbern('carrierid')
305 # || $self->ut_numbern('upstream_rateid')
306 # || $self->ut_numbern('svcnum')
307 # || $self->ut_textn('freesidestatus')
308 # || $self->ut_textn('freesiderewritestatus')
310 # return $error if $error;
312 for my $f ( grep { $self->$_ =~ /\D/ } qw(startdate answerdate enddate)){
313 $self->$f( str2time($self->$f) );
316 $self->calldate( $self->startdate_sql )
317 if !$self->calldate && $self->startdate;
319 #was just for $format eq 'taqua' but can't see the harm... add something to
320 #disable if it becomes a problem
321 if ( $self->duration eq '' && $self->enddate && $self->startdate ) {
322 $self->duration( $self->enddate - $self->startdate );
324 if ( $self->billsec eq '' && $self->enddate && $self->answerdate ) {
325 $self->billsec( $self->enddate - $self->answerdate );
328 $self->set_charged_party;
330 #check the foreign keys even?
331 #do we want to outright *reject* the CDR?
333 $self->ut_numbern('acctid')
335 #add a config option to turn these back on if someone needs 'em
337 # #Usage = 1, S&E = 7, OC&C = 8
338 # || $self->ut_foreign_keyn('cdrtypenum', 'cdr_type', 'cdrtypenum' )
340 # #the big list in appendix 2
341 # || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
343 # # Telstra =1, Optus = 2, RSL COM = 3
344 # || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
346 return $error if $error;
351 =item is_tollfree [ COLUMN ]
353 Returns true when the cdr represents a toll free number and false otherwise.
355 By default, inspects the dst field, but an optional column name can be passed
356 to inspect other field.
362 my $field = scalar(@_) ? shift : 'dst';
363 ( $self->$field() =~ /^(\+?1)?8(8|([02-7])\3)/ ) ? 1 : 0;
366 =item set_charged_party
368 If the charged_party field is already set, does nothing. Otherwise:
370 If the cdr-charged_party-accountcode config option is enabled, sets the
371 charged_party to the accountcode.
373 Otherwise sets the charged_party normally: to the src field in most cases,
374 or to the dst field if it is a toll free number.
378 sub set_charged_party {
381 my $conf = new FS::Conf;
383 unless ( $self->charged_party ) {
385 if ( $conf->exists('cdr-charged_party-accountcode') && $self->accountcode ){
387 my $charged_party = $self->accountcode;
388 $charged_party =~ s/^0+//
389 if $conf->exists('cdr-charged_party-accountcode-trim_leading_0s');
390 $self->charged_party( $charged_party );
392 } elsif ( $conf->exists('cdr-charged_party-field') ) {
394 my $field = $conf->config('cdr-charged_party-field');
395 $self->charged_party( $self->$field() );
399 if ( $self->is_tollfree ) {
400 $self->charged_party($self->dst);
402 $self->charged_party($self->src);
409 # my $prefix = $conf->config('cdr-charged_party-truncate_prefix');
410 # my $prefix_len = length($prefix);
411 # my $trunc_len = $conf->config('cdr-charged_party-truncate_length');
413 # $self->charged_party( substr($self->charged_party, 0, $trunc_len) )
414 # if $prefix_len && $trunc_len
415 # && substr($self->charged_party, 0, $prefix_len) eq $prefix;
419 =item set_status STATUS
421 Sets the status to the provided string. If there is an error, returns the
422 error, otherwise returns false.
427 my($self, $status) = @_;
428 $self->freesidestatus($status);
432 =item set_status_and_rated_price STATUS RATED_PRICE [ SVCNUM [ OPTION => VALUE ... ] ]
434 Sets the status and rated price.
436 Available options are: inbound, rated_pretty_dst, rated_regionname,
437 rated_seconds, rated_minutes, rated_granularity, rated_ratedetailnum,
438 rated_classnum, rated_ratename.
440 If there is an error, returns the error, otherwise returns false.
444 sub set_status_and_rated_price {
445 my($self, $status, $rated_price, $svcnum, %opt) = @_;
447 if ($opt{'inbound'}) {
449 my $term = $self->cdr_termination( 1 ); #1: inbound
452 warn "replacing existing cdr status (".$self->acctid.")\n" if $term;
453 $error = $term->delete;
454 return $error if $error;
456 $term = FS::cdr_termination->new({
457 acctid => $self->acctid,
459 rated_price => $rated_price,
462 $term->rated_seconds($opt{rated_seconds}) if exists($opt{rated_seconds});
463 $term->rated_minutes($opt{rated_minutes}) if exists($opt{rated_minutes});
464 $term->svcnum($svcnum) if $svcnum;
465 return $term->insert;
469 $self->freesidestatus($status);
470 $self->rated_price($rated_price);
472 foreach grep exists($opt{$_}), map "rated_$_",
473 qw( pretty_dst regionname seconds minutes granularity
474 ratedetailnum classnum ratename );
475 $self->svcnum($svcnum) if $svcnum;
476 return $self->replace();
481 =item rate [ OPTION => VALUE ... ]
483 Rates this CDR according and sets the status to 'rated'.
485 Available options are: part_pkg, svcnum, single_price_included_minutes, region_group, region_group_included_minutes.
487 part_pkg is required.
489 If svcnum is specified, will also associate this CDR with the specified svcnum.
491 single_price_included_minutes is requried for single_price price plans
492 (otherwise unused/ignored). It should be set to a scalar reference of the
493 number of included minutes and will be decremented by the rated minutes of this
496 region_group_included_minutes is required for prefix price plans which have
497 included minutes (otherwise unused/ignored). It should be set to a scalar
498 reference of the number of included minutes and will be decremented by the
499 rated minutes of this CDR.
501 region_group_included_minutes_hashref is required for prefix price plans which
502 have included minues (otehrwise unused/ignored). It should be set to an empty
503 hashref at the start of a month's rating and then preserved across CDRs.
508 my( $self, %opt ) = @_;
509 my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
512 warn "rating CDR $self\n".
513 join('', map { " $_ => ". $self->{$_}. "\n" } keys %$self );
516 my $rating_method = $part_pkg->option_cacheable('rating_method') || 'prefix';
517 my $method = "rate_$rating_method";
518 $self->$method(%opt);
522 our %interval_cache = (); # for timed rates
525 my( $self, %opt ) = @_;
526 my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
529 # this will result in those CDRs being marked as done... is that
532 if ( $part_pkg->option_cacheable('411_rewrite') ) {
533 my $dirass = $part_pkg->option_cacheable('411_rewrite');
535 @dirass = split(',', $dirass);
538 if ( length($self->dst) && grep { $self->dst eq $_ } @dirass ) {
543 my $reason = $part_pkg->check_chargable( $self,
544 'da_rewrote' => $da_rewrote,
547 warn "not charging for CDR ($reason)\n" if $DEBUG;
548 return $self->set_status_and_rated_price( 'skipped',
556 # look up rate details based on called station id
557 # (or calling station id for toll free calls)
560 my( $to_or_from, $number );
561 if ( $self->is_tollfree && ! $part_pkg->option_cacheable('disable_tollfree') )
563 $to_or_from = 'from';
564 $number = $self->src;
565 } else { #regular call
567 $number = $self->dst;
570 warn "parsing call $to_or_from $number\n" if $DEBUG;
572 #remove non-phone# stuff and whitespace
575 # $dest =~ s/^(\w+):// and $proto = $1; #sip:
577 # $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
579 #determine the country code
580 my $intl = $part_pkg->option_cacheable('international_prefix') || '011';
581 my $countrycode = '';
582 if ( $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
583 || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
587 my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
588 #first look for 1 digit country code
589 if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
591 $number = $u1.$u2.$rest;
592 } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
595 } else { #3 digit country code
596 $countrycode = $three;
601 my $domestic_prefix = $part_pkg->option_cacheable('domestic_prefix');
602 $countrycode = length($domestic_prefix) ? $domestic_prefix : '1';
603 $number =~ s/^$countrycode//;# if length($number) > 10;
606 warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
607 my $pretty_dst = "+$countrycode $number";
608 #asterisks here causes inserting the detail to barf, so:
609 $pretty_dst =~ s/\*//g;
611 my $eff_ratenum = $self->is_tollfree('accountcode')
612 ? $part_pkg->option_cacheable('accountcode_tollfree_ratenum')
616 my $intrastate_ratenum = $part_pkg->option_cacheable('intrastate_ratenum');
617 if ( $intrastate_ratenum && !$self->is_tollfree ) {
618 $ratename = 'Interstate'; #until proven otherwise
619 # this is relatively easy only because:
620 # -assume all numbers are valid NANP numbers NOT in a fully-qualified format
621 # -disregard toll-free
622 # -disregard private or unknown numbers
623 # -there is exactly one record in rate_prefix for a given NPANXX
624 # -default to interstate if we can't find one or both of the prefixes
625 my $dstprefix = $self->dst;
626 $dstprefix =~ /^(\d{6})/;
627 $dstprefix = qsearchs('rate_prefix', { 'countrycode' => '1',
630 my $srcprefix = $self->src;
631 $srcprefix =~ /^(\d{6})/;
632 $srcprefix = qsearchs('rate_prefix', { 'countrycode' => '1',
635 if ($srcprefix && $dstprefix
636 && $srcprefix->state && $dstprefix->state
637 && $srcprefix->state eq $dstprefix->state) {
638 $eff_ratenum = $intrastate_ratenum;
639 $ratename = 'Intrastate'; # XXX possibly just use the ratename?
643 $eff_ratenum ||= $part_pkg->option_cacheable('ratenum');
644 my $rate = qsearchs('rate', { 'ratenum' => $eff_ratenum })
645 or die "ratenum $eff_ratenum not found!";
647 my @ltime = localtime($self->startdate);
648 my $weektime = $ltime[0] +
649 $ltime[1]*60 + #minutes
650 $ltime[2]*3600 + #hours
651 $ltime[6]*86400; #days since sunday
652 # if there's no timed rate_detail for this time/region combination,
653 # dest_detail returns the default. There may still be a timed rate
654 # that applies after the starttime of the call, so be careful...
655 my $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
656 'phonenum' => $number,
657 'weektime' => $weektime,
658 'cdrtypenum' => $self->cdrtypenum,
661 unless ( $rate_detail ) {
663 if ( $part_pkg->option_cacheable('ignore_unrateable') ) {
665 if ( $part_pkg->option_cacheable('ignore_unrateable') == 2 ) {
666 # mark the CDR as unrateable
667 return $self->set_status_and_rated_price(
672 } elsif ( $part_pkg->option_cacheable('ignore_unrateable') == 1 ) {
674 warn "no rate_detail found for CDR.acctid: ". $self->acctid.
679 die "unknown ignore_unrateable, pkgpart ". $part_pkg->pkgpart;
684 die "FATAL: no rate_detail found in ".
685 $rate->ratenum. ":". $rate->ratename. " rate plan ".
686 "for +$countrycode $number (CDR acctid ". $self->acctid. "); ".
687 "add a rate or set ignore_unrateable flag on the package def\n";
692 my $rate_region = $rate_detail->dest_region;
693 my $regionnum = $rate_region->regionnum;
694 warn " found rate for regionnum $regionnum ".
695 "and rate detail $rate_detail\n"
698 if ( !exists($interval_cache{$regionnum}) ) {
700 sort { $a->stime <=> $b->stime }
701 map { $_->rate_time->intervals }
702 qsearch({ 'table' => 'rate_detail',
703 'hashref' => { 'ratenum' => $rate->ratenum },
704 'extra_sql' => 'AND ratetimenum IS NOT NULL',
707 $interval_cache{$regionnum} = \@intervals;
708 warn " cached ".scalar(@intervals)." interval(s)\n"
713 # find the price and add detail to the invoice
716 # About this section:
717 # We don't round _anything_ (except granularizing)
718 # until the final $charge = sprintf("%.2f"...).
720 my $seconds_left = $part_pkg->option_cacheable('use_duration')
723 # charge for the first (conn_sec) seconds
724 my $seconds = min($seconds_left, $rate_detail->conn_sec);
725 $seconds_left -= $seconds;
726 $weektime += $seconds;
727 my $charge = $rate_detail->conn_charge;
730 while($seconds_left) {
731 my $ratetimenum = $rate_detail->ratetimenum; # may be empty
733 # find the end of the current rate interval
734 if(@{ $interval_cache{$regionnum} } == 0) {
735 # There are no timed rates in this group, so just stay
736 # in the default rate_detail for the entire duration.
737 # Set an "end" of 1 past the end of the current call.
738 $etime = $weektime + $seconds_left + 1;
740 elsif($ratetimenum) {
741 # This is a timed rate, so go to the etime of this interval.
742 # If it's followed by another timed rate, the stime of that
743 # interval should match the etime of this one.
744 my $interval = $rate_detail->rate_time->contains($weektime);
745 $etime = $interval->etime;
748 # This is a default rate, so use the stime of the next
749 # interval in the sequence.
750 my $next_int = first { $_->stime > $weektime }
751 @{ $interval_cache{$regionnum} };
753 $etime = $next_int->stime;
756 # weektime is near the end of the week, so decrement
757 # it by a full week and use the stime of the first
759 $weektime -= (3600*24*7);
760 $etime = $interval_cache{$regionnum}->[0]->stime;
764 my $charge_sec = min($seconds_left, $etime - $weektime);
766 $seconds_left -= $charge_sec;
768 my $included_min = $opt{'region_group_included_min_hashref'} || {};
770 $included_min->{$regionnum}{$ratetimenum} = $rate_detail->min_included
771 unless exists $included_min->{$regionnum}{$ratetimenum};
773 my $granularity = $rate_detail->sec_granularity;
776 if ( $granularity ) { # charge per minute
777 # Round up to the nearest $granularity
778 if ( $charge_sec and $charge_sec % $granularity ) {
779 $charge_sec += $granularity - ($charge_sec % $granularity);
781 $minutes = $charge_sec / 60; #don't round this
788 $seconds += $charge_sec;
790 my $region_group = ($part_pkg->option_cacheable('min_included') || 0) > 0;
792 ${$opt{region_group_included_min}} -= $minutes
793 if $region_group && $rate_detail->region_group;
795 $included_min->{$regionnum}{$ratetimenum} -= $minutes;
797 $included_min->{$regionnum}{$ratetimenum} <= 0
798 && ( ${$opt{region_group_included_min}} <= 0
799 || ! $rate_detail->region_group
803 #should preserve (display?) this
804 my $charge_min = 0 - $included_min->{$regionnum}{$ratetimenum};
805 $included_min->{$regionnum}{$ratetimenum} = 0;
806 $charge += ($rate_detail->min_charge * $charge_min); #still not rounded
808 } elsif ( ${$opt{region_group_included_min}} > 0
810 && $rate_detail->region_group
813 $included_min->{$regionnum}{$ratetimenum} = 0
816 # choose next rate_detail
817 $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
818 'phonenum' => $number,
819 'weektime' => $etime,
820 'cdrtypenum' => $self->cdrtypenum })
822 # we have now moved forward to $etime
825 } #while $seconds_left
827 # this is why we need regionnum/rate_region....
828 warn " (rate region $rate_region)\n" if $DEBUG;
830 $self->set_status_and_rated_price(
832 sprintf('%.2f', $charge + 0.000001), # NOW round it.
834 'rated_pretty_dst' => $pretty_dst,
835 'rated_regionname' => $rate_region->regionname,
836 'rated_seconds' => $seconds,
837 'rated_granularity' => $rate_detail->sec_granularity, #$granularity
838 'rated_ratedetailnum' => $rate_detail->ratedetailnum,
839 'rated_classnum' => $rate_detail->classnum, #rated_ratedetailnum?
840 'rated_ratename' => $ratename, #not rate_detail - Intrastate/Interstate
845 sub rate_upstream_simple {
846 my( $self, %opt ) = @_;
848 $self->set_status_and_rated_price(
850 sprintf('%.3f', $self->upstream_price),
852 'rated_classnum' => $self->calltypenum,
856 sub rate_single_price {
857 my( $self, %opt ) = @_;
858 my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
860 # a little false laziness w/abov
861 # $rate_detail = new FS::rate_detail({sec_granularity => ... }) ?
863 my $granularity = length($part_pkg->option_cacheable('sec_granularity'))
864 ? $part_pkg->option_cacheable('sec_granularity')
867 my $seconds = $part_pkg->option_cacheable('use_duration')
871 $seconds += $granularity - ( $seconds % $granularity )
872 if $seconds # don't granular-ize 0 billsec calls (bills them)
873 && $granularity # 0 is per call
874 && $seconds % $granularity;
875 my $minutes = $granularity ? ($seconds / 60) : 1;
877 my $charge_min = $minutes;
879 ${$opt{single_price_included_min}} -= $minutes;
880 if ( ${$opt{single_price_included_min}} > 0 ) {
883 $charge_min = 0 - ${$opt{single_price_included_min}};
884 ${$opt{single_price_included_min}} = 0;
888 sprintf('%.4f', ( $part_pkg->option_cacheable('min_charge') * $charge_min )
889 + 0.0000000001 ); #so 1.00005 rounds to 1.0001
891 $self->set_status_and_rated_price(
895 'rated_granularity' => $granularity,
896 'rated_seconds' => $seconds,
901 =item cdr_termination [ TERMPART ]
905 sub cdr_termination {
908 if ( scalar(@_) && $_[0] ) {
909 my $termpart = shift;
911 qsearchs('cdr_termination', { acctid => $self->acctid,
912 termpart => $termpart,
918 qsearch('cdr_termination', { acctid => $self->acctid, } );
926 Parses the calldate in SQL string format and returns a UNIX timestamp.
931 str2time(shift->calldate);
936 Parses the startdate in UNIX timestamp format and returns a string in SQL
942 my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
945 "$year-$mon-$mday $hour:$min:$sec";
950 Returns the FS::cdr_carrier object associated with this CDR, or false if no
951 carrierid is defined.
955 my %carrier_cache = ();
959 return '' unless $self->carrierid;
960 $carrier_cache{$self->carrierid} ||=
961 qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
966 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
967 no FS::cdr_carrier object is assocated with this CDR.
973 my $cdr_carrier = $self->cdr_carrier;
974 $cdr_carrier ? $cdr_carrier->carriername : '';
979 Returns the FS::cdr_calltype object associated with this CDR, or false if no
980 calltypenum is defined.
984 my %calltype_cache = ();
988 return '' unless $self->calltypenum;
989 $calltype_cache{$self->calltypenum} ||=
990 qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
995 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
996 no FS::cdr_calltype object is assocated with this CDR.
1002 my $cdr_calltype = $self->cdr_calltype;
1003 $cdr_calltype ? $cdr_calltype->calltypename : '';
1006 =item downstream_csv [ OPTION => VALUE, ... ]
1010 my %export_names = (
1013 'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
1016 'name' => 'Simple with source',
1017 'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
1018 #"Date,Time,Name,Called From,Destination,Duration,Price",
1020 'accountcode_simple' => {
1021 'name' => 'Simple with accountcode',
1022 'invoice_header' => "Date,Time,Called From,Account,Duration,Price",
1026 'invoice_header' => "Date/Time,Called Number,Min/Sec,Price",
1029 'name' => 'Default',
1030 'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
1032 'source_default' => {
1033 'name' => 'Default with source',
1034 'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
1036 'accountcode_default' => {
1037 'name' => 'Default plus accountcode',
1038 'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
1040 'description_default' => {
1041 'name' => 'Default with description field as destination',
1042 'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
1045 'name' => 'Summary, one line per service',
1046 'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
1049 'name' => 'Number of calls, one line per service',
1050 'invoice_header' => 'Caller,Rate,Messages,Price',
1052 'sum_duration_prefix' => {
1053 'name' => 'Summary, one line per destination prefix',
1054 'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
1058 my %export_formats = ();
1059 sub export_formats {
1062 return %export_formats if keys %export_formats;
1064 my $conf = new FS::Conf;
1065 my $date_format = $conf->config('date_format') || '%m/%d/%Y';
1067 # call duration in the largest units that accurately reflect the granularity
1068 my $duration_sub = sub {
1069 my($cdr, %opt) = @_;
1070 my $sec = $opt{seconds} || $cdr->billsec;
1071 if ( defined $opt{granularity} &&
1072 $opt{granularity} == 0 ) { #per call
1075 elsif ( defined $opt{granularity} && $opt{granularity} == 60 ) {#full minutes
1076 my $min = int($sec/60);
1080 else { #anything else
1081 return sprintf("%dm %ds", $sec/60, $sec%60);
1085 my $price_sub = sub {
1086 my ($cdr, %opt) = @_;
1088 if ( defined($opt{charge}) ) {
1089 $price = $opt{charge};
1091 elsif ( $opt{inbound} ) {
1092 my $term = $cdr->cdr_termination(1); # 1 = inbound
1093 $price = $term->rated_price if defined $term;
1096 $price = $cdr->rated_price;
1098 length($price) ? ($opt{money_char} . $price) : '';
1103 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
1104 sub { time2str('%r', shift->calldate_unix ) }, #TIME
1106 'dst', #NUMBER_DIALED
1107 $duration_sub, #DURATION
1108 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
1112 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
1113 sub { time2str('%r', shift->calldate_unix ) }, #TIME
1116 'dst', #NUMBER_DIALED
1117 $duration_sub, #DURATION
1118 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
1121 'accountcode_simple' => [
1122 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
1123 sub { time2str('%r', shift->calldate_unix ) }, #TIME
1125 'accountcode', #NUMBER_DIALED
1126 $duration_sub, #DURATION
1130 # for summary formats, the CDR is a fictitious object containing the
1131 # total billsec and the phone number of the service
1133 sub { my($cdr, %opt) = @_; $opt{ratename} },
1134 sub { my($cdr, %opt) = @_; $opt{count} },
1135 sub { my($cdr, %opt) = @_; int($opt{seconds}/60).'m' },
1140 sub { my($cdr, %opt) = @_; $opt{ratename} },
1141 sub { my($cdr, %opt) = @_; $opt{count} },
1145 sub { time2str('%d %b - %I:%M %p', shift->calldate_unix) },
1153 sub { time2str($date_format, shift->calldate_unix ) },
1154 # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
1157 sub { time2str('%r', shift->calldate_unix ) },
1158 # 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
1161 sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
1163 #REGIONNAME ("Destination")
1164 sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
1173 $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
1174 $export_formats{'accountcode_default'} =
1175 [ @{ $export_formats{'default'} }[0,1],
1177 @{ $export_formats{'default'} }[2..5],
1179 my @default = @{ $export_formats{'default'} };
1180 $export_formats{'description_default'} =
1181 [ 'src', @default[0..2],
1182 sub { my($cdr, %opt) = @_; $cdr->description },
1185 return %export_formats;
1188 =item downstream_csv OPTION => VALUE ...
1190 Returns a string of formatted call details for display on an invoice.
1196 charge - override the 'rated_price' field of the CDR
1198 seconds - override the 'billsec' field of the CDR
1200 count - number of usage events included in this record, for summary formats
1202 ratename - name of the rate table used to rate this call
1208 sub downstream_csv {
1209 my( $self, %opt ) = @_;
1211 my $format = $opt{'format'};
1212 my %formats = $self->export_formats;
1213 return "Unknown format $format" unless exists $formats{$format};
1215 #my $conf = new FS::Conf;
1216 #$opt{'money_char'} ||= $conf->config('money_char') || '$';
1217 $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
1219 eval "use Text::CSV_XS;";
1221 my $csv = new Text::CSV_XS;
1225 ref($_) ? &{$_}($self, %opt) : $self->$_();
1227 @{ $formats{$format} };
1229 return @columns if defined $opt{'keeparray'};
1231 my $status = $csv->combine(@columns);
1232 die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
1241 =head1 CLASS METHODS
1245 =item invoice_formats
1247 Returns an ordered list of key value pairs containing invoice format names
1248 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
1252 # in the future, load this dynamically from detail_format classes
1254 sub invoice_formats {
1255 map { ($_ => $export_names{$_}->{'name'}) }
1256 grep { $export_names{$_}->{'invoice_header'} }
1260 =item invoice_header FORMAT
1262 Returns a scalar containing the CSV column header for invoice format FORMAT.
1266 sub invoice_header {
1268 $export_names{$format}->{'invoice_header'};
1273 Clears cdr and any associated cdr_termination statuses - used for
1282 local $SIG{HUP} = 'IGNORE';
1283 local $SIG{INT} = 'IGNORE';
1284 local $SIG{QUIT} = 'IGNORE';
1285 local $SIG{TERM} = 'IGNORE';
1286 local $SIG{TSTP} = 'IGNORE';
1287 local $SIG{PIPE} = 'IGNORE';
1289 my $oldAutoCommit = $FS::UID::AutoCommit;
1290 local $FS::UID::AutoCommit = 0;
1293 if ( $cdr_prerate && $cdr_prerate_cdrtypenums{$self->cdrtypenum}
1294 && $self->rated_ratedetailnum #avoid putting old CDRs back in "rated"
1295 && $self->freesidestatus eq 'done'
1299 $self->freesidestatus('rated');
1301 $self->freesidestatus('');
1304 my $error = $self->replace;
1306 $dbh->rollback if $oldAutoCommit;
1310 foreach my $cdr_termination ( $self->cdr_termination ) {
1311 #$cdr_termination->status('');
1312 #$error = $cdr_termination->replace;
1313 $error = $cdr_termination->delete;
1315 $dbh->rollback if $oldAutoCommit;
1320 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1325 =item import_formats
1327 Returns an ordered list of key value pairs containing import format names
1328 as keys (for use with batch_import) and "pretty" format names as values.
1332 #false laziness w/part_pkg & part_export
1335 foreach my $INC ( @INC ) {
1336 warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
1337 foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
1338 warn "attempting to load CDR format info from $file\n" if $DEBUG;
1339 $file =~ /\/(\w+)\.pm$/ or do {
1340 warn "unrecognized file in $INC/FS/cdr/: $file\n";
1344 my $info = eval "use FS::cdr::$mod; ".
1345 "\\%FS::cdr::$mod\::info;";
1347 die "error using FS::cdr::$mod (skipping): $@\n" if $@;
1350 unless ( keys %$info ) {
1351 warn "no %info hash found in FS::cdr::$mod, skipping\n";
1354 warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
1355 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1356 warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
1359 $cdr_info{$mod} = $info;
1363 tie my %import_formats, 'Tie::IxHash',
1364 map { $_ => $cdr_info{$_}->{'name'} }
1365 sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
1366 grep { exists($cdr_info{$_}->{'import_fields'}) }
1369 sub import_formats {
1373 sub _cdr_min_parser_maker {
1375 my @fields = ref($field) ? @$field : ($field);
1376 @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
1378 my( $cdr, $min ) = @_;
1379 my $sec = eval { _cdr_min_parse($min) };
1380 die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
1381 $cdr->$_($sec) foreach @fields;
1385 sub _cdr_min_parse {
1387 sprintf('%.0f', $min * 60 );
1390 sub _cdr_date_parser_maker {
1393 my @fields = ref($field) ? @$field : ($field);
1395 my( $cdr, $datestring ) = @_;
1396 my $unixdate = eval { _cdr_date_parse($datestring, %options) };
1397 die "error parsing date for @fields from $datestring: $@\n" if $@;
1398 $cdr->$_($unixdate) foreach @fields;
1402 sub _cdr_date_parse {
1406 return '' unless length($date); #that's okay, it becomes NULL
1407 return '' if $date eq 'NA'; #sansay
1409 if ( $date =~ /^([a-z]{3})\s+([a-z]{3})\s+(\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s+(\d{4})$/i && $7 > 1970 ) {
1410 my $time = str2time($date);
1411 return $time if $time > 100000; #just in case
1414 my($year, $mon, $day, $hour, $min, $sec);
1416 #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
1417 #taqua #2007-10-31 08:57:24.113000000
1419 if ( $date =~ /^\s*(\d{4})\D(\d{1,2})\D(\d{1,2})\D+(\d{1,2})\D(\d{1,2})\D(\d{1,2})(\D|$)/ ) {
1420 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1421 } elsif ( $date =~ /^\s*(\d{1,2})\D(\d{1,2})\D(\d{4})\s+(\d{1,2})\D(\d{1,2})(?:\D(\d{1,2}))?(\D|$)/ ) {
1422 # 8/26/2010 12:20:01
1423 # optionally without seconds
1424 ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1425 $sec = 0 if !defined($sec);
1426 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
1427 # broadsoft: 20081223201938.314
1428 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1429 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\d+(\D|$)/ ) {
1430 # Taqua OM: 20050422203450943
1431 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1432 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/ ) {
1433 # WIP: 20100329121420
1434 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1435 } elsif ( $date =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/) {
1437 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1440 die "unparsable date: $date"; #maybe we shouldn't die...
1443 return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
1444 && $hour == 0 && $min == 0 && $sec == 0;
1446 if ($options{gmt}) {
1447 timegm($sec, $min, $hour, $day, $mon-1, $year);
1449 timelocal($sec, $min, $hour, $day, $mon-1, $year);
1453 =item batch_import HASHREF
1455 Imports CDR records. Available options are:
1467 Hash reference of preset fields, typically cdrbatch
1471 Set true to prevent throwing an error on empty imports
1477 my %import_options = (
1480 'batch_keycol' => 'cdrbatchnum',
1481 'batch_table' => 'cdr_batch',
1482 'batch_namecol' => 'cdrbatch',
1484 'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
1488 #drop the || 'csv' to allow auto xls for csv types?
1489 'format_types' => { map { $_ => lc($cdr_info{$_}->{'type'} || 'csv'); }
1493 'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
1497 'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
1501 'format_fixedlength_formats' =>
1502 { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
1506 'format_xml_formats' =>
1507 { map { $_ => $cdr_info{$_}->{'xml_format'}; }
1511 'format_row_callbacks' => { map { $_ => $cdr_info{$_}->{'row_callback'}; }
1516 sub _import_options {
1523 my $iopt = _import_options;
1524 $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
1526 if ( defined $opt->{'cdrtypenum'} ) {
1527 $opt->{'preinsert_callback'} = sub {
1528 my($record,$param) = (shift,shift);
1529 $record->cdrtypenum($opt->{'cdrtypenum'});
1534 FS::Record::batch_import( $opt );
1538 =item process_batch_import
1542 sub process_batch_import {
1545 my $opt = _import_options;
1546 # $opt->{'params'} = [ 'format', 'cdrbatch' ];
1548 FS::Record::process_batch_import( $job, $opt, @_ );
1551 # if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
1552 # @columns = map { s/^ +//; $_; } @columns;
1557 # Used by FS::Upgrade to migrate to a new database.
1560 my ($class, %opts) = @_;
1562 warn "$me upgrading $class\n" if $DEBUG;
1564 my $sth = dbh->prepare(
1565 'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
1566 ) or die dbh->errstr;
1568 $sth->execute or die $sth->errstr;
1570 my %cdrbatchnum = ();
1571 while (my $row = $sth->fetchrow_arrayref) {
1573 my $cdr_batch = qsearchs( 'cdr_batch', { 'cdrbatch' => $row->[0] } );
1574 unless ( $cdr_batch ) {
1575 $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
1576 my $error = $cdr_batch->insert;
1577 die $error if $error;
1580 $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
1583 $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
1585 foreach my $cdrbatch (keys %cdrbatchnum) {
1586 $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
1591 =item ip_addr_sql FIELD RANGE
1593 Returns an SQL condition to search for CDRs with an IP address
1594 within RANGE. FIELD is either 'src_ip_addr' or 'dst_ip_addr'. RANGE
1595 should be in the form "a.b.c.d-e.f.g.h' (dotted quads), where any of
1596 the leftmost octets of the second address can be omitted if they're
1597 the same as the first address.
1603 my ($field, $range) = @_;
1604 $range =~ /^[\d\.-]+$/ or die "bad ip address range '$range'";
1605 my @r = split('-', $range);
1606 my @saddr = split('\.', $r[0] || '');
1607 my @eaddr = split('\.', $r[1] || '');
1608 unshift @eaddr, (undef) x (4 - scalar @eaddr);
1610 $eaddr[$_] = $saddr[$_] if !defined $eaddr[$_];
1612 "$field >= '".sprintf('%03d.%03d.%03d.%03d', @saddr) . "' AND ".
1613 "$field <= '".sprintf('%03d.%03d.%03d.%03d', @eaddr) . "'";
1622 L<FS::Record>, schema.html from the base documentation.