4 use vars qw( @ISA @EXPORT_OK $DEBUG $me );
10 use FS::UID qw( dbh );
12 use FS::Record qw( qsearch qsearchs );
18 @ISA = qw(FS::Record);
19 @EXPORT_OK = qw( _cdr_date_parser_maker _cdr_min_parser_maker );
26 FS::cdr - Object methods for cdr records
32 $record = new FS::cdr \%hash;
33 $record = new FS::cdr { 'column' => 'value' };
35 $error = $record->insert;
37 $error = $new_record->replace($old_record);
39 $error = $record->delete;
41 $error = $record->check;
45 An FS::cdr object represents an Call Data Record, typically from a telephony
46 system or provider of some sort. FS::cdr inherits from FS::Record. The
47 following fields are currently supported:
51 =item acctid - primary key
53 =item calldate - Call timestamp (SQL timestamp)
55 =item clid - Caller*ID with text
57 =item src - Caller*ID number / Source number
59 =item dst - Destination extension
61 =item dcontext - Destination context
63 =item channel - Channel used
65 =item dstchannel - Destination channel if appropriate
67 =item lastapp - Last application if appropriate
69 =item lastdata - Last application data
71 =item startdate - Start of call (UNIX-style integer timestamp)
73 =item answerdate - Answer time of call (UNIX-style integer timestamp)
75 =item enddate - End time of call (UNIX-style integer timestamp)
77 =item duration - Total time in system, in seconds
79 =item billsec - Total time call is up, in seconds
81 =item disposition - What happened to the call: ANSWERED, NO ANSWER, BUSY
83 =item amaflags - What flags to use: BILL, IGNORE etc, specified on a per channel basis like accountcode.
87 #ignore the "omit" and "documentation" AMAs??
88 #AMA = Automated Message Accounting.
89 #default: Sets the system default.
90 #omit: Do not record calls.
91 #billing: Mark the entry for billing
92 #documentation: Mark the entry for documentation.
94 =item accountcode - CDR account number to use: account
96 =item uniqueid - Unique channel identifier (Unitel/RSLCOM Event ID)
98 =item userfield - CDR user-defined field
100 =item cdr_type - CDR type - see L<FS::cdr_type> (Usage = 1, S&E = 7, OC&C = 8)
102 =item charged_party - Service number to be billed
104 =item upstream_currency - Wholesale currency from upstream
106 =item upstream_price - Wholesale price from upstream
108 =item upstream_rateplanid - Upstream rate plan ID
110 =item rated_price - Rated (or re-rated) price
112 =item distance - km (need units field?)
114 =item islocal - Local - 1, Non Local = 0
116 =item calltypenum - Type of call - see L<FS::cdr_calltype>
118 =item description - Description (cdr_type 7&8 only) (used for cust_bill_pkg.itemdesc)
120 =item quantity - Number of items (cdr_type 7&8 only)
122 =item carrierid - Upstream Carrier ID (see L<FS::cdr_carrier>)
126 #Telstra =1, Optus = 2, RSL COM = 3
128 =item upstream_rateid - Upstream Rate ID
130 =item svcnum - Link to customer service (see L<FS::cust_svc>)
132 =item freesidestatus - NULL, done (or something)
134 =item freesiderewritestatus - NULL, done (or something)
146 Creates a new CDR. To add the CDR to the database, see L<"insert">.
148 Note that this stores the hash reference, not a distinct copy of the hash it
149 points to. You can ask the object for a copy with the I<hash> method.
153 # the new method can be inherited from FS::Record, if a table method is defined
160 #XXX fill in some (more) nice names
162 'calldate' => 'Call date',
163 'clid' => 'Caller ID',
165 'dst' => 'Destination',
166 'dcontext' => 'Dest. context',
167 'channel' => 'Channel',
168 'dstchannel' => 'Destination channel',
171 'startdate' => 'Start date',
172 'answerdate' => 'Answer date',
173 'enddate' => 'End date',
174 'duration' => 'Duration',
175 'billsec' => 'Billable seconds',
176 'disposition' => 'Disposition',
177 'amaflags' => 'AMA flags',
178 'accountcode' => 'Account code',
180 'userfield' => 'User field',
182 'charged_party' => 'Charged party',
183 #'upstream_currency' => '',
184 'upstream_price' => 'Upstream price',
185 #'upstream_rateplanid' => '',
186 #'ratedetailnum' => '',
187 'rated_price' => 'Rated price',
190 #'calltypenum' => '',
191 #'description' => '',
193 'carrierid' => 'Carrier ID',
194 #'upstream_rateid' => '',
195 'svcnum' => 'Freeside service',
196 'freesidestatus' => 'Freeside status',
197 'freesiderewritestatus' => 'Freeside rewrite status',
198 'cdrbatch' => 'Legacy batch',
199 'cdrbatchnum' => 'Batch',
208 Adds this record to the database. If there is an error, returns the error,
209 otherwise returns false.
213 # the insert method can be inherited from FS::Record
217 Delete this record from the database.
221 # the delete method can be inherited from FS::Record
223 =item replace OLD_RECORD
225 Replaces the OLD_RECORD with this one in the database. If there is an error,
226 returns the error, otherwise returns false.
230 # the replace method can be inherited from FS::Record
234 Checks all fields to make sure this is a valid CDR. If there is
235 an error, returns the error, otherwise returns false. Called by the insert
238 Note: Unlike most types of records, we don't want to "reject" a CDR and we want
239 to process them as quickly as possible, so we allow the database to check most
247 # we don't want to "reject" a CDR like other sorts of input...
249 # $self->ut_numbern('acctid')
250 ## || $self->ut_('calldate')
251 # || $self->ut_text('clid')
252 # || $self->ut_text('src')
253 # || $self->ut_text('dst')
254 # || $self->ut_text('dcontext')
255 # || $self->ut_text('channel')
256 # || $self->ut_text('dstchannel')
257 # || $self->ut_text('lastapp')
258 # || $self->ut_text('lastdata')
259 # || $self->ut_numbern('startdate')
260 # || $self->ut_numbern('answerdate')
261 # || $self->ut_numbern('enddate')
262 # || $self->ut_number('duration')
263 # || $self->ut_number('billsec')
264 # || $self->ut_text('disposition')
265 # || $self->ut_number('amaflags')
266 # || $self->ut_text('accountcode')
267 # || $self->ut_text('uniqueid')
268 # || $self->ut_text('userfield')
269 # || $self->ut_numbern('cdrtypenum')
270 # || $self->ut_textn('charged_party')
271 ## || $self->ut_n('upstream_currency')
272 ## || $self->ut_n('upstream_price')
273 # || $self->ut_numbern('upstream_rateplanid')
274 ## || $self->ut_n('distance')
275 # || $self->ut_numbern('islocal')
276 # || $self->ut_numbern('calltypenum')
277 # || $self->ut_textn('description')
278 # || $self->ut_numbern('quantity')
279 # || $self->ut_numbern('carrierid')
280 # || $self->ut_numbern('upstream_rateid')
281 # || $self->ut_numbern('svcnum')
282 # || $self->ut_textn('freesidestatus')
283 # || $self->ut_textn('freesiderewritestatus')
285 # return $error if $error;
287 $self->calldate( $self->startdate_sql )
288 if !$self->calldate && $self->startdate;
290 #was just for $format eq 'taqua' but can't see the harm... add something to
291 #disable if it becomes a problem
292 if ( $self->duration eq '' && $self->enddate && $self->startdate ) {
293 $self->duration( $self->enddate - $self->startdate );
295 if ( $self->billsec eq '' && $self->enddate && $self->answerdate ) {
296 $self->billsec( $self->enddate - $self->answerdate );
299 $self->set_charged_party;
301 #check the foreign keys even?
302 #do we want to outright *reject* the CDR?
304 $self->ut_numbern('acctid')
306 #add a config option to turn these back on if someone needs 'em
308 # #Usage = 1, S&E = 7, OC&C = 8
309 # || $self->ut_foreign_keyn('cdrtypenum', 'cdr_type', 'cdrtypenum' )
311 # #the big list in appendix 2
312 # || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
314 # # Telstra =1, Optus = 2, RSL COM = 3
315 # || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
317 return $error if $error;
324 Returns true when the cdr represents a toll free number and false otherwise.
330 ( $self->dst =~ /^(\+?1)?8(8|([02-7])\3)/ ) ? 1 : 0;
333 =item set_charged_party
335 If the charged_party field is already set, does nothing. Otherwise:
337 If the cdr-charged_party-accountcode config option is enabled, sets the
338 charged_party to the accountcode.
340 Otherwise sets the charged_party normally: to the src field in most cases,
341 or to the dst field if it is a toll free number.
345 sub set_charged_party {
348 my $conf = new FS::Conf;
350 unless ( $self->charged_party ) {
352 if ( $conf->exists('cdr-charged_party-accountcode') && $self->accountcode ){
354 my $charged_party = $self->accountcode;
355 $charged_party =~ s/^0+//
356 if $conf->exists('cdr-charged_party-accountcode-trim_leading_0s');
357 $self->charged_party( $charged_party );
361 if ( $self->is_tollfree ) {
362 $self->charged_party($self->dst);
364 $self->charged_party($self->src);
371 # my $prefix = $conf->config('cdr-charged_party-truncate_prefix');
372 # my $prefix_len = length($prefix);
373 # my $trunc_len = $conf->config('cdr-charged_party-truncate_length');
375 # $self->charged_party( substr($self->charged_party, 0, $trunc_len) )
376 # if $prefix_len && $trunc_len
377 # && substr($self->charged_party, 0, $prefix_len) eq $prefix;
381 =item set_status_and_rated_price STATUS [ RATED_PRICE [ SVCNUM ] ]
383 Sets the status to the provided string. If there is an error, returns the
384 error, otherwise returns false.
388 sub set_status_and_rated_price {
389 my($self, $status, $rated_price, $svcnum) = @_;
390 $self->freesidestatus($status);
391 $self->rated_price($rated_price);
392 $self->svcnum($svcnum) if $svcnum;
398 Parses the calldate in SQL string format and returns a UNIX timestamp.
403 str2time(shift->calldate);
408 Parses the startdate in UNIX timestamp format and returns a string in SQL
414 my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
417 "$year-$mon-$mday $hour:$min:$sec";
422 Returns the FS::cdr_carrier object associated with this CDR, or false if no
423 carrierid is defined.
427 my %carrier_cache = ();
431 return '' unless $self->carrierid;
432 $carrier_cache{$self->carrierid} ||=
433 qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
438 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
439 no FS::cdr_carrier object is assocated with this CDR.
445 my $cdr_carrier = $self->cdr_carrier;
446 $cdr_carrier ? $cdr_carrier->carriername : '';
451 Returns the FS::cdr_calltype object associated with this CDR, or false if no
452 calltypenum is defined.
456 my %calltype_cache = ();
460 return '' unless $self->calltypenum;
461 $calltype_cache{$self->calltypenum} ||=
462 qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
467 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
468 no FS::cdr_calltype object is assocated with this CDR.
474 my $cdr_calltype = $self->cdr_calltype;
475 $cdr_calltype ? $cdr_calltype->calltypename : '';
478 =item downstream_csv [ OPTION => VALUE, ... ]
485 'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
488 'name' => 'Simple with source',
489 'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
490 #"Date,Time,Name,Called From,Destination,Duration,Price",
494 'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
496 'source_default' => {
497 'name' => 'Default with source',
498 'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
500 'accountcode_default' => {
501 'name' => 'Default plus accountcode',
502 'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
506 my $duration_sub = sub {
508 if ( $opt{minutes} ) {
509 $opt{minutes}. ( $opt{granularity} ? 'm' : ' call' );
511 #config if anyone really wants decimal minutes back
512 #sprintf('%.2fm', $cdr->billsec / 60 );
513 int($cdr->billsec / 60).'m '. ($cdr->billsec % 60).'s';
517 my %export_formats = (
519 sub { time2str('%D', shift->calldate_unix ) }, #DATE
520 sub { time2str('%r', shift->calldate_unix ) }, #TIME
522 'dst', #NUMBER_DIALED
523 $duration_sub, #DURATION
524 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
525 sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
528 sub { time2str('%D', shift->calldate_unix ) }, #DATE
529 sub { time2str('%r', shift->calldate_unix ) }, #TIME
532 'dst', #NUMBER_DIALED
533 $duration_sub, #DURATION
534 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
535 sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
540 sub { time2str('%D', shift->calldate_unix ) },
541 # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
544 sub { time2str('%r', shift->calldate_unix ) },
545 # 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
548 sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
550 #REGIONNAME ("Destination")
551 sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
557 sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; },
561 $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
562 $export_formats{'accountcode_default'} =
563 [ @{ $export_formats{'default'} }[0,1],
565 @{ $export_formats{'default'} }[2..5],
569 my( $self, %opt ) = @_;
571 my $format = $opt{'format'};
572 return "Unknown format $format" unless exists $export_formats{$format};
574 #my $conf = new FS::Conf;
575 #$opt{'money_char'} ||= $conf->config('money_char') || '$';
576 $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
578 eval "use Text::CSV_XS;";
580 my $csv = new Text::CSV_XS;
584 ref($_) ? &{$_}($self, %opt) : $self->$_();
586 @{ $export_formats{$format} };
588 my $status = $csv->combine(@columns);
589 die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
602 =item invoice_formats
604 Returns an ordered list of key value pairs containing invoice format names
605 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
609 sub invoice_formats {
610 map { ($_ => $export_names{$_}->{'name'}) }
611 grep { $export_names{$_}->{'invoice_header'} }
615 =item invoice_header FORMAT
617 Returns a scalar containing the CSV column header for invoice format FORMAT.
623 $export_names{$format}->{'invoice_header'};
628 Returns an ordered list of key value pairs containing import format names
629 as keys (for use with batch_import) and "pretty" format names as values.
633 #false laziness w/part_pkg & part_export
636 foreach my $INC ( @INC ) {
637 warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
638 foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
639 warn "attempting to load CDR format info from $file\n" if $DEBUG;
640 $file =~ /\/(\w+)\.pm$/ or do {
641 warn "unrecognized file in $INC/FS/cdr/: $file\n";
645 my $info = eval "use FS::cdr::$mod; ".
646 "\\%FS::cdr::$mod\::info;";
648 die "error using FS::cdr::$mod (skipping): $@\n" if $@;
651 unless ( keys %$info ) {
652 warn "no %info hash found in FS::cdr::$mod, skipping\n";
655 warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
656 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
657 warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
660 $cdr_info{$mod} = $info;
664 tie my %import_formats, 'Tie::IxHash',
665 map { $_ => $cdr_info{$_}->{'name'} }
666 sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
667 grep { exists($cdr_info{$_}->{'import_fields'}) }
674 sub _cdr_min_parser_maker {
676 my @fields = ref($field) ? @$field : ($field);
677 @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
679 my( $cdr, $min ) = @_;
680 my $sec = eval { _cdr_min_parse($min) };
681 die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
682 $cdr->$_($sec) foreach @fields;
688 sprintf('%.0f', $min * 60 );
691 sub _cdr_date_parser_maker {
694 my @fields = ref($field) ? @$field : ($field);
696 my( $cdr, $datestring ) = @_;
697 my $unixdate = eval { _cdr_date_parse($datestring, %options) };
698 die "error parsing date for @fields from $datestring: $@\n" if $@;
699 $cdr->$_($unixdate) foreach @fields;
703 sub _cdr_date_parse {
707 return '' unless length($date); #that's okay, it becomes NULL
708 return '' if $date eq 'NA'; #sansay
710 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 ) {
711 my $time = str2time($date);
712 return $time if $time > 100000; #just in case
715 my($year, $mon, $day, $hour, $min, $sec);
717 #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
718 #taqua #2007-10-31 08:57:24.113000000
720 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|$)/ ) {
721 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
722 } 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|$)/ ) {
723 ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
724 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
725 # broadsoft: 20081223201938.314
726 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6);
728 die "unparsable date: $date"; #maybe we shouldn't die...
731 return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
732 && $hour == 0 && $min == 0 && $sec == 0;
735 timegm($sec, $min, $hour, $day, $mon-1, $year);
737 timelocal($sec, $min, $hour, $day, $mon-1, $year);
741 =item batch_import HASHREF
743 Imports CDR records. Available options are:
755 Hash reference of preset fields, typically cdrbatch
759 Set true to prevent throwing an error on empty imports
765 my %import_options = (
768 'batch_keycol' => 'cdrbatchnum',
769 'batch_table' => 'cdr_batch',
770 'batch_namecol' => 'cdrbatch',
772 'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
776 #drop the || 'csv' to allow auto xls for csv types?
777 'format_types' => { map { $_ => ( lc($cdr_info{$_}->{'type'}) || 'csv' ); }
781 'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
785 'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
789 'format_fixedlength_formats' =>
790 { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
795 sub _import_options {
802 my $iopt = _import_options;
803 $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
805 FS::Record::batch_import( $opt );
809 =item process_batch_import
813 sub process_batch_import {
816 my $opt = _import_options;
817 # $opt->{'params'} = [ 'format', 'cdrbatch' ];
819 FS::Record::process_batch_import( $job, $opt, @_ );
822 # if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
823 # @columns = map { s/^ +//; $_; } @columns;
828 # Used by FS::Upgrade to migrate to a new database.
831 my ($class, %opts) = @_;
833 warn "$me upgrading $class\n" if $DEBUG;
835 my $sth = dbh->prepare(
836 'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
837 ) or die dbh->errstr;
839 $sth->execute or die $sth->errstr;
841 my %cdrbatchnum = ();
842 while (my $row = $sth->fetchrow_arrayref) {
843 my $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
844 my $error = $cdr_batch->insert;
845 die $error if $error;
846 $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
849 $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
851 foreach my $cdrbatch (keys %cdrbatchnum) {
852 $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
863 L<FS::Record>, schema.html from the base documentation.