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, processing-tiered, done
135 =item freesiderewritestatus - NULL, done, skipped
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 for my $f ( grep { $self->$_ =~ /\D/ } qw(startdate answerdate enddate)){
289 $self->$f( str2time($self->$f) );
292 $self->calldate( $self->startdate_sql )
293 if !$self->calldate && $self->startdate;
295 #was just for $format eq 'taqua' but can't see the harm... add something to
296 #disable if it becomes a problem
297 if ( $self->duration eq '' && $self->enddate && $self->startdate ) {
298 $self->duration( $self->enddate - $self->startdate );
300 if ( $self->billsec eq '' && $self->enddate && $self->answerdate ) {
301 $self->billsec( $self->enddate - $self->answerdate );
304 $self->set_charged_party;
306 #check the foreign keys even?
307 #do we want to outright *reject* the CDR?
309 $self->ut_numbern('acctid')
311 #add a config option to turn these back on if someone needs 'em
313 # #Usage = 1, S&E = 7, OC&C = 8
314 # || $self->ut_foreign_keyn('cdrtypenum', 'cdr_type', 'cdrtypenum' )
316 # #the big list in appendix 2
317 # || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
319 # # Telstra =1, Optus = 2, RSL COM = 3
320 # || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
322 return $error if $error;
327 =item is_tollfree [ COLUMN ]
329 Returns true when the cdr represents a toll free number and false otherwise.
331 By default, inspects the dst field, but an optional column name can be passed
332 to inspect other field.
338 my $field = scalar(@_) ? shift : 'dst';
339 ( $self->$field() =~ /^(\+?1)?8(8|([02-7])\3)/ ) ? 1 : 0;
342 =item set_charged_party
344 If the charged_party field is already set, does nothing. Otherwise:
346 If the cdr-charged_party-accountcode config option is enabled, sets the
347 charged_party to the accountcode.
349 Otherwise sets the charged_party normally: to the src field in most cases,
350 or to the dst field if it is a toll free number.
354 sub set_charged_party {
357 my $conf = new FS::Conf;
359 unless ( $self->charged_party ) {
361 if ( $conf->exists('cdr-charged_party-accountcode') && $self->accountcode ){
363 my $charged_party = $self->accountcode;
364 $charged_party =~ s/^0+//
365 if $conf->exists('cdr-charged_party-accountcode-trim_leading_0s');
366 $self->charged_party( $charged_party );
368 } elsif ( $conf->exists('cdr-charged_party-field') ) {
370 my $field = $conf->config('cdr-charged_party-field');
371 $self->charged_party( $self->$field() );
375 if ( $self->is_tollfree ) {
376 $self->charged_party($self->dst);
378 $self->charged_party($self->src);
385 # my $prefix = $conf->config('cdr-charged_party-truncate_prefix');
386 # my $prefix_len = length($prefix);
387 # my $trunc_len = $conf->config('cdr-charged_party-truncate_length');
389 # $self->charged_party( substr($self->charged_party, 0, $trunc_len) )
390 # if $prefix_len && $trunc_len
391 # && substr($self->charged_party, 0, $prefix_len) eq $prefix;
395 =item set_status_and_rated_price STATUS [ RATED_PRICE [ SVCNUM ] ]
397 Sets the status to the provided string. If there is an error, returns the
398 error, otherwise returns false.
402 sub set_status_and_rated_price {
403 my($self, $status, $rated_price, $svcnum, %opt) = @_;
405 if ($opt{'inbound'}) {
407 my $term = $self->cdr_termination( 1 ); #1: inbound
410 warn "replacing existing cdr status (".$self->acctid.")\n" if $term;
411 $error = $term->delete;
412 return $error if $error;
414 $term = FS::cdr_termination->new({
415 acctid => $self->acctid,
417 rated_price => $rated_price,
420 $term->rated_seconds($opt{rated_seconds}) if exists($opt{rated_seconds});
421 $term->rated_minutes($opt{rated_minutes}) if exists($opt{rated_minutes});
422 $term->svcnum($svcnum) if $svcnum;
423 return $term->insert;
427 $self->freesidestatus($status);
428 $self->rated_price($rated_price);
429 $self->rated_seconds($opt{rated_seconds}) if exists($opt{rated_seconds});
430 $self->rated_minutes($opt{rated_minutes}) if exists($opt{rated_minutes});
431 $self->svcnum($svcnum) if $svcnum;
432 return $self->replace();
437 =item cdr_termination [ TERMPART ]
441 sub cdr_termination {
444 if ( scalar(@_) && $_[0] ) {
445 my $termpart = shift;
447 qsearchs('cdr_termination', { acctid => $self->acctid,
448 termpart => $termpart,
454 qsearch('cdr_termination', { acctid => $self->acctid, } );
462 Parses the calldate in SQL string format and returns a UNIX timestamp.
467 str2time(shift->calldate);
472 Parses the startdate in UNIX timestamp format and returns a string in SQL
478 my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
481 "$year-$mon-$mday $hour:$min:$sec";
486 Returns the FS::cdr_carrier object associated with this CDR, or false if no
487 carrierid is defined.
491 my %carrier_cache = ();
495 return '' unless $self->carrierid;
496 $carrier_cache{$self->carrierid} ||=
497 qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
502 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
503 no FS::cdr_carrier object is assocated with this CDR.
509 my $cdr_carrier = $self->cdr_carrier;
510 $cdr_carrier ? $cdr_carrier->carriername : '';
515 Returns the FS::cdr_calltype object associated with this CDR, or false if no
516 calltypenum is defined.
520 my %calltype_cache = ();
524 return '' unless $self->calltypenum;
525 $calltype_cache{$self->calltypenum} ||=
526 qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
531 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
532 no FS::cdr_calltype object is assocated with this CDR.
538 my $cdr_calltype = $self->cdr_calltype;
539 $cdr_calltype ? $cdr_calltype->calltypename : '';
542 =item downstream_csv [ OPTION => VALUE, ... ]
549 'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
552 'name' => 'Simple with source',
553 'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
554 #"Date,Time,Name,Called From,Destination,Duration,Price",
558 'invoice_header' => "Date/Time,Called Number,Min/Sec,Price",
562 'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
564 'source_default' => {
565 'name' => 'Default with source',
566 'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
568 'accountcode_default' => {
569 'name' => 'Default plus accountcode',
570 'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
572 'description_default' => {
573 'name' => 'Default with description field as destination',
574 'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
577 'name' => 'Summary (one line per service, with duration)',
578 'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
581 'name' => 'Summary (one line per service, with count)',
582 'invoice_header' => 'Caller,Rate,Messages,Price',
586 my %export_formats = ();
590 return %export_formats if keys %export_formats;
592 my $conf = new FS::Conf;
593 my $date_format = $conf->config('date_format') || '%m/%d/%Y';
595 # call duration in the largest units that accurately reflect the granularity
596 my $duration_sub = sub {
598 my $sec = $opt{seconds} || $cdr->billsec;
599 if ( defined $opt{granularity} &&
600 $opt{granularity} == 0 ) { #per call
603 elsif ( defined $opt{granularity} && $opt{granularity} == 60 ) {#full minutes
604 my $min = int($sec/60);
608 else { #anything else
609 return sprintf("%dm %ds", $sec/60, $sec%60);
613 my $price_sub = sub {
614 my ($cdr, %opt) = @_;
616 if ( defined($opt{charge}) ) {
617 $price = $opt{charge};
619 elsif ( $opt{inbound} ) {
620 my $term = $cdr->cdr_termination(1); # 1 = inbound
621 $price = $term->rated_price if defined $term;
624 $price = $cdr->rated_price;
626 length($price) ? ($opt{money_char} . $price) : '';
631 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
632 sub { time2str('%r', shift->calldate_unix ) }, #TIME
634 'dst', #NUMBER_DIALED
635 $duration_sub, #DURATION
636 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
640 sub { time2str($date_format, shift->calldate_unix ) }, #DATE
641 sub { time2str('%r', shift->calldate_unix ) }, #TIME
644 'dst', #NUMBER_DIALED
645 $duration_sub, #DURATION
646 #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
650 # for summary formats, the CDR is a fictitious object containing the
651 # total billsec and the phone number of the service
653 sub { my($cdr, %opt) = @_; $opt{ratename} },
654 sub { my($cdr, %opt) = @_; $opt{count} },
655 sub { my($cdr, %opt) = @_; int($opt{seconds}/60).'m' },
660 sub { my($cdr, %opt) = @_; $opt{ratename} },
661 sub { my($cdr, %opt) = @_; $opt{count} },
665 sub { time2str('%d %b - %I:%M %p', shift->calldate_unix) },
673 sub { time2str($date_format, shift->calldate_unix ) },
674 # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
677 sub { time2str('%r', shift->calldate_unix ) },
678 # 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
681 sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
683 #REGIONNAME ("Destination")
684 sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
693 $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
694 $export_formats{'accountcode_default'} =
695 [ @{ $export_formats{'default'} }[0,1],
697 @{ $export_formats{'default'} }[2..5],
699 my @default = @{ $export_formats{'default'} };
700 $export_formats{'description_default'} =
701 [ 'src', @default[0..2],
702 sub { my($cdr, %opt) = @_; $cdr->description },
705 return %export_formats;
708 =item downstream_csv OPTION => VALUE ...
710 Returns a string of formatted call details for display on an invoice.
716 charge - override the 'rated_price' field of the CDR
718 seconds - override the 'billsec' field of the CDR
720 count - number of usage events included in this record, for summary formats
722 ratename - name of the rate table used to rate this call
729 my( $self, %opt ) = @_;
731 my $format = $opt{'format'};
732 my %formats = $self->export_formats;
733 return "Unknown format $format" unless exists $formats{$format};
735 #my $conf = new FS::Conf;
736 #$opt{'money_char'} ||= $conf->config('money_char') || '$';
737 $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
739 eval "use Text::CSV_XS;";
741 my $csv = new Text::CSV_XS;
745 ref($_) ? &{$_}($self, %opt) : $self->$_();
747 @{ $formats{$format} };
749 return @columns if defined $opt{'keeparray'};
751 my $status = $csv->combine(@columns);
752 die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
765 =item invoice_formats
767 Returns an ordered list of key value pairs containing invoice format names
768 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
772 sub invoice_formats {
773 map { ($_ => $export_names{$_}->{'name'}) }
774 grep { $export_names{$_}->{'invoice_header'} }
778 =item invoice_header FORMAT
780 Returns a scalar containing the CSV column header for invoice format FORMAT.
786 $export_names{$format}->{'invoice_header'};
791 Clears cdr and any associated cdr_termination statuses - used for
799 local $SIG{HUP} = 'IGNORE';
800 local $SIG{INT} = 'IGNORE';
801 local $SIG{QUIT} = 'IGNORE';
802 local $SIG{TERM} = 'IGNORE';
803 local $SIG{TSTP} = 'IGNORE';
804 local $SIG{PIPE} = 'IGNORE';
806 my $oldAutoCommit = $FS::UID::AutoCommit;
807 local $FS::UID::AutoCommit = 0;
810 $self->freesidestatus('');
811 my $error = $self->replace;
813 $dbh->rollback if $oldAutoCommit;
817 foreach my $cdr_termination ( $self->cdr_termination ) {
818 #$cdr_termination->status('');
819 #$error = $cdr_termination->replace;
820 $error = $cdr_termination->delete;
822 $dbh->rollback if $oldAutoCommit;
827 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
834 Returns an ordered list of key value pairs containing import format names
835 as keys (for use with batch_import) and "pretty" format names as values.
839 #false laziness w/part_pkg & part_export
842 foreach my $INC ( @INC ) {
843 warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
844 foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
845 warn "attempting to load CDR format info from $file\n" if $DEBUG;
846 $file =~ /\/(\w+)\.pm$/ or do {
847 warn "unrecognized file in $INC/FS/cdr/: $file\n";
851 my $info = eval "use FS::cdr::$mod; ".
852 "\\%FS::cdr::$mod\::info;";
854 die "error using FS::cdr::$mod (skipping): $@\n" if $@;
857 unless ( keys %$info ) {
858 warn "no %info hash found in FS::cdr::$mod, skipping\n";
861 warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
862 if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
863 warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
866 $cdr_info{$mod} = $info;
870 tie my %import_formats, 'Tie::IxHash',
871 map { $_ => $cdr_info{$_}->{'name'} }
872 sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
873 grep { exists($cdr_info{$_}->{'import_fields'}) }
880 sub _cdr_min_parser_maker {
882 my @fields = ref($field) ? @$field : ($field);
883 @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
885 my( $cdr, $min ) = @_;
886 my $sec = eval { _cdr_min_parse($min) };
887 die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
888 $cdr->$_($sec) foreach @fields;
894 sprintf('%.0f', $min * 60 );
897 sub _cdr_date_parser_maker {
900 my @fields = ref($field) ? @$field : ($field);
902 my( $cdr, $datestring ) = @_;
903 my $unixdate = eval { _cdr_date_parse($datestring, %options) };
904 die "error parsing date for @fields from $datestring: $@\n" if $@;
905 $cdr->$_($unixdate) foreach @fields;
909 sub _cdr_date_parse {
913 return '' unless length($date); #that's okay, it becomes NULL
914 return '' if $date eq 'NA'; #sansay
916 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 ) {
917 my $time = str2time($date);
918 return $time if $time > 100000; #just in case
921 my($year, $mon, $day, $hour, $min, $sec);
923 #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
924 #taqua #2007-10-31 08:57:24.113000000
926 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|$)/ ) {
927 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
928 } 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|$)/ ) {
930 # optionally without seconds
931 ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
932 $sec = 0 if !defined($sec);
933 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
934 # broadsoft: 20081223201938.314
935 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
936 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\d+(\D|$)/ ) {
937 # Taqua OM: 20050422203450943
938 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
939 } elsif ( $date =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/ ) {
940 # WIP: 20100329121420
941 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
942 } elsif ( $date =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/) {
944 ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
947 die "unparsable date: $date"; #maybe we shouldn't die...
950 return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
951 && $hour == 0 && $min == 0 && $sec == 0;
954 timegm($sec, $min, $hour, $day, $mon-1, $year);
956 timelocal($sec, $min, $hour, $day, $mon-1, $year);
960 =item batch_import HASHREF
962 Imports CDR records. Available options are:
974 Hash reference of preset fields, typically cdrbatch
978 Set true to prevent throwing an error on empty imports
984 my %import_options = (
987 'batch_keycol' => 'cdrbatchnum',
988 'batch_table' => 'cdr_batch',
989 'batch_namecol' => 'cdrbatch',
991 'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
995 #drop the || 'csv' to allow auto xls for csv types?
996 'format_types' => { map { $_ => lc($cdr_info{$_}->{'type'} || 'csv'); }
1000 'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
1004 'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
1008 'format_fixedlength_formats' =>
1009 { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
1013 'format_xml_formats' =>
1014 { map { $_ => $cdr_info{$_}->{'xml_format'}; }
1018 'format_row_callbacks' => { map { $_ => $cdr_info{$_}->{'row_callback'}; }
1023 sub _import_options {
1030 my $iopt = _import_options;
1031 $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
1033 if ( defined $opt->{'cdrtypenum'} ) {
1034 $opt->{'preinsert_callback'} = sub {
1035 my($record,$param) = (shift,shift);
1036 $record->cdrtypenum($opt->{'cdrtypenum'});
1041 FS::Record::batch_import( $opt );
1045 =item process_batch_import
1049 sub process_batch_import {
1052 my $opt = _import_options;
1053 # $opt->{'params'} = [ 'format', 'cdrbatch' ];
1055 FS::Record::process_batch_import( $job, $opt, @_ );
1058 # if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
1059 # @columns = map { s/^ +//; $_; } @columns;
1064 # Used by FS::Upgrade to migrate to a new database.
1067 my ($class, %opts) = @_;
1069 warn "$me upgrading $class\n" if $DEBUG;
1071 my $sth = dbh->prepare(
1072 'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
1073 ) or die dbh->errstr;
1075 $sth->execute or die $sth->errstr;
1077 my %cdrbatchnum = ();
1078 while (my $row = $sth->fetchrow_arrayref) {
1080 my $cdr_batch = qsearchs( 'cdr_batch', { 'cdrbatch' => $row->[0] } );
1081 unless ( $cdr_batch ) {
1082 $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
1083 my $error = $cdr_batch->insert;
1084 die $error if $error;
1087 $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
1090 $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
1092 foreach my $cdrbatch (keys %cdrbatchnum) {
1093 $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
1104 L<FS::Record>, schema.html from the base documentation.