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;
19 @ISA = qw(FS::Record);
20 @EXPORT_OK = qw( _cdr_date_parser_maker _cdr_min_parser_maker );
27 FS::cdr - Object methods for cdr records
33 $record = new FS::cdr \%hash;
34 $record = new FS::cdr { 'column' => 'value' };
36 $error = $record->insert;
38 $error = $new_record->replace($old_record);
40 $error = $record->delete;
42 $error = $record->check;
46 An FS::cdr object represents an Call Data Record, typically from a telephony
47 system or provider of some sort. FS::cdr inherits from FS::Record. The
48 following fields are currently supported:
52 =item acctid - primary key
54 =item calldate - Call timestamp (SQL timestamp)
56 =item clid - Caller*ID with text
58 =item src - Caller*ID number / Source number
60 =item dst - Destination extension
62 =item dcontext - Destination context
64 =item channel - Channel used
66 =item dstchannel - Destination channel if appropriate
68 =item lastapp - Last application if appropriate
70 =item lastdata - Last application data
72 =item startdate - Start of call (UNIX-style integer timestamp)
74 =item answerdate - Answer time of call (UNIX-style integer timestamp)
76 =item enddate - End time of call (UNIX-style integer timestamp)
78 =item duration - Total time in system, in seconds
80 =item billsec - Total time call is up, in seconds
82 =item disposition - What happened to the call: ANSWERED, NO ANSWER, BUSY
84 =item amaflags - What flags to use: BILL, IGNORE etc, specified on a per channel basis like accountcode.
88 #ignore the "omit" and "documentation" AMAs??
89 #AMA = Automated Message Accounting.
90 #default: Sets the system default.
91 #omit: Do not record calls.
92 #billing: Mark the entry for billing
93 #documentation: Mark the entry for documentation.
95 =item accountcode - CDR account number to use: account
97 =item uniqueid - Unique channel identifier (Unitel/RSLCOM Event ID)
99 =item userfield - CDR user-defined field
101 =item cdr_type - CDR type - see L<FS::cdr_type> (Usage = 1, S&E = 7, OC&C = 8)
103 =item charged_party - Service number to be billed
105 =item upstream_currency - Wholesale currency from upstream
107 =item upstream_price - Wholesale price from upstream
109 =item upstream_rateplanid - Upstream rate plan ID
111 =item rated_price - Rated (or re-rated) price
113 =item distance - km (need units field?)
115 =item islocal - Local - 1, Non Local = 0
117 =item calltypenum - Type of call - see L<FS::cdr_calltype>
119 =item description - Description (cdr_type 7&8 only) (used for cust_bill_pkg.itemdesc)
121 =item quantity - Number of items (cdr_type 7&8 only)
123 =item carrierid - Upstream Carrier ID (see L<FS::cdr_carrier>)
127 #Telstra =1, Optus = 2, RSL COM = 3
129 =item upstream_rateid - Upstream Rate ID
131 =item svcnum - Link to customer service (see L<FS::cust_svc>)
133 =item freesidestatus - NULL, done (or something)
135 =item freesiderewritestatus - NULL, done (or something)
147 Creates a new CDR. To add the CDR to the database, see L<"insert">.
149 Note that this stores the hash reference, not a distinct copy of the hash it
150 points to. You can ask the object for a copy with the I<hash> method.
154 # the new method can be inherited from FS::Record, if a table method is defined
161 #XXX fill in some (more) nice names
163 'calldate' => 'Call date',
164 'clid' => 'Caller ID',
166 'dst' => 'Destination',
167 'dcontext' => 'Dest. context',
168 'channel' => 'Channel',
169 'dstchannel' => 'Destination channel',
172 'startdate' => 'Start date',
173 'answerdate' => 'Answer date',
174 'enddate' => 'End date',
175 'duration' => 'Duration',
176 'billsec' => 'Billable seconds',
177 'disposition' => 'Disposition',
178 'amaflags' => 'AMA flags',
179 'accountcode' => 'Account code',
181 'userfield' => 'User field',
183 'charged_party' => 'Charged party',
184 #'upstream_currency' => '',
185 'upstream_price' => 'Upstream price',
186 #'upstream_rateplanid' => '',
187 #'ratedetailnum' => '',
188 'rated_price' => 'Rated price',
191 #'calltypenum' => '',
192 #'description' => '',
194 'carrierid' => 'Carrier ID',
195 #'upstream_rateid' => '',
196 'svcnum' => 'Freeside service',
197 'freesidestatus' => 'Freeside status',
198 'freesiderewritestatus' => 'Freeside rewrite status',
199 'cdrbatch' => 'Legacy batch',
200 'cdrbatchnum' => 'Batch',
209 Adds this record to the database. If there is an error, returns the error,
210 otherwise returns false.
214 # the insert method can be inherited from FS::Record
218 Delete this record from the database.
222 # the delete method can be inherited from FS::Record
224 =item replace OLD_RECORD
226 Replaces the OLD_RECORD with this one in the database. If there is an error,
227 returns the error, otherwise returns false.
231 # the replace method can be inherited from FS::Record
235 Checks all fields to make sure this is a valid CDR. If there is
236 an error, returns the error, otherwise returns false. Called by the insert
239 Note: Unlike most types of records, we don't want to "reject" a CDR and we want
240 to process them as quickly as possible, so we allow the database to check most
248 # we don't want to "reject" a CDR like other sorts of input...
250 # $self->ut_numbern('acctid')
251 ## || $self->ut_('calldate')
252 # || $self->ut_text('clid')
253 # || $self->ut_text('src')
254 # || $self->ut_text('dst')
255 # || $self->ut_text('dcontext')
256 # || $self->ut_text('channel')
257 # || $self->ut_text('dstchannel')
258 # || $self->ut_text('lastapp')
259 # || $self->ut_text('lastdata')
260 # || $self->ut_numbern('startdate')
261 # || $self->ut_numbern('answerdate')
262 # || $self->ut_numbern('enddate')
263 # || $self->ut_number('duration')
264 # || $self->ut_number('billsec')
265 # || $self->ut_text('disposition')
266 # || $self->ut_number('amaflags')
267 # || $self->ut_text('accountcode')
268 # || $self->ut_text('uniqueid')
269 # || $self->ut_text('userfield')
270 # || $self->ut_numbern('cdrtypenum')
271 # || $self->ut_textn('charged_party')
272 ## || $self->ut_n('upstream_currency')
273 ## || $self->ut_n('upstream_price')
274 # || $self->ut_numbern('upstream_rateplanid')
275 ## || $self->ut_n('distance')
276 # || $self->ut_numbern('islocal')
277 # || $self->ut_numbern('calltypenum')
278 # || $self->ut_textn('description')
279 # || $self->ut_numbern('quantity')
280 # || $self->ut_numbern('carrierid')
281 # || $self->ut_numbern('upstream_rateid')
282 # || $self->ut_numbern('svcnum')
283 # || $self->ut_textn('freesidestatus')
284 # || $self->ut_textn('freesiderewritestatus')
286 # return $error if $error;
288 $self->calldate( $self->startdate_sql )
289 if !$self->calldate && $self->startdate;
291 #was just for $format eq 'taqua' but can't see the harm... add something to
292 #disable if it becomes a problem
293 if ( $self->duration eq '' && $self->enddate && $self->startdate ) {
294 $self->duration( $self->enddate - $self->startdate );
296 if ( $self->billsec eq '' && $self->enddate && $self->answerdate ) {
297 $self->billsec( $self->enddate - $self->answerdate );
300 $self->set_charged_party;
302 #check the foreign keys even?
303 #do we want to outright *reject* the CDR?
305 $self->ut_numbern('acctid')
307 #add a config option to turn these back on if someone needs 'em
309 # #Usage = 1, S&E = 7, OC&C = 8
310 # || $self->ut_foreign_keyn('cdrtypenum', 'cdr_type', 'cdrtypenum' )
312 # #the big list in appendix 2
313 # || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
315 # # Telstra =1, Optus = 2, RSL COM = 3
316 # || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
318 return $error if $error;
325 Returns true when the cdr represents a toll free number and false otherwise.
331 ( $self->dst =~ /^(\+?1)?8(8|([02-7])\3)/ ) ? 1 : 0;
334 =item set_charged_party
336 If the charged_party field is already set, does nothing. Otherwise:
338 If the cdr-charged_party-accountcode config option is enabled, sets the
339 charged_party to the accountcode.
341 Otherwise sets the charged_party normally: to the src field in most cases,
342 or to the dst field if it is a toll free number.
346 sub set_charged_party {
349 my $conf = new FS::Conf;
351 unless ( $self->charged_party ) {
353 if ( $conf->exists('cdr-charged_party-accountcode') && $self->accountcode ){
355 my $charged_party = $self->accountcode;
356 $charged_party =~ s/^0+//
357 if $conf->exists('cdr-charged_party-accountcode-trim_leading_0s');
358 $self->charged_party( $charged_party );
362 if ( $self->is_tollfree ) {
363 $self->charged_party($self->dst);
365 $self->charged_party($self->src);
372 # my $prefix = $conf->config('cdr-charged_party-truncate_prefix');
373 # my $prefix_len = length($prefix);
374 # my $trunc_len = $conf->config('cdr-charged_party-truncate_length');
376 # $self->charged_party( substr($self->charged_party, 0, $trunc_len) )
377 # if $prefix_len && $trunc_len
378 # && substr($self->charged_party, 0, $prefix_len) eq $prefix;
382 =item set_status_and_rated_price STATUS [ RATED_PRICE [ SVCNUM ] ]
384 Sets the status to the provided string. If there is an error, returns the
385 error, otherwise returns false.
389 sub set_status_and_rated_price {
390 my($self, $status, $rated_price, $svcnum, %opt) = @_;
391 if($opt{'inbound'}) {
392 my $term = qsearchs('cdr_termination', {
393 acctid => $self->acctid,
394 termpart => 1 # inbound
398 warn "replacing existing cdr status (".$self->acctid.")\n" if $term;
399 $error = $term->delete;
400 return $error if $error;
402 $term = FS::cdr_termination->new({
403 acctid => $self->acctid,
405 rated_price => $rated_price,
409 return $term->insert;
412 $self->freesidestatus($status);
413 $self->rated_price($rated_price);
414 $self->svcnum($svcnum) if $svcnum;
415 return $self->replace();
421 Parses the calldate in SQL string format and returns a UNIX timestamp.
426 str2time(shift->calldate);
431 Parses the startdate in UNIX timestamp format and returns a string in SQL
437 my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
440 "$year-$mon-$mday $hour:$min:$sec";
445 Returns the FS::cdr_carrier object associated with this CDR, or false if no
446 carrierid is defined.
450 my %carrier_cache = ();
454 return '' unless $self->carrierid;
455 $carrier_cache{$self->carrierid} ||=
456 qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
461 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
462 no FS::cdr_carrier object is assocated with this CDR.
468 my $cdr_carrier = $self->cdr_carrier;
469 $cdr_carrier ? $cdr_carrier->carriername : '';
474 Returns the FS::cdr_calltype object associated with this CDR, or false if no
475 calltypenum is defined.
479 my %calltype_cache = ();
483 return '' unless $self->calltypenum;
484 $calltype_cache{$self->calltypenum} ||=
485 qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
490 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
491 no FS::cdr_calltype object is assocated with this CDR.
497 my $cdr_calltype = $self->cdr_calltype;
498 $cdr_calltype ? $cdr_calltype->calltypename : '';
501 =item downstream_csv [ OPTION => VALUE, ... ]
508 'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
511 'name' => 'Simple with source',
512 'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
513 #"Date,Time,Name,Called From,Destination,Duration,Price",
517 'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
519 'source_default' => {
520 'name' => 'Default with source',
521 'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
523 'accountcode_default' => {
524 'name' => 'Default plus accountcode',
525 'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
529 my %export_formats = ();
533 return %export_formats if keys %export_formats;
535 my $conf = new FS::Conf;
536 my $date_format = $conf->config('date_format') || '%m/%d/%Y';
538 my $duration_sub = sub {
540 if ( $opt{minutes} ) {
541 $opt{minutes}. ( $opt{granularity} ? 'm' : ' call' );
543 #config if anyone really wants decimal minutes back
544 #sprintf('%.2fm', $cdr->billsec / 60 );
545 int($cdr->billsec / 60).'m '. ($cdr->billsec % 60).'s';
551 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
552 sub { time2str('%r', shift->calldate_unix ) }, #TIME
554 'dst', #NUMBER_DIALED
555 $duration_sub, #DURATION
556 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
557 sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
560 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
561 sub { time2str('%r', shift->calldate_unix ) }, #TIME
564 'dst', #NUMBER_DIALED
565 $duration_sub, #DURATION
566 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
567 sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
572 sub { time2str($date_format, shift->calldate_unix ) },
573 # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
576 sub { time2str('%r', shift->calldate_unix ) },
577 # 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
580 sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
582 #REGIONNAME ("Destination")
583 sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
589 sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; },
593 $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
594 $export_formats{'accountcode_default'} =
595 [ @{ $export_formats{'default'} }[0,1],
597 @{ $export_formats{'default'} }[2..5],
604 my( $self, %opt ) = @_;
606 my $format = $opt{'format'};
607 my %formats = $self->export_formats;
608 return "Unknown format $format" unless exists $formats{$format};
610 #my $conf = new FS::Conf;
611 #$opt{'money_char'} ||= $conf->config('money_char') || '$';
612 $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
614 eval "use Text::CSV_XS;";
616 my $csv = new Text::CSV_XS;
620 ref($_) ? &{$_}($self, %opt) : $self->$_();
622 @{ $formats{$format} };
624 my $status = $csv->combine(@columns);
625 die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
638 =item invoice_formats
640 Returns an ordered list of key value pairs containing invoice format names
641 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
645 sub invoice_formats {
646 map { ($_ => $export_names{$_}->{'name'}) }
647 grep { $export_names{$_}->{'invoice_header'} }
651 =item invoice_header FORMAT
653 Returns a scalar containing the CSV column header for invoice format FORMAT.
659 $export_names{$format}->{'invoice_header'};
664 Returns an ordered list of key value pairs containing import format names
665 as keys (for use with batch_import) and "pretty" format names as values.
669 #false laziness w/part_pkg & part_export
672 foreach my $INC ( @INC ) {
673 warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
674 foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
675 warn "attempting to load CDR format info from $file\n" if $DEBUG;
676 $file =~ /\/(\w+)\.pm$/ or do {
677 warn "unrecognized file in $INC/FS/cdr/: $file\n";
681 my $info = eval "use FS::cdr::$mod; ".
682 "\\%FS::cdr::$mod\::info;";
684 die "error using FS::cdr::$mod (skipping): $@\n" if $@;
687 unless ( keys %$info ) {
688 warn "no %info hash found in FS::cdr::$mod, skipping\n";
691 warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
692 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
693 warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
696 $cdr_info{$mod} = $info;
700 tie my %import_formats, 'Tie::IxHash',
701 map { $_ => $cdr_info{$_}->{'name'} }
702 sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
703 grep { exists($cdr_info{$_}->{'import_fields'}) }
710 sub _cdr_min_parser_maker {
712 my @fields = ref($field) ? @$field : ($field);
713 @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
715 my( $cdr, $min ) = @_;
716 my $sec = eval { _cdr_min_parse($min) };
717 die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
718 $cdr->$_($sec) foreach @fields;
724 sprintf('%.0f', $min * 60 );
727 sub _cdr_date_parser_maker {
730 my @fields = ref($field) ? @$field : ($field);
732 my( $cdr, $datestring ) = @_;
733 my $unixdate = eval { _cdr_date_parse($datestring, %options) };
734 die "error parsing date for @fields from $datestring: $@\n" if $@;
735 $cdr->$_($unixdate) foreach @fields;
739 sub _cdr_date_parse {
743 return '' unless length($date); #that's okay, it becomes NULL
744 return '' if $date eq 'NA'; #sansay
746 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 ) {
747 my $time = str2time($date);
748 return $time if $time > 100000; #just in case
751 my($year, $mon, $day, $hour, $min, $sec);
753 #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
754 #taqua #2007-10-31 08:57:24.113000000
756 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|$)/ ) {
757 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
758 } 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|$)/ ) {
759 ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
760 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
761 # broadsoft: 20081223201938.314
762 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
763 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/ ) {
764 # WIP: 20100329121420
765 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
767 die "unparsable date: $date"; #maybe we shouldn't die...
770 return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
771 && $hour == 0 && $min == 0 && $sec == 0;
774 timegm($sec, $min, $hour, $day, $mon-1, $year);
776 timelocal($sec, $min, $hour, $day, $mon-1, $year);
780 =item batch_import HASHREF
782 Imports CDR records. Available options are:
794 Hash reference of preset fields, typically cdrbatch
798 Set true to prevent throwing an error on empty imports
804 my %import_options = (
807 'batch_keycol' => 'cdrbatchnum',
808 'batch_table' => 'cdr_batch',
809 'batch_namecol' => 'cdrbatch',
811 'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
815 #drop the || 'csv' to allow auto xls for csv types?
816 'format_types' => { map { $_ => ( lc($cdr_info{$_}->{'type'}) || 'csv' ); }
820 'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
824 'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
828 'format_fixedlength_formats' =>
829 { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
834 sub _import_options {
841 my $iopt = _import_options;
842 $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
844 FS::Record::batch_import( $opt );
848 =item process_batch_import
852 sub process_batch_import {
855 my $opt = _import_options;
856 # $opt->{'params'} = [ 'format', 'cdrbatch' ];
858 FS::Record::process_batch_import( $job, $opt, @_ );
861 # if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
862 # @columns = map { s/^ +//; $_; } @columns;
867 # Used by FS::Upgrade to migrate to a new database.
870 my ($class, %opts) = @_;
872 warn "$me upgrading $class\n" if $DEBUG;
874 my $sth = dbh->prepare(
875 'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
876 ) or die dbh->errstr;
878 $sth->execute or die $sth->errstr;
880 my %cdrbatchnum = ();
881 while (my $row = $sth->fetchrow_arrayref) {
882 my $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
883 my $error = $cdr_batch->insert;
884 die $error if $error;
885 $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
888 $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
890 foreach my $cdrbatch (keys %cdrbatchnum) {
891 $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
902 L<FS::Record>, schema.html from the base documentation.