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 FS::UID qw( dbh );
15 use FS::Record qw( qsearch qsearchs );
20 use FS::cdr_termination;
25 @ISA = qw(FS::Record);
26 @EXPORT_OK = qw( _cdr_date_parser_maker _cdr_min_parser_maker );
31 #ask FS::UID to run this stuff for us later
32 FS::UID->install_callback( sub {
35 my @cdr_prerate_cdrtypenums;
36 $cdr_prerate = $conf->exists('cdr-prerate');
37 @cdr_prerate_cdrtypenums = $conf->config('cdr-prerate-cdrtypenums')
39 %cdr_prerate_cdrtypenums = map { $_=>1 } @cdr_prerate_cdrtypenums;
44 FS::cdr - Object methods for cdr records
50 $record = new FS::cdr \%hash;
51 $record = new FS::cdr { 'column' => 'value' };
53 $error = $record->insert;
55 $error = $new_record->replace($old_record);
57 $error = $record->delete;
59 $error = $record->check;
63 An FS::cdr object represents an Call Data Record, typically from a telephony
64 system or provider of some sort. FS::cdr inherits from FS::Record. The
65 following fields are currently supported:
69 =item acctid - primary key
71 =item calldate - Call timestamp (SQL timestamp)
73 =item clid - Caller*ID with text
75 =item src - Caller*ID number / Source number
77 =item dst - Destination extension
79 =item dcontext - Destination context
81 =item channel - Channel used
83 =item dstchannel - Destination channel if appropriate
85 =item lastapp - Last application if appropriate
87 =item lastdata - Last application data
89 =item startdate - Start of call (UNIX-style integer timestamp)
91 =item answerdate - Answer time of call (UNIX-style integer timestamp)
93 =item enddate - End time of call (UNIX-style integer timestamp)
95 =item duration - Total time in system, in seconds
97 =item billsec - Total time call is up, in seconds
99 =item disposition - What happened to the call: ANSWERED, NO ANSWER, BUSY
101 =item amaflags - What flags to use: BILL, IGNORE etc, specified on a per channel basis like accountcode.
105 #ignore the "omit" and "documentation" AMAs??
106 #AMA = Automated Message Accounting.
107 #default: Sets the system default.
108 #omit: Do not record calls.
109 #billing: Mark the entry for billing
110 #documentation: Mark the entry for documentation.
112 =item accountcode - CDR account number to use: account
114 =item uniqueid - Unique channel identifier (Unitel/RSLCOM Event ID)
116 =item userfield - CDR user-defined field
118 =item cdr_type - CDR type - see L<FS::cdr_type> (Usage = 1, S&E = 7, OC&C = 8)
120 =item charged_party - Service number to be billed
122 =item upstream_currency - Wholesale currency from upstream
124 =item upstream_price - Wholesale price from upstream
126 =item upstream_rateplanid - Upstream rate plan ID
128 =item rated_price - Rated (or re-rated) price
130 =item distance - km (need units field?)
132 =item islocal - Local - 1, Non Local = 0
134 =item calltypenum - Type of call - see L<FS::cdr_calltype>
136 =item description - Description (cdr_type 7&8 only) (used for cust_bill_pkg.itemdesc)
138 =item quantity - Number of items (cdr_type 7&8 only)
140 =item carrierid - Upstream Carrier ID (see L<FS::cdr_carrier>)
144 #Telstra =1, Optus = 2, RSL COM = 3
146 =item upstream_rateid - Upstream Rate ID
148 =item svcnum - Link to customer service (see L<FS::cust_svc>)
150 =item freesidestatus - NULL, processing-tiered, rated, done
152 =item freesiderewritestatus - NULL, done, skipped
164 Creates a new CDR. To add the CDR to the database, see L<"insert">.
166 Note that this stores the hash reference, not a distinct copy of the hash it
167 points to. You can ask the object for a copy with the I<hash> method.
171 # the new method can be inherited from FS::Record, if a table method is defined
178 #XXX fill in some (more) nice names
180 'calldate' => 'Call date',
181 'clid' => 'Caller ID',
183 'dst' => 'Destination',
184 'dcontext' => 'Dest. context',
185 'channel' => 'Channel',
186 'dstchannel' => 'Destination channel',
189 'startdate' => 'Start date',
190 'answerdate' => 'Answer date',
191 'enddate' => 'End date',
192 'duration' => 'Duration',
193 'billsec' => 'Billable seconds',
194 'disposition' => 'Disposition',
195 'amaflags' => 'AMA flags',
196 'accountcode' => 'Account code',
198 'userfield' => 'User field',
200 'charged_party' => 'Charged party',
201 #'upstream_currency' => '',
202 'upstream_price' => 'Upstream price',
203 #'upstream_rateplanid' => '',
204 #'ratedetailnum' => '',
205 'rated_price' => 'Rated price',
208 #'calltypenum' => '',
209 #'description' => '',
211 'carrierid' => 'Carrier ID',
212 #'upstream_rateid' => '',
213 'svcnum' => 'Freeside service',
214 'freesidestatus' => 'Freeside status',
215 'freesiderewritestatus' => 'Freeside rewrite status',
216 'cdrbatch' => 'Legacy batch',
217 'cdrbatchnum' => 'Batch',
226 Adds this record to the database. If there is an error, returns the error,
227 otherwise returns false.
231 # the insert method can be inherited from FS::Record
235 Delete this record from the database.
239 # the delete method can be inherited from FS::Record
241 =item replace OLD_RECORD
243 Replaces the OLD_RECORD with this one in the database. If there is an error,
244 returns the error, otherwise returns false.
248 # the replace method can be inherited from FS::Record
252 Checks all fields to make sure this is a valid CDR. If there is
253 an error, returns the error, otherwise returns false. Called by the insert
256 Note: Unlike most types of records, we don't want to "reject" a CDR and we want
257 to process them as quickly as possible, so we allow the database to check most
265 # we don't want to "reject" a CDR like other sorts of input...
267 # $self->ut_numbern('acctid')
268 ## || $self->ut_('calldate')
269 # || $self->ut_text('clid')
270 # || $self->ut_text('src')
271 # || $self->ut_text('dst')
272 # || $self->ut_text('dcontext')
273 # || $self->ut_text('channel')
274 # || $self->ut_text('dstchannel')
275 # || $self->ut_text('lastapp')
276 # || $self->ut_text('lastdata')
277 # || $self->ut_numbern('startdate')
278 # || $self->ut_numbern('answerdate')
279 # || $self->ut_numbern('enddate')
280 # || $self->ut_number('duration')
281 # || $self->ut_number('billsec')
282 # || $self->ut_text('disposition')
283 # || $self->ut_number('amaflags')
284 # || $self->ut_text('accountcode')
285 # || $self->ut_text('uniqueid')
286 # || $self->ut_text('userfield')
287 # || $self->ut_numbern('cdrtypenum')
288 # || $self->ut_textn('charged_party')
289 ## || $self->ut_n('upstream_currency')
290 ## || $self->ut_n('upstream_price')
291 # || $self->ut_numbern('upstream_rateplanid')
292 ## || $self->ut_n('distance')
293 # || $self->ut_numbern('islocal')
294 # || $self->ut_numbern('calltypenum')
295 # || $self->ut_textn('description')
296 # || $self->ut_numbern('quantity')
297 # || $self->ut_numbern('carrierid')
298 # || $self->ut_numbern('upstream_rateid')
299 # || $self->ut_numbern('svcnum')
300 # || $self->ut_textn('freesidestatus')
301 # || $self->ut_textn('freesiderewritestatus')
303 # return $error if $error;
305 for my $f ( grep { $self->$_ =~ /\D/ } qw(startdate answerdate enddate)){
306 $self->$f( str2time($self->$f) );
309 $self->calldate( $self->startdate_sql )
310 if !$self->calldate && $self->startdate;
312 #was just for $format eq 'taqua' but can't see the harm... add something to
313 #disable if it becomes a problem
314 if ( $self->duration eq '' && $self->enddate && $self->startdate ) {
315 $self->duration( $self->enddate - $self->startdate );
317 if ( $self->billsec eq '' && $self->enddate && $self->answerdate ) {
318 $self->billsec( $self->enddate - $self->answerdate );
321 $self->set_charged_party;
323 #check the foreign keys even?
324 #do we want to outright *reject* the CDR?
326 $self->ut_numbern('acctid')
328 #add a config option to turn these back on if someone needs 'em
330 # #Usage = 1, S&E = 7, OC&C = 8
331 # || $self->ut_foreign_keyn('cdrtypenum', 'cdr_type', 'cdrtypenum' )
333 # #the big list in appendix 2
334 # || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
336 # # Telstra =1, Optus = 2, RSL COM = 3
337 # || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
339 return $error if $error;
344 =item is_tollfree [ COLUMN ]
346 Returns true when the cdr represents a toll free number and false otherwise.
348 By default, inspects the dst field, but an optional column name can be passed
349 to inspect other field.
355 my $field = scalar(@_) ? shift : 'dst';
356 ( $self->$field() =~ /^(\+?1)?8(8|([02-7])\3)/ ) ? 1 : 0;
359 =item set_charged_party
361 If the charged_party field is already set, does nothing. Otherwise:
363 If the cdr-charged_party-accountcode config option is enabled, sets the
364 charged_party to the accountcode.
366 Otherwise sets the charged_party normally: to the src field in most cases,
367 or to the dst field if it is a toll free number.
371 sub set_charged_party {
374 my $conf = new FS::Conf;
376 unless ( $self->charged_party ) {
378 if ( $conf->exists('cdr-charged_party-accountcode') && $self->accountcode ){
380 my $charged_party = $self->accountcode;
381 $charged_party =~ s/^0+//
382 if $conf->exists('cdr-charged_party-accountcode-trim_leading_0s');
383 $self->charged_party( $charged_party );
385 } elsif ( $conf->exists('cdr-charged_party-field') ) {
387 my $field = $conf->config('cdr-charged_party-field');
388 $self->charged_party( $self->$field() );
392 if ( $self->is_tollfree ) {
393 $self->charged_party($self->dst);
395 $self->charged_party($self->src);
402 # my $prefix = $conf->config('cdr-charged_party-truncate_prefix');
403 # my $prefix_len = length($prefix);
404 # my $trunc_len = $conf->config('cdr-charged_party-truncate_length');
406 # $self->charged_party( substr($self->charged_party, 0, $trunc_len) )
407 # if $prefix_len && $trunc_len
408 # && substr($self->charged_party, 0, $prefix_len) eq $prefix;
412 =item set_status STATUS
414 Sets the status to the provided string. If there is an error, returns the
415 error, otherwise returns false.
420 my($self, $status) = @_;
421 $self->freesidestatus($status);
425 =item set_status_and_rated_price STATUS RATED_PRICE [ SVCNUM [ OPTION => VALUE ... ] ]
427 Sets the status and rated price.
429 Available options are: inbound, rated_seconds, rated_minutes, rated_classnum, rated_ratename
431 If there is an error, returns the error, otherwise returns false.
435 sub set_status_and_rated_price {
436 my($self, $status, $rated_price, $svcnum, %opt) = @_;
438 if ($opt{'inbound'}) {
440 my $term = $self->cdr_termination( 1 ); #1: inbound
443 warn "replacing existing cdr status (".$self->acctid.")\n" if $term;
444 $error = $term->delete;
445 return $error if $error;
447 $term = FS::cdr_termination->new({
448 acctid => $self->acctid,
450 rated_price => $rated_price,
453 $term->rated_seconds($opt{rated_seconds}) if exists($opt{rated_seconds});
454 $term->rated_minutes($opt{rated_minutes}) if exists($opt{rated_minutes});
455 $term->svcnum($svcnum) if $svcnum;
456 return $term->insert;
460 $self->freesidestatus($status);
461 $self->rated_price($rated_price);
463 foreach grep exists($opt{$_}), map "rated_$_",
464 qw( pretty_dst regionname seconds minutes granularity
465 ratedetailnum classnum ratename );
466 $self->svcnum($svcnum) if $svcnum;
467 return $self->replace();
472 =item rate [ OPTION => VALUE ... ]
474 Rates this CDR according and sets the status to 'rated'.
476 Available options are: part_pkg, svcnum, single_price_included_minutes, region_group, region_group_included_minutes.
478 part_pkg is required.
480 If svcnum is specified, will also associate this CDR with the specified svcnum.
482 single_price_included_minutes is requried for single_price price plans
483 (otherwise unused/ignored). It should be set to a scalar reference of the
484 number of included minutes and will be decremented by the rated minutes of this
487 region_group_included_minutes is required for prefix price plans which have
488 included minutes (otherwise unused/ignored). It should be set to a scalar
489 reference of the number of included minutes and will be decremented by the
490 rated minutes of this CDR.
492 region_group_included_minutes_hashref is required for prefix price plans which
493 have included minues (otehrwise unused/ignored). It should be set to an empty
494 hashref at the start of a month's rating and then preserved across CDRs.
499 my( $self, %opt ) = @_;
500 my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
503 warn "rating CDR $self\n".
504 join('', map { " $_ => ". $self->{$_}. "\n" } keys %$self );
507 my $rating_method = $part_pkg->option_cacheable('rating_method') || 'prefix';
508 my $method = "rate_$rating_method";
509 $self->$method(%opt);
513 our %interval_cache = (); # for timed rates
516 my( $self, %opt ) = @_;
517 my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
520 # this will result in those CDRs being marked as done... is that
523 if ( $part_pkg->option_cacheable('411_rewrite') ) {
524 my $dirass = $part_pkg->option_cacheable('411_rewrite');
526 @dirass = split(',', $dirass);
529 if ( length($self->dst) && grep { $self->dst eq $_ } @dirass ) {
534 my $reason = $part_pkg->check_chargable( $self,
535 'da_rewrote' => $da_rewrote,
538 warn "not charging for CDR ($reason)\n" if $DEBUG;
539 return $self->set_status_and_rated_price( 'rated',
547 # look up rate details based on called station id
548 # (or calling station id for toll free calls)
551 my( $to_or_from, $number );
552 if ( $self->is_tollfree && ! $part_pkg->option_cacheable('disable_tollfree') )
554 $to_or_from = 'from';
555 $number = $self->src;
556 } else { #regular call
558 $number = $self->dst;
561 warn "parsing call $to_or_from $number\n" if $DEBUG;
563 #remove non-phone# stuff and whitespace
566 # $dest =~ s/^(\w+):// and $proto = $1; #sip:
568 # $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
570 #determine the country code
571 my $intl = $part_pkg->option_cacheable('international_prefix') || '011';
572 my $countrycode = '';
573 if ( $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
574 || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
578 my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
579 #first look for 1 digit country code
580 if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
582 $number = $u1.$u2.$rest;
583 } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
586 } else { #3 digit country code
587 $countrycode = $three;
592 my $domestic_prefix = $part_pkg->option_cacheable('domestic_prefix');
593 $countrycode = length($domestic_prefix) ? $domestic_prefix : '1';
594 $number =~ s/^$countrycode//;# if length($number) > 10;
597 warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
598 my $pretty_dst = "+$countrycode $number";
599 #asterisks here causes inserting the detail to barf, so:
600 $pretty_dst =~ s/\*//g;
602 my $eff_ratenum = $self->is_tollfree('accountcode')
603 ? $part_pkg->option_cacheable('accountcode_tollfree_ratenum')
607 my $intrastate_ratenum = $part_pkg->option_cacheable('intrastate_ratenum');
608 if ( $intrastate_ratenum && !$self->is_tollfree ) {
609 $ratename = 'Interstate'; #until proven otherwise
610 # this is relatively easy only because:
611 # -assume all numbers are valid NANP numbers NOT in a fully-qualified format
612 # -disregard toll-free
613 # -disregard private or unknown numbers
614 # -there is exactly one record in rate_prefix for a given NPANXX
615 # -default to interstate if we can't find one or both of the prefixes
616 my $dstprefix = $self->dst;
617 $dstprefix =~ /^(\d{6})/;
618 $dstprefix = qsearchs('rate_prefix', { 'countrycode' => '1',
621 my $srcprefix = $self->src;
622 $srcprefix =~ /^(\d{6})/;
623 $srcprefix = qsearchs('rate_prefix', { 'countrycode' => '1',
626 if ($srcprefix && $dstprefix
627 && $srcprefix->state && $dstprefix->state
628 && $srcprefix->state eq $dstprefix->state) {
629 $eff_ratenum = $intrastate_ratenum;
630 $ratename = 'Intrastate'; # XXX possibly just use the ratename?
634 $eff_ratenum ||= $part_pkg->option_cacheable('ratenum');
635 my $rate = qsearchs('rate', { 'ratenum' => $eff_ratenum })
636 or die "ratenum $eff_ratenum not found!";
638 my @ltime = localtime($self->startdate);
639 my $weektime = $ltime[0] +
640 $ltime[1]*60 + #minutes
641 $ltime[2]*3600 + #hours
642 $ltime[6]*86400; #days since sunday
643 # if there's no timed rate_detail for this time/region combination,
644 # dest_detail returns the default. There may still be a timed rate
645 # that applies after the starttime of the call, so be careful...
646 my $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
647 'phonenum' => $number,
648 'weektime' => $weektime,
649 'cdrtypenum' => $self->cdrtypenum,
652 unless ( $rate_detail ) {
654 if ( $part_pkg->option_cacheable('ignore_unrateable') ) {
656 if ( $part_pkg->option_cacheable('ignore_unrateable') == 2 ) {
657 # mark the CDR as unrateable
658 return $self->set_status_and_rated_price(
663 } elsif ( $part_pkg->option_cacheable('ignore_unrateable') == 1 ) {
665 warn "no rate_detail found for CDR.acctid: ". $self->acctid.
670 die "unknown ignore_unrateable, pkgpart ". $part_pkg->pkgpart;
675 die "FATAL: no rate_detail found in ".
676 $rate->ratenum. ":". $rate->ratename. " rate plan ".
677 "for +$countrycode $number (CDR acctid ". $self->acctid. "); ".
678 "add a rate or set ignore_unrateable flag on the package def\n";
683 my $rate_region = $rate_detail->dest_region;
684 my $regionnum = $rate_region->regionnum;
685 warn " found rate for regionnum $regionnum ".
686 "and rate detail $rate_detail\n"
689 if ( !exists($interval_cache{$regionnum}) ) {
691 sort { $a->stime <=> $b->stime }
692 map { my $r = $_->rate_time; $r ? $r->intervals : () }
695 $interval_cache{$regionnum} = \@intervals;
696 warn " cached ".scalar(@intervals)." interval(s)\n"
701 # find the price and add detail to the invoice
704 # About this section:
705 # We don't round _anything_ (except granularizing)
706 # until the final $charge = sprintf("%.2f"...).
708 my $seconds_left = $part_pkg->option_cacheable('use_duration')
711 # charge for the first (conn_sec) seconds
712 my $seconds = min($seconds_left, $rate_detail->conn_sec);
713 $seconds_left -= $seconds;
714 $weektime += $seconds;
715 my $charge = $rate_detail->conn_charge;
718 while($seconds_left) {
719 my $ratetimenum = $rate_detail->ratetimenum; # may be empty
721 # find the end of the current rate interval
722 if(@{ $interval_cache{$regionnum} } == 0) {
723 # There are no timed rates in this group, so just stay
724 # in the default rate_detail for the entire duration.
725 # Set an "end" of 1 past the end of the current call.
726 $etime = $weektime + $seconds_left + 1;
728 elsif($ratetimenum) {
729 # This is a timed rate, so go to the etime of this interval.
730 # If it's followed by another timed rate, the stime of that
731 # interval should match the etime of this one.
732 my $interval = $rate_detail->rate_time->contains($weektime);
733 $etime = $interval->etime;
736 # This is a default rate, so use the stime of the next
737 # interval in the sequence.
738 my $next_int = first { $_->stime > $weektime }
739 @{ $interval_cache{$regionnum} };
741 $etime = $next_int->stime;
744 # weektime is near the end of the week, so decrement
745 # it by a full week and use the stime of the first
747 $weektime -= (3600*24*7);
748 $etime = $interval_cache{$regionnum}->[0]->stime;
752 my $charge_sec = min($seconds_left, $etime - $weektime);
754 $seconds_left -= $charge_sec;
756 my $included_min = $opt{'region_group_included_min_hashref'} || {};
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 my $region_group = ($part_pkg->option_cacheable('min_included') || 0) > 0;
780 ${$opt{region_group_included_min}} -= $minutes
781 if $region_group && $rate_detail->region_group;
783 $included_min->{$regionnum}{$ratetimenum} -= $minutes;
785 $included_min->{$regionnum}{$ratetimenum} <= 0
786 && ( ${$opt{region_group_included_min}} <= 0
787 || ! $rate_detail->region_group
791 #should preserve (display?) this
792 my $charge_min = 0 - $included_min->{$regionnum}{$ratetimenum};
793 $included_min->{$regionnum}{$ratetimenum} = 0;
794 $charge += ($rate_detail->min_charge * $charge_min); #still not rounded
796 } elsif ( ${$opt{region_group_included_min}} > 0
798 && $rate_detail->region_group
801 $included_min->{$regionnum}{$ratetimenum} = 0
804 # choose next rate_detail
805 $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
806 'phonenum' => $number,
807 'weektime' => $etime,
808 'cdrtypenum' => $self->cdrtypenum })
810 # we have now moved forward to $etime
813 } #while $seconds_left
815 # this is why we need regionnum/rate_region....
816 warn " (rate region $rate_region)\n" if $DEBUG;
818 $self->set_status_and_rated_price(
820 sprintf('%.2f', $charge + 0.000001), # NOW round it.
822 'rated_pretty_dst' => $pretty_dst,
823 'rated_regionname' => $rate_region->regionname,
824 'rated_seconds' => $seconds,
825 'rated_granularity' => $rate_detail->sec_granularity, #$granularity
826 'rated_ratedetailnum' => $rate_detail->ratedetailnum,
827 'rated_classnum' => $rate_detail->classnum, #rated_ratedetailnum?
828 'rated_ratename' => $ratename, #not rate_detail - Intrastate/Interstate
833 sub rate_upstream_simple {
834 my( $self, %opt ) = @_;
836 $self->set_status_and_rated_price( 'rated',
837 sprintf('%.3f', $self->upstream_price),
842 sub rate_single_price {
843 my( $self, %opt ) = @_;
844 my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
846 # a little false laziness w/abov
847 # $rate_detail = new FS::rate_detail({sec_granularity => ... }) ?
849 my $granularity = length($part_pkg->option_cacheable('sec_granularity'))
850 ? $part_pkg->option_cacheable('sec_granularity')
853 my $seconds = $part_pkg->option_cacheable('use_duration')
857 $seconds += $granularity - ( $seconds % $granularity )
858 if $seconds # don't granular-ize 0 billsec calls (bills them)
859 && $granularity # 0 is per call
860 && $seconds % $granularity;
861 my $minutes = $granularity ? ($seconds / 60) : 1;
863 my $charge_min = $minutes;
865 ${$opt{single_price_included_min}} -= $minutes;
866 if ( ${$opt{single_price_included_min}} > 0 ) {
869 $charge_min = 0 - ${$opt{single_price_included_min}};
870 ${$opt{single_price_included_min}} = 0;
874 sprintf('%.4f', ( $part_pkg->option_cacheable('min_charge') * $charge_min )
875 + 0.0000000001 ); #so 1.00005 rounds to 1.0001
877 $self->set_status_and_rated_price( 'rated',
884 =item cdr_termination [ TERMPART ]
888 sub cdr_termination {
891 if ( scalar(@_) && $_[0] ) {
892 my $termpart = shift;
894 qsearchs('cdr_termination', { acctid => $self->acctid,
895 termpart => $termpart,
901 qsearch('cdr_termination', { acctid => $self->acctid, } );
909 Parses the calldate in SQL string format and returns a UNIX timestamp.
914 str2time(shift->calldate);
919 Parses the startdate in UNIX timestamp format and returns a string in SQL
925 my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
928 "$year-$mon-$mday $hour:$min:$sec";
933 Returns the FS::cdr_carrier object associated with this CDR, or false if no
934 carrierid is defined.
938 my %carrier_cache = ();
942 return '' unless $self->carrierid;
943 $carrier_cache{$self->carrierid} ||=
944 qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
949 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
950 no FS::cdr_carrier object is assocated with this CDR.
956 my $cdr_carrier = $self->cdr_carrier;
957 $cdr_carrier ? $cdr_carrier->carriername : '';
962 Returns the FS::cdr_calltype object associated with this CDR, or false if no
963 calltypenum is defined.
967 my %calltype_cache = ();
971 return '' unless $self->calltypenum;
972 $calltype_cache{$self->calltypenum} ||=
973 qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
978 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
979 no FS::cdr_calltype object is assocated with this CDR.
985 my $cdr_calltype = $self->cdr_calltype;
986 $cdr_calltype ? $cdr_calltype->calltypename : '';
989 =item downstream_csv [ OPTION => VALUE, ... ]
996 'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
999 'name' => 'Simple with source',
1000 'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
1001 #"Date,Time,Name,Called From,Destination,Duration,Price",
1005 'invoice_header' => "Date/Time,Called Number,Min/Sec,Price",
1008 'name' => 'Default',
1009 'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
1011 'source_default' => {
1012 'name' => 'Default with source',
1013 'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
1015 'accountcode_default' => {
1016 'name' => 'Default plus accountcode',
1017 'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
1019 'description_default' => {
1020 'name' => 'Default with description field as destination',
1021 'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
1024 'name' => 'Summary (one line per service, with duration)',
1025 'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
1028 'name' => 'Summary (one line per service, with count)',
1029 'invoice_header' => 'Caller,Rate,Messages,Price',
1033 my %export_formats = ();
1034 sub export_formats {
1037 return %export_formats if keys %export_formats;
1039 my $conf = new FS::Conf;
1040 my $date_format = $conf->config('date_format') || '%m/%d/%Y';
1042 # call duration in the largest units that accurately reflect the granularity
1043 my $duration_sub = sub {
1044 my($cdr, %opt) = @_;
1045 my $sec = $opt{seconds} || $cdr->billsec;
1046 if ( defined $opt{granularity} &&
1047 $opt{granularity} == 0 ) { #per call
1050 elsif ( defined $opt{granularity} && $opt{granularity} == 60 ) {#full minutes
1051 my $min = int($sec/60);
1055 else { #anything else
1056 return sprintf("%dm %ds", $sec/60, $sec%60);
1060 my $price_sub = sub {
1061 my ($cdr, %opt) = @_;
1063 if ( defined($opt{charge}) ) {
1064 $price = $opt{charge};
1066 elsif ( $opt{inbound} ) {
1067 my $term = $cdr->cdr_termination(1); # 1 = inbound
1068 $price = $term->rated_price if defined $term;
1071 $price = $cdr->rated_price;
1073 length($price) ? ($opt{money_char} . $price) : '';
1078 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
1079 sub { time2str('%r', shift->calldate_unix ) }, #TIME
1081 'dst', #NUMBER_DIALED
1082 $duration_sub, #DURATION
1083 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
1087 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
1088 sub { time2str('%r', shift->calldate_unix ) }, #TIME
1091 'dst', #NUMBER_DIALED
1092 $duration_sub, #DURATION
1093 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
1097 # for summary formats, the CDR is a fictitious object containing the
1098 # total billsec and the phone number of the service
1100 sub { my($cdr, %opt) = @_; $opt{ratename} },
1101 sub { my($cdr, %opt) = @_; $opt{count} },
1102 sub { my($cdr, %opt) = @_; int($opt{seconds}/60).'m' },
1107 sub { my($cdr, %opt) = @_; $opt{ratename} },
1108 sub { my($cdr, %opt) = @_; $opt{count} },
1112 sub { time2str('%d %b - %I:%M %p', shift->calldate_unix) },
1120 sub { time2str($date_format, shift->calldate_unix ) },
1121 # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
1124 sub { time2str('%r', shift->calldate_unix ) },
1125 # 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
1128 sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
1130 #REGIONNAME ("Destination")
1131 sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
1140 $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
1141 $export_formats{'accountcode_default'} =
1142 [ @{ $export_formats{'default'} }[0,1],
1144 @{ $export_formats{'default'} }[2..5],
1146 my @default = @{ $export_formats{'default'} };
1147 $export_formats{'description_default'} =
1148 [ 'src', @default[0..2],
1149 sub { my($cdr, %opt) = @_; $cdr->description },
1152 return %export_formats;
1155 =item downstream_csv OPTION => VALUE ...
1157 Returns a string of formatted call details for display on an invoice.
1163 charge - override the 'rated_price' field of the CDR
1165 seconds - override the 'billsec' field of the CDR
1167 count - number of usage events included in this record, for summary formats
1169 ratename - name of the rate table used to rate this call
1175 sub downstream_csv {
1176 my( $self, %opt ) = @_;
1178 my $format = $opt{'format'};
1179 my %formats = $self->export_formats;
1180 return "Unknown format $format" unless exists $formats{$format};
1182 #my $conf = new FS::Conf;
1183 #$opt{'money_char'} ||= $conf->config('money_char') || '$';
1184 $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
1186 eval "use Text::CSV_XS;";
1188 my $csv = new Text::CSV_XS;
1192 ref($_) ? &{$_}($self, %opt) : $self->$_();
1194 @{ $formats{$format} };
1196 return @columns if defined $opt{'keeparray'};
1198 my $status = $csv->combine(@columns);
1199 die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
1208 =head1 CLASS METHODS
1212 =item invoice_formats
1214 Returns an ordered list of key value pairs containing invoice format names
1215 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
1219 sub invoice_formats {
1220 map { ($_ => $export_names{$_}->{'name'}) }
1221 grep { $export_names{$_}->{'invoice_header'} }
1225 =item invoice_header FORMAT
1227 Returns a scalar containing the CSV column header for invoice format FORMAT.
1231 sub invoice_header {
1233 $export_names{$format}->{'invoice_header'};
1238 Clears cdr and any associated cdr_termination statuses - used for
1246 local $SIG{HUP} = 'IGNORE';
1247 local $SIG{INT} = 'IGNORE';
1248 local $SIG{QUIT} = 'IGNORE';
1249 local $SIG{TERM} = 'IGNORE';
1250 local $SIG{TSTP} = 'IGNORE';
1251 local $SIG{PIPE} = 'IGNORE';
1253 my $oldAutoCommit = $FS::UID::AutoCommit;
1254 local $FS::UID::AutoCommit = 0;
1257 if ( $cdr_prerate && $cdr_prerate_cdrtypenums{$self->cdrtypenum}
1258 && $self->rated_ratedetailnum #avoid putting old CDRs back in "rated"
1259 && $self->freesidestatus eq 'done'
1262 $self->freesidestatus('rated');
1264 $self->freesidestatus('');
1267 my $error = $self->replace;
1269 $dbh->rollback if $oldAutoCommit;
1273 foreach my $cdr_termination ( $self->cdr_termination ) {
1274 #$cdr_termination->status('');
1275 #$error = $cdr_termination->replace;
1276 $error = $cdr_termination->delete;
1278 $dbh->rollback if $oldAutoCommit;
1283 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1288 =item import_formats
1290 Returns an ordered list of key value pairs containing import format names
1291 as keys (for use with batch_import) and "pretty" format names as values.
1295 #false laziness w/part_pkg & part_export
1298 foreach my $INC ( @INC ) {
1299 warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
1300 foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
1301 warn "attempting to load CDR format info from $file\n" if $DEBUG;
1302 $file =~ /\/(\w+)\.pm$/ or do {
1303 warn "unrecognized file in $INC/FS/cdr/: $file\n";
1307 my $info = eval "use FS::cdr::$mod; ".
1308 "\\%FS::cdr::$mod\::info;";
1310 die "error using FS::cdr::$mod (skipping): $@\n" if $@;
1313 unless ( keys %$info ) {
1314 warn "no %info hash found in FS::cdr::$mod, skipping\n";
1317 warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
1318 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1319 warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
1322 $cdr_info{$mod} = $info;
1326 tie my %import_formats, 'Tie::IxHash',
1327 map { $_ => $cdr_info{$_}->{'name'} }
1328 sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
1329 grep { exists($cdr_info{$_}->{'import_fields'}) }
1332 sub import_formats {
1336 sub _cdr_min_parser_maker {
1338 my @fields = ref($field) ? @$field : ($field);
1339 @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
1341 my( $cdr, $min ) = @_;
1342 my $sec = eval { _cdr_min_parse($min) };
1343 die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
1344 $cdr->$_($sec) foreach @fields;
1348 sub _cdr_min_parse {
1350 sprintf('%.0f', $min * 60 );
1353 sub _cdr_date_parser_maker {
1356 my @fields = ref($field) ? @$field : ($field);
1358 my( $cdr, $datestring ) = @_;
1359 my $unixdate = eval { _cdr_date_parse($datestring, %options) };
1360 die "error parsing date for @fields from $datestring: $@\n" if $@;
1361 $cdr->$_($unixdate) foreach @fields;
1365 sub _cdr_date_parse {
1369 return '' unless length($date); #that's okay, it becomes NULL
1370 return '' if $date eq 'NA'; #sansay
1372 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 ) {
1373 my $time = str2time($date);
1374 return $time if $time > 100000; #just in case
1377 my($year, $mon, $day, $hour, $min, $sec);
1379 #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
1380 #taqua #2007-10-31 08:57:24.113000000
1382 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|$)/ ) {
1383 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1384 } 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|$)/ ) {
1385 # 8/26/2010 12:20:01
1386 # optionally without seconds
1387 ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1388 $sec = 0 if !defined($sec);
1389 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
1390 # broadsoft: 20081223201938.314
1391 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1392 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\d+(\D|$)/ ) {
1393 # Taqua OM: 20050422203450943
1394 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1395 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/ ) {
1396 # WIP: 20100329121420
1397 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1398 } elsif ( $date =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/) {
1400 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1403 die "unparsable date: $date"; #maybe we shouldn't die...
1406 return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
1407 && $hour == 0 && $min == 0 && $sec == 0;
1409 if ($options{gmt}) {
1410 timegm($sec, $min, $hour, $day, $mon-1, $year);
1412 timelocal($sec, $min, $hour, $day, $mon-1, $year);
1416 =item batch_import HASHREF
1418 Imports CDR records. Available options are:
1430 Hash reference of preset fields, typically cdrbatch
1434 Set true to prevent throwing an error on empty imports
1440 my %import_options = (
1443 'batch_keycol' => 'cdrbatchnum',
1444 'batch_table' => 'cdr_batch',
1445 'batch_namecol' => 'cdrbatch',
1447 'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
1451 #drop the || 'csv' to allow auto xls for csv types?
1452 'format_types' => { map { $_ => lc($cdr_info{$_}->{'type'} || 'csv'); }
1456 'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
1460 'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
1464 'format_fixedlength_formats' =>
1465 { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
1469 'format_xml_formats' =>
1470 { map { $_ => $cdr_info{$_}->{'xml_format'}; }
1474 'format_row_callbacks' => { map { $_ => $cdr_info{$_}->{'row_callback'}; }
1479 sub _import_options {
1486 my $iopt = _import_options;
1487 $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
1489 if ( defined $opt->{'cdrtypenum'} ) {
1490 $opt->{'preinsert_callback'} = sub {
1491 my($record,$param) = (shift,shift);
1492 $record->cdrtypenum($opt->{'cdrtypenum'});
1497 FS::Record::batch_import( $opt );
1501 =item process_batch_import
1505 sub process_batch_import {
1508 my $opt = _import_options;
1509 # $opt->{'params'} = [ 'format', 'cdrbatch' ];
1511 FS::Record::process_batch_import( $job, $opt, @_ );
1514 # if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
1515 # @columns = map { s/^ +//; $_; } @columns;
1520 # Used by FS::Upgrade to migrate to a new database.
1523 my ($class, %opts) = @_;
1525 warn "$me upgrading $class\n" if $DEBUG;
1527 my $sth = dbh->prepare(
1528 'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
1529 ) or die dbh->errstr;
1531 $sth->execute or die $sth->errstr;
1533 my %cdrbatchnum = ();
1534 while (my $row = $sth->fetchrow_arrayref) {
1536 my $cdr_batch = qsearchs( 'cdr_batch', { 'cdrbatch' => $row->[0] } );
1537 unless ( $cdr_batch ) {
1538 $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
1539 my $error = $cdr_batch->insert;
1540 die $error if $error;
1543 $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
1546 $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
1548 foreach my $cdrbatch (keys %cdrbatchnum) {
1549 $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
1560 L<FS::Record>, schema.html from the base documentation.