4 use vars qw( @ISA @EXPORT_OK $DEBUG $me );
10 use FS::UID qw( dbh );
12 use FS::Record qw( qsearch qsearchs );
17 use FS::cdr_termination;
22 @ISA = qw(FS::Record);
23 @EXPORT_OK = qw( _cdr_date_parser_maker _cdr_min_parser_maker );
30 FS::cdr - Object methods for cdr records
36 $record = new FS::cdr \%hash;
37 $record = new FS::cdr { 'column' => 'value' };
39 $error = $record->insert;
41 $error = $new_record->replace($old_record);
43 $error = $record->delete;
45 $error = $record->check;
49 An FS::cdr object represents an Call Data Record, typically from a telephony
50 system or provider of some sort. FS::cdr inherits from FS::Record. The
51 following fields are currently supported:
55 =item acctid - primary key
57 =item calldate - Call timestamp (SQL timestamp)
59 =item clid - Caller*ID with text
61 =item src - Caller*ID number / Source number
63 =item dst - Destination extension
65 =item dcontext - Destination context
67 =item channel - Channel used
69 =item dstchannel - Destination channel if appropriate
71 =item lastapp - Last application if appropriate
73 =item lastdata - Last application data
75 =item startdate - Start of call (UNIX-style integer timestamp)
77 =item answerdate - Answer time of call (UNIX-style integer timestamp)
79 =item enddate - End time of call (UNIX-style integer timestamp)
81 =item duration - Total time in system, in seconds
83 =item billsec - Total time call is up, in seconds
85 =item disposition - What happened to the call: ANSWERED, NO ANSWER, BUSY
87 =item amaflags - What flags to use: BILL, IGNORE etc, specified on a per channel basis like accountcode.
91 #ignore the "omit" and "documentation" AMAs??
92 #AMA = Automated Message Accounting.
93 #default: Sets the system default.
94 #omit: Do not record calls.
95 #billing: Mark the entry for billing
96 #documentation: Mark the entry for documentation.
98 =item accountcode - CDR account number to use: account
100 =item uniqueid - Unique channel identifier (Unitel/RSLCOM Event ID)
102 =item userfield - CDR user-defined field
104 =item cdr_type - CDR type - see L<FS::cdr_type> (Usage = 1, S&E = 7, OC&C = 8)
106 =item charged_party - Service number to be billed
108 =item upstream_currency - Wholesale currency from upstream
110 =item upstream_price - Wholesale price from upstream
112 =item upstream_rateplanid - Upstream rate plan ID
114 =item rated_price - Rated (or re-rated) price
116 =item distance - km (need units field?)
118 =item islocal - Local - 1, Non Local = 0
120 =item calltypenum - Type of call - see L<FS::cdr_calltype>
122 =item description - Description (cdr_type 7&8 only) (used for cust_bill_pkg.itemdesc)
124 =item quantity - Number of items (cdr_type 7&8 only)
126 =item carrierid - Upstream Carrier ID (see L<FS::cdr_carrier>)
130 #Telstra =1, Optus = 2, RSL COM = 3
132 =item upstream_rateid - Upstream Rate ID
134 =item svcnum - Link to customer service (see L<FS::cust_svc>)
136 =item freesidestatus - NULL, processing-tiered, rated, done
138 =item freesiderewritestatus - NULL, done, skipped
150 Creates a new CDR. To add the CDR to the database, see L<"insert">.
152 Note that this stores the hash reference, not a distinct copy of the hash it
153 points to. You can ask the object for a copy with the I<hash> method.
157 # the new method can be inherited from FS::Record, if a table method is defined
164 #XXX fill in some (more) nice names
166 'calldate' => 'Call date',
167 'clid' => 'Caller ID',
169 'dst' => 'Destination',
170 'dcontext' => 'Dest. context',
171 'channel' => 'Channel',
172 'dstchannel' => 'Destination channel',
175 'startdate' => 'Start date',
176 'answerdate' => 'Answer date',
177 'enddate' => 'End date',
178 'duration' => 'Duration',
179 'billsec' => 'Billable seconds',
180 'disposition' => 'Disposition',
181 'amaflags' => 'AMA flags',
182 'accountcode' => 'Account code',
184 'userfield' => 'User field',
186 'charged_party' => 'Charged party',
187 #'upstream_currency' => '',
188 'upstream_price' => 'Upstream price',
189 #'upstream_rateplanid' => '',
190 #'ratedetailnum' => '',
191 'rated_price' => 'Rated price',
194 #'calltypenum' => '',
195 #'description' => '',
197 'carrierid' => 'Carrier ID',
198 #'upstream_rateid' => '',
199 'svcnum' => 'Freeside service',
200 'freesidestatus' => 'Freeside status',
201 'freesiderewritestatus' => 'Freeside rewrite status',
202 'cdrbatch' => 'Legacy batch',
203 'cdrbatchnum' => 'Batch',
212 Adds this record to the database. If there is an error, returns the error,
213 otherwise returns false.
217 # the insert method can be inherited from FS::Record
221 Delete this record from the database.
225 # the delete method can be inherited from FS::Record
227 =item replace OLD_RECORD
229 Replaces the OLD_RECORD with this one in the database. If there is an error,
230 returns the error, otherwise returns false.
234 # the replace method can be inherited from FS::Record
238 Checks all fields to make sure this is a valid CDR. If there is
239 an error, returns the error, otherwise returns false. Called by the insert
242 Note: Unlike most types of records, we don't want to "reject" a CDR and we want
243 to process them as quickly as possible, so we allow the database to check most
251 # we don't want to "reject" a CDR like other sorts of input...
253 # $self->ut_numbern('acctid')
254 ## || $self->ut_('calldate')
255 # || $self->ut_text('clid')
256 # || $self->ut_text('src')
257 # || $self->ut_text('dst')
258 # || $self->ut_text('dcontext')
259 # || $self->ut_text('channel')
260 # || $self->ut_text('dstchannel')
261 # || $self->ut_text('lastapp')
262 # || $self->ut_text('lastdata')
263 # || $self->ut_numbern('startdate')
264 # || $self->ut_numbern('answerdate')
265 # || $self->ut_numbern('enddate')
266 # || $self->ut_number('duration')
267 # || $self->ut_number('billsec')
268 # || $self->ut_text('disposition')
269 # || $self->ut_number('amaflags')
270 # || $self->ut_text('accountcode')
271 # || $self->ut_text('uniqueid')
272 # || $self->ut_text('userfield')
273 # || $self->ut_numbern('cdrtypenum')
274 # || $self->ut_textn('charged_party')
275 ## || $self->ut_n('upstream_currency')
276 ## || $self->ut_n('upstream_price')
277 # || $self->ut_numbern('upstream_rateplanid')
278 ## || $self->ut_n('distance')
279 # || $self->ut_numbern('islocal')
280 # || $self->ut_numbern('calltypenum')
281 # || $self->ut_textn('description')
282 # || $self->ut_numbern('quantity')
283 # || $self->ut_numbern('carrierid')
284 # || $self->ut_numbern('upstream_rateid')
285 # || $self->ut_numbern('svcnum')
286 # || $self->ut_textn('freesidestatus')
287 # || $self->ut_textn('freesiderewritestatus')
289 # return $error if $error;
291 for my $f ( grep { $self->$_ =~ /\D/ } qw(startdate answerdate enddate)){
292 $self->$f( str2time($self->$f) );
295 $self->calldate( $self->startdate_sql )
296 if !$self->calldate && $self->startdate;
298 #was just for $format eq 'taqua' but can't see the harm... add something to
299 #disable if it becomes a problem
300 if ( $self->duration eq '' && $self->enddate && $self->startdate ) {
301 $self->duration( $self->enddate - $self->startdate );
303 if ( $self->billsec eq '' && $self->enddate && $self->answerdate ) {
304 $self->billsec( $self->enddate - $self->answerdate );
307 $self->set_charged_party;
309 #check the foreign keys even?
310 #do we want to outright *reject* the CDR?
312 $self->ut_numbern('acctid')
314 #add a config option to turn these back on if someone needs 'em
316 # #Usage = 1, S&E = 7, OC&C = 8
317 # || $self->ut_foreign_keyn('cdrtypenum', 'cdr_type', 'cdrtypenum' )
319 # #the big list in appendix 2
320 # || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
322 # # Telstra =1, Optus = 2, RSL COM = 3
323 # || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
325 return $error if $error;
330 =item is_tollfree [ COLUMN ]
332 Returns true when the cdr represents a toll free number and false otherwise.
334 By default, inspects the dst field, but an optional column name can be passed
335 to inspect other field.
341 my $field = scalar(@_) ? shift : 'dst';
342 ( $self->$field() =~ /^(\+?1)?8(8|([02-7])\3)/ ) ? 1 : 0;
345 =item set_charged_party
347 If the charged_party field is already set, does nothing. Otherwise:
349 If the cdr-charged_party-accountcode config option is enabled, sets the
350 charged_party to the accountcode.
352 Otherwise sets the charged_party normally: to the src field in most cases,
353 or to the dst field if it is a toll free number.
357 sub set_charged_party {
360 my $conf = new FS::Conf;
362 unless ( $self->charged_party ) {
364 if ( $conf->exists('cdr-charged_party-accountcode') && $self->accountcode ){
366 my $charged_party = $self->accountcode;
367 $charged_party =~ s/^0+//
368 if $conf->exists('cdr-charged_party-accountcode-trim_leading_0s');
369 $self->charged_party( $charged_party );
371 } elsif ( $conf->exists('cdr-charged_party-field') ) {
373 my $field = $conf->config('cdr-charged_party-field');
374 $self->charged_party( $self->$field() );
378 if ( $self->is_tollfree ) {
379 $self->charged_party($self->dst);
381 $self->charged_party($self->src);
388 # my $prefix = $conf->config('cdr-charged_party-truncate_prefix');
389 # my $prefix_len = length($prefix);
390 # my $trunc_len = $conf->config('cdr-charged_party-truncate_length');
392 # $self->charged_party( substr($self->charged_party, 0, $trunc_len) )
393 # if $prefix_len && $trunc_len
394 # && substr($self->charged_party, 0, $prefix_len) eq $prefix;
398 =item set_status STATUS
400 Sets the status to the provided string. If there is an error, returns the
401 error, otherwise returns false.
406 my($self, $status) = @_;
407 $self->freesidestatus($status);
411 =item set_status_and_rated_price STATUS RATED_PRICE [ SVCNUM [ OPTION => VALUE ... ] ]
413 Sets the status and rated price.
415 Available options are: inbound, rated_seconds, rated_minutes, rated_classnum, rated_ratename
417 If there is an error, returns the error, otherwise returns false.
421 sub set_status_and_rated_price {
422 my($self, $status, $rated_price, $svcnum, %opt) = @_;
424 if ($opt{'inbound'}) {
426 my $term = $self->cdr_termination( 1 ); #1: inbound
429 warn "replacing existing cdr status (".$self->acctid.")\n" if $term;
430 $error = $term->delete;
431 return $error if $error;
433 $term = FS::cdr_termination->new({
434 acctid => $self->acctid,
436 rated_price => $rated_price,
439 $term->rated_seconds($opt{rated_seconds}) if exists($opt{rated_seconds});
440 $term->rated_minutes($opt{rated_minutes}) if exists($opt{rated_minutes});
441 $term->svcnum($svcnum) if $svcnum;
442 return $term->insert;
446 $self->freesidestatus($status);
447 $self->rated_price($rated_price);
449 foreach grep exists($opt{$_}), map "rated_$_",
450 qw( pretty_dst regionname seconds minutes granularity
451 ratedetailnum classnum ratename );
452 $self->svcnum($svcnum) if $svcnum;
453 return $self->replace();
458 =item rate [ OPTION => VALUE ... ]
460 Rates this CDR according and sets the status to 'rated'.
462 Available options are: part_pkg, svcnum, single_price_included_minutes, region_group, region_group_included_minutes.
464 part_pkg is required.
466 If svcnum is specified, will also associate this CDR with the specified svcnum.
468 single_price_included_minutes is requried for single_price price plans
469 (otherwise unused/ignored). It should be set to a scalar reference of the
470 number of included minutes and will be decremented by the rated minutes of this
473 region_group_included_minutes is required for prefix price plans which have
474 included minutes (otherwise unused/ignored). It should be set to a scalar
475 reference of the number of included minutes and will be decremented by the
476 rated minutes of this CDR.
478 region_group_included_minutes_hashref is required for prefix price plans which
479 have included minues (otehrwise unused/ignored). It should be set to an empty
480 hashref at the start of a month's rating and then preserved across CDRs.
485 my( $self, %opt ) = @_;
486 my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
489 warn "rating CDR $self\n".
490 join('', map { " $_ => ". $self->{$_}. "\n" } keys %$self );
493 my $rating_method = $part_pkg->option_cacheable('rating_method') || 'prefix';
494 my $method = "rate_$rating_method";
495 $self->$method(%opt);
499 our %interval_cache = (); # for timed rates
502 my( $self, %opt ) = @_;
503 my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
506 # this will result in those CDRs being marked as done... is that
509 if ( $part_pkg->option_cacheable('411_rewrite') ) {
510 my $dirass = $part_pkg->option_cacheable('411_rewrite');
512 @dirass = split(',', $dirass);
515 if ( length($self->dst) && grep { $self->dst eq $_ } @dirass ) {
520 my $reason = $part_pkg->check_chargable( $self,
521 'da_rewrote' => $da_rewrote,
524 warn "not charging for CDR ($reason)\n" if $DEBUG;
525 return $self->set_status_and_rated_price( 'rated',
533 # look up rate details based on called station id
534 # (or calling station id for toll free calls)
537 my( $to_or_from, $number );
538 if ( $self->is_tollfree && ! $part_pkg->option_cacheable('disable_tollfree') )
540 $to_or_from = 'from';
541 $number = $self->src;
542 } else { #regular call
544 $number = $self->dst;
547 warn "parsing call $to_or_from $number\n" if $DEBUG;
549 #remove non-phone# stuff and whitespace
552 # $dest =~ s/^(\w+):// and $proto = $1; #sip:
554 # $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
556 #determine the country code
557 my $intl = $part_pkg->option_cacheable('international_prefix') || '011';
558 my $countrycode = '';
559 if ( $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
560 || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
564 my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
565 #first look for 1 digit country code
566 if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
568 $number = $u1.$u2.$rest;
569 } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
572 } else { #3 digit country code
573 $countrycode = $three;
578 my $domestic_prefix = $part_pkg->option_cacheable('domestic_prefix');
579 $countrycode = length($domestic_prefix) ? $domestic_prefix : '1';
580 $number =~ s/^$countrycode//;# if length($number) > 10;
583 warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
584 my $pretty_dst = "+$countrycode $number";
585 #asterisks here causes inserting the detail to barf, so:
586 $pretty_dst =~ s/\*//g;
588 my $eff_ratenum = $self->is_tollfree('accountcode')
589 ? $part_pkg->option_cacheable('accountcode_tollfree_ratenum')
593 my $intrastate_ratenum = $part_pkg->option_cacheable('intrastate_ratenum');
594 if ( $intrastate_ratenum && !$self->is_tollfree ) {
595 $ratename = 'Interstate'; #until proven otherwise
596 # this is relatively easy only because:
597 # -assume all numbers are valid NANP numbers NOT in a fully-qualified format
598 # -disregard toll-free
599 # -disregard private or unknown numbers
600 # -there is exactly one record in rate_prefix for a given NPANXX
601 # -default to interstate if we can't find one or both of the prefixes
602 my $dstprefix = $self->dst;
603 $dstprefix =~ /^(\d{6})/;
604 $dstprefix = qsearchs('rate_prefix', { 'countrycode' => '1',
607 my $srcprefix = $self->src;
608 $srcprefix =~ /^(\d{6})/;
609 $srcprefix = qsearchs('rate_prefix', { 'countrycode' => '1',
612 if ($srcprefix && $dstprefix
613 && $srcprefix->state && $dstprefix->state
614 && $srcprefix->state eq $dstprefix->state) {
615 $eff_ratenum = $intrastate_ratenum;
616 $ratename = 'Intrastate'; # XXX possibly just use the ratename?
620 $eff_ratenum ||= $part_pkg->option_cacheable('ratenum');
621 my $rate = qsearchs('rate', { 'ratenum' => $eff_ratenum })
622 or die "ratenum $eff_ratenum not found!";
624 my @ltime = localtime($self->startdate);
625 my $weektime = $ltime[0] +
626 $ltime[1]*60 + #minutes
627 $ltime[2]*3600 + #hours
628 $ltime[6]*86400; #days since sunday
629 # if there's no timed rate_detail for this time/region combination,
630 # dest_detail returns the default. There may still be a timed rate
631 # that applies after the starttime of the call, so be careful...
632 my $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
633 'phonenum' => $number,
634 'weektime' => $weektime,
635 'cdrtypenum' => $self->cdrtypenum,
638 unless ( $rate_detail ) {
640 if ( $part_pkg->option_cacheable('ignore_unrateable') ) {
642 if ( $part_pkg->option_cacheable('ignore_unrateable') == 2 ) {
643 # mark the CDR as unrateable
644 return $self->set_status_and_rated_price(
649 } elsif ( $part_pkg->option_cacheable('ignore_unrateable') == 1 ) {
651 warn "no rate_detail found for CDR.acctid: ". $self->acctid.
656 die "unknown ignore_unrateable, pkgpart ". $part_pkg->pkgpart;
661 die "FATAL: no rate_detail found in ".
662 $rate->ratenum. ":". $rate->ratename. " rate plan ".
663 "for +$countrycode $number (CDR acctid ". $self->acctid. "); ".
664 "add a rate or set ignore_unrateable flag on the package def\n";
669 my $rate_region = $rate_detail->dest_region;
670 my $regionnum = $rate_region->regionnum;
671 warn " found rate for regionnum $regionnum ".
672 "and rate detail $rate_detail\n"
675 if ( !exists($interval_cache{$regionnum}) ) {
677 sort { $a->stime <=> $b->stime }
678 map { my $r = $_->rate_time; $r ? $r->intervals : () }
681 $interval_cache{$regionnum} = \@intervals;
682 warn " cached ".scalar(@intervals)." interval(s)\n"
687 # find the price and add detail to the invoice
690 # About this section:
691 # We don't round _anything_ (except granularizing)
692 # until the final $charge = sprintf("%.2f"...).
694 my $seconds_left = $part_pkg->option_cacheable('use_duration')
697 # charge for the first (conn_sec) seconds
698 my $seconds = min($seconds_left, $rate_detail->conn_sec);
699 $seconds_left -= $seconds;
700 $weektime += $seconds;
701 my $charge = $rate_detail->conn_charge;
704 while($seconds_left) {
705 my $ratetimenum = $rate_detail->ratetimenum; # may be empty
707 # find the end of the current rate interval
708 if(@{ $interval_cache{$regionnum} } == 0) {
709 # There are no timed rates in this group, so just stay
710 # in the default rate_detail for the entire duration.
711 # Set an "end" of 1 past the end of the current call.
712 $etime = $weektime + $seconds_left + 1;
714 elsif($ratetimenum) {
715 # This is a timed rate, so go to the etime of this interval.
716 # If it's followed by another timed rate, the stime of that
717 # interval should match the etime of this one.
718 my $interval = $rate_detail->rate_time->contains($weektime);
719 $etime = $interval->etime;
722 # This is a default rate, so use the stime of the next
723 # interval in the sequence.
724 my $next_int = first { $_->stime > $weektime }
725 @{ $interval_cache{$regionnum} };
727 $etime = $next_int->stime;
730 # weektime is near the end of the week, so decrement
731 # it by a full week and use the stime of the first
733 $weektime -= (3600*24*7);
734 $etime = $interval_cache{$regionnum}->[0]->stime;
738 my $charge_sec = min($seconds_left, $etime - $weektime);
740 $seconds_left -= $charge_sec;
742 my $included_min = $opt{'region_group_included_min_hashref'} || {};
744 $included_min->{$regionnum}{$ratetimenum} = $rate_detail->min_included
745 unless exists $included_min->{$regionnum}{$ratetimenum};
747 my $granularity = $rate_detail->sec_granularity;
750 if ( $granularity ) { # charge per minute
751 # Round up to the nearest $granularity
752 if ( $charge_sec and $charge_sec % $granularity ) {
753 $charge_sec += $granularity - ($charge_sec % $granularity);
755 $minutes = $charge_sec / 60; #don't round this
762 $seconds += $charge_sec;
764 my $region_group = ($part_pkg->option_cacheable('min_included') || 0) > 0;
766 ${$opt{region_group_included_min}} -= $minutes
767 if $region_group && $rate_detail->region_group;
769 $included_min->{$regionnum}{$ratetimenum} -= $minutes;
771 $included_min->{$regionnum}{$ratetimenum} <= 0
772 && ( ${$opt{region_group_included_min}} <= 0
773 || ! $rate_detail->region_group
777 #should preserve (display?) this
778 my $charge_min = 0 - $included_min->{$regionnum}{$ratetimenum};
779 $included_min->{$regionnum}{$ratetimenum} = 0;
780 $charge += ($rate_detail->min_charge * $charge_min); #still not rounded
782 } elsif ( ${$opt{region_group_included_min}} > 0
784 && $rate_detail->region_group
787 $included_min->{$regionnum}{$ratetimenum} = 0
790 # choose next rate_detail
791 $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
792 'phonenum' => $number,
793 'weektime' => $etime,
794 'cdrtypenum' => $self->cdrtypenum })
796 # we have now moved forward to $etime
799 } #while $seconds_left
801 # this is why we need regionnum/rate_region....
802 warn " (rate region $rate_region)\n" if $DEBUG;
804 $self->set_status_and_rated_price(
806 sprintf('%.2f', $charge + 0.000001), # NOW round it.
808 'rated_pretty_dst' => $pretty_dst,
809 'rated_regionname' => $rate_region->regionname,
810 'rated_seconds' => $seconds,
811 'rated_granularity' => $rate_detail->sec_granularity, #$granularity
812 'rated_ratedetailnum' => $rate_detail->ratedetailnum,
813 'rated_classnum' => $rate_detail->classnum, #rated_ratedetailnum?
814 'rated_ratename' => $ratename, #not rate_detail - Intrastate/Interstate
819 sub rate_upstream_simple {
820 my( $self, %opt ) = @_;
822 $self->set_status_and_rated_price( 'rated',
823 sprintf('%.3f', $self->upstream_price),
828 sub rate_single_price {
829 my( $self, %opt ) = @_;
830 my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
832 # a little false laziness w/abov
833 # $rate_detail = new FS::rate_detail({sec_granularity => ... }) ?
835 my $granularity = length($part_pkg->option_cacheable('sec_granularity'))
836 ? $part_pkg->option_cacheable('sec_granularity')
839 my $seconds = $part_pkg->option_cacheable('use_duration')
843 $seconds += $granularity - ( $seconds % $granularity )
844 if $seconds # don't granular-ize 0 billsec calls (bills them)
845 && $granularity # 0 is per call
846 && $seconds % $granularity;
847 my $minutes = $granularity ? ($seconds / 60) : 1;
849 my $charge_min = $minutes;
851 ${$opt{single_price_included_min}} -= $minutes;
852 if ( ${$opt{single_price_included_min}} > 0 ) {
855 $charge_min = 0 - ${$opt{single_price_included_min}};
856 ${$opt{single_price_included_min}} = 0;
860 sprintf('%.4f', ( $part_pkg->option_cacheable('min_charge') * $charge_min )
861 + 0.0000000001 ); #so 1.00005 rounds to 1.0001
863 $self->set_status_and_rated_price( 'rated',
870 =item cdr_termination [ TERMPART ]
874 sub cdr_termination {
877 if ( scalar(@_) && $_[0] ) {
878 my $termpart = shift;
880 qsearchs('cdr_termination', { acctid => $self->acctid,
881 termpart => $termpart,
887 qsearch('cdr_termination', { acctid => $self->acctid, } );
895 Parses the calldate in SQL string format and returns a UNIX timestamp.
900 str2time(shift->calldate);
905 Parses the startdate in UNIX timestamp format and returns a string in SQL
911 my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
914 "$year-$mon-$mday $hour:$min:$sec";
919 Returns the FS::cdr_carrier object associated with this CDR, or false if no
920 carrierid is defined.
924 my %carrier_cache = ();
928 return '' unless $self->carrierid;
929 $carrier_cache{$self->carrierid} ||=
930 qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
935 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
936 no FS::cdr_carrier object is assocated with this CDR.
942 my $cdr_carrier = $self->cdr_carrier;
943 $cdr_carrier ? $cdr_carrier->carriername : '';
948 Returns the FS::cdr_calltype object associated with this CDR, or false if no
949 calltypenum is defined.
953 my %calltype_cache = ();
957 return '' unless $self->calltypenum;
958 $calltype_cache{$self->calltypenum} ||=
959 qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
964 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
965 no FS::cdr_calltype object is assocated with this CDR.
971 my $cdr_calltype = $self->cdr_calltype;
972 $cdr_calltype ? $cdr_calltype->calltypename : '';
975 =item downstream_csv [ OPTION => VALUE, ... ]
982 'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
985 'name' => 'Simple with source',
986 'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
987 #"Date,Time,Name,Called From,Destination,Duration,Price",
991 'invoice_header' => "Date/Time,Called Number,Min/Sec,Price",
995 'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
997 'source_default' => {
998 'name' => 'Default with source',
999 'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
1001 'accountcode_default' => {
1002 'name' => 'Default plus accountcode',
1003 'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
1005 'description_default' => {
1006 'name' => 'Default with description field as destination',
1007 'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
1010 'name' => 'Summary (one line per service, with duration)',
1011 'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
1014 'name' => 'Summary (one line per service, with count)',
1015 'invoice_header' => 'Caller,Rate,Messages,Price',
1019 my %export_formats = ();
1020 sub export_formats {
1023 return %export_formats if keys %export_formats;
1025 my $conf = new FS::Conf;
1026 my $date_format = $conf->config('date_format') || '%m/%d/%Y';
1028 # call duration in the largest units that accurately reflect the granularity
1029 my $duration_sub = sub {
1030 my($cdr, %opt) = @_;
1031 my $sec = $opt{seconds} || $cdr->billsec;
1032 if ( defined $opt{granularity} &&
1033 $opt{granularity} == 0 ) { #per call
1036 elsif ( defined $opt{granularity} && $opt{granularity} == 60 ) {#full minutes
1037 my $min = int($sec/60);
1041 else { #anything else
1042 return sprintf("%dm %ds", $sec/60, $sec%60);
1046 my $price_sub = sub {
1047 my ($cdr, %opt) = @_;
1049 if ( defined($opt{charge}) ) {
1050 $price = $opt{charge};
1052 elsif ( $opt{inbound} ) {
1053 my $term = $cdr->cdr_termination(1); # 1 = inbound
1054 $price = $term->rated_price if defined $term;
1057 $price = $cdr->rated_price;
1059 length($price) ? ($opt{money_char} . $price) : '';
1064 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
1065 sub { time2str('%r', shift->calldate_unix ) }, #TIME
1067 'dst', #NUMBER_DIALED
1068 $duration_sub, #DURATION
1069 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
1073 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
1074 sub { time2str('%r', shift->calldate_unix ) }, #TIME
1077 'dst', #NUMBER_DIALED
1078 $duration_sub, #DURATION
1079 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
1083 # for summary formats, the CDR is a fictitious object containing the
1084 # total billsec and the phone number of the service
1086 sub { my($cdr, %opt) = @_; $opt{ratename} },
1087 sub { my($cdr, %opt) = @_; $opt{count} },
1088 sub { my($cdr, %opt) = @_; int($opt{seconds}/60).'m' },
1093 sub { my($cdr, %opt) = @_; $opt{ratename} },
1094 sub { my($cdr, %opt) = @_; $opt{count} },
1098 sub { time2str('%d %b - %I:%M %p', shift->calldate_unix) },
1106 sub { time2str($date_format, shift->calldate_unix ) },
1107 # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
1110 sub { time2str('%r', shift->calldate_unix ) },
1111 # 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
1114 sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
1116 #REGIONNAME ("Destination")
1117 sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
1126 $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
1127 $export_formats{'accountcode_default'} =
1128 [ @{ $export_formats{'default'} }[0,1],
1130 @{ $export_formats{'default'} }[2..5],
1132 my @default = @{ $export_formats{'default'} };
1133 $export_formats{'description_default'} =
1134 [ 'src', @default[0..2],
1135 sub { my($cdr, %opt) = @_; $cdr->description },
1138 return %export_formats;
1141 =item downstream_csv OPTION => VALUE ...
1143 Returns a string of formatted call details for display on an invoice.
1149 charge - override the 'rated_price' field of the CDR
1151 seconds - override the 'billsec' field of the CDR
1153 count - number of usage events included in this record, for summary formats
1155 ratename - name of the rate table used to rate this call
1161 sub downstream_csv {
1162 my( $self, %opt ) = @_;
1164 my $format = $opt{'format'};
1165 my %formats = $self->export_formats;
1166 return "Unknown format $format" unless exists $formats{$format};
1168 #my $conf = new FS::Conf;
1169 #$opt{'money_char'} ||= $conf->config('money_char') || '$';
1170 $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
1172 eval "use Text::CSV_XS;";
1174 my $csv = new Text::CSV_XS;
1178 ref($_) ? &{$_}($self, %opt) : $self->$_();
1180 @{ $formats{$format} };
1182 return @columns if defined $opt{'keeparray'};
1184 my $status = $csv->combine(@columns);
1185 die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
1194 =head1 CLASS METHODS
1198 =item invoice_formats
1200 Returns an ordered list of key value pairs containing invoice format names
1201 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
1205 sub invoice_formats {
1206 map { ($_ => $export_names{$_}->{'name'}) }
1207 grep { $export_names{$_}->{'invoice_header'} }
1211 =item invoice_header FORMAT
1213 Returns a scalar containing the CSV column header for invoice format FORMAT.
1217 sub invoice_header {
1219 $export_names{$format}->{'invoice_header'};
1224 Clears cdr and any associated cdr_termination statuses - used for
1232 local $SIG{HUP} = 'IGNORE';
1233 local $SIG{INT} = 'IGNORE';
1234 local $SIG{QUIT} = 'IGNORE';
1235 local $SIG{TERM} = 'IGNORE';
1236 local $SIG{TSTP} = 'IGNORE';
1237 local $SIG{PIPE} = 'IGNORE';
1239 my $oldAutoCommit = $FS::UID::AutoCommit;
1240 local $FS::UID::AutoCommit = 0;
1243 $self->freesidestatus('');
1244 my $error = $self->replace;
1246 $dbh->rollback if $oldAutoCommit;
1250 foreach my $cdr_termination ( $self->cdr_termination ) {
1251 #$cdr_termination->status('');
1252 #$error = $cdr_termination->replace;
1253 $error = $cdr_termination->delete;
1255 $dbh->rollback if $oldAutoCommit;
1260 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1265 =item import_formats
1267 Returns an ordered list of key value pairs containing import format names
1268 as keys (for use with batch_import) and "pretty" format names as values.
1272 #false laziness w/part_pkg & part_export
1275 foreach my $INC ( @INC ) {
1276 warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
1277 foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
1278 warn "attempting to load CDR format info from $file\n" if $DEBUG;
1279 $file =~ /\/(\w+)\.pm$/ or do {
1280 warn "unrecognized file in $INC/FS/cdr/: $file\n";
1284 my $info = eval "use FS::cdr::$mod; ".
1285 "\\%FS::cdr::$mod\::info;";
1287 die "error using FS::cdr::$mod (skipping): $@\n" if $@;
1290 unless ( keys %$info ) {
1291 warn "no %info hash found in FS::cdr::$mod, skipping\n";
1294 warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
1295 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1296 warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
1299 $cdr_info{$mod} = $info;
1303 tie my %import_formats, 'Tie::IxHash',
1304 map { $_ => $cdr_info{$_}->{'name'} }
1305 sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
1306 grep { exists($cdr_info{$_}->{'import_fields'}) }
1309 sub import_formats {
1313 sub _cdr_min_parser_maker {
1315 my @fields = ref($field) ? @$field : ($field);
1316 @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
1318 my( $cdr, $min ) = @_;
1319 my $sec = eval { _cdr_min_parse($min) };
1320 die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
1321 $cdr->$_($sec) foreach @fields;
1325 sub _cdr_min_parse {
1327 sprintf('%.0f', $min * 60 );
1330 sub _cdr_date_parser_maker {
1333 my @fields = ref($field) ? @$field : ($field);
1335 my( $cdr, $datestring ) = @_;
1336 my $unixdate = eval { _cdr_date_parse($datestring, %options) };
1337 die "error parsing date for @fields from $datestring: $@\n" if $@;
1338 $cdr->$_($unixdate) foreach @fields;
1342 sub _cdr_date_parse {
1346 return '' unless length($date); #that's okay, it becomes NULL
1347 return '' if $date eq 'NA'; #sansay
1349 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 ) {
1350 my $time = str2time($date);
1351 return $time if $time > 100000; #just in case
1354 my($year, $mon, $day, $hour, $min, $sec);
1356 #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
1357 #taqua #2007-10-31 08:57:24.113000000
1359 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|$)/ ) {
1360 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1361 } 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|$)/ ) {
1362 # 8/26/2010 12:20:01
1363 # optionally without seconds
1364 ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1365 $sec = 0 if !defined($sec);
1366 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
1367 # broadsoft: 20081223201938.314
1368 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1369 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\d+(\D|$)/ ) {
1370 # Taqua OM: 20050422203450943
1371 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1372 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/ ) {
1373 # WIP: 20100329121420
1374 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1375 } elsif ( $date =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/) {
1377 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1380 die "unparsable date: $date"; #maybe we shouldn't die...
1383 return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
1384 && $hour == 0 && $min == 0 && $sec == 0;
1386 if ($options{gmt}) {
1387 timegm($sec, $min, $hour, $day, $mon-1, $year);
1389 timelocal($sec, $min, $hour, $day, $mon-1, $year);
1393 =item batch_import HASHREF
1395 Imports CDR records. Available options are:
1407 Hash reference of preset fields, typically cdrbatch
1411 Set true to prevent throwing an error on empty imports
1417 my %import_options = (
1420 'batch_keycol' => 'cdrbatchnum',
1421 'batch_table' => 'cdr_batch',
1422 'batch_namecol' => 'cdrbatch',
1424 'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
1428 #drop the || 'csv' to allow auto xls for csv types?
1429 'format_types' => { map { $_ => lc($cdr_info{$_}->{'type'} || 'csv'); }
1433 'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
1437 'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
1441 'format_fixedlength_formats' =>
1442 { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
1446 'format_xml_formats' =>
1447 { map { $_ => $cdr_info{$_}->{'xml_format'}; }
1451 'format_row_callbacks' => { map { $_ => $cdr_info{$_}->{'row_callback'}; }
1456 sub _import_options {
1463 my $iopt = _import_options;
1464 $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
1466 if ( defined $opt->{'cdrtypenum'} ) {
1467 $opt->{'preinsert_callback'} = sub {
1468 my($record,$param) = (shift,shift);
1469 $record->cdrtypenum($opt->{'cdrtypenum'});
1474 FS::Record::batch_import( $opt );
1478 =item process_batch_import
1482 sub process_batch_import {
1485 my $opt = _import_options;
1486 # $opt->{'params'} = [ 'format', 'cdrbatch' ];
1488 FS::Record::process_batch_import( $job, $opt, @_ );
1491 # if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
1492 # @columns = map { s/^ +//; $_; } @columns;
1497 # Used by FS::Upgrade to migrate to a new database.
1500 my ($class, %opts) = @_;
1502 warn "$me upgrading $class\n" if $DEBUG;
1504 my $sth = dbh->prepare(
1505 'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
1506 ) or die dbh->errstr;
1508 $sth->execute or die $sth->errstr;
1510 my %cdrbatchnum = ();
1511 while (my $row = $sth->fetchrow_arrayref) {
1513 my $cdr_batch = qsearchs( 'cdr_batch', { 'cdrbatch' => $row->[0] } );
1514 unless ( $cdr_batch ) {
1515 $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
1516 my $error = $cdr_batch->insert;
1517 die $error if $error;
1520 $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
1523 $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
1525 foreach my $cdrbatch (keys %cdrbatchnum) {
1526 $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
1537 L<FS::Record>, schema.html from the base documentation.