This commit was generated by cvs2svn to compensate for changes in r9232,
[freeside.git] / FS / FS / cdr.pm
1 package FS::cdr;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK $DEBUG $me );
5 use Exporter;
6 use Tie::IxHash;
7 use Date::Parse;
8 use Date::Format;
9 use Time::Local;
10 use FS::UID qw( dbh );
11 use FS::Conf;
12 use FS::Record qw( qsearch qsearchs );
13 use FS::cdr_type;
14 use FS::cdr_calltype;
15 use FS::cdr_carrier;
16 use FS::cdr_batch;
17 use FS::cdr_termination;
18
19 @ISA = qw(FS::Record);
20 @EXPORT_OK = qw( _cdr_date_parser_maker _cdr_min_parser_maker );
21
22 $DEBUG = 0;
23 $me = '[FS::cdr]';
24
25 =head1 NAME
26
27 FS::cdr - Object methods for cdr records
28
29 =head1 SYNOPSIS
30
31   use FS::cdr;
32
33   $record = new FS::cdr \%hash;
34   $record = new FS::cdr { 'column' => 'value' };
35
36   $error = $record->insert;
37
38   $error = $new_record->replace($old_record);
39
40   $error = $record->delete;
41
42   $error = $record->check;
43
44 =head1 DESCRIPTION
45
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:
49
50 =over 4
51
52 =item acctid - primary key
53
54 =item calldate - Call timestamp (SQL timestamp)
55
56 =item clid - Caller*ID with text
57
58 =item src - Caller*ID number / Source number
59
60 =item dst - Destination extension
61
62 =item dcontext - Destination context
63
64 =item channel - Channel used
65
66 =item dstchannel - Destination channel if appropriate
67
68 =item lastapp - Last application if appropriate
69
70 =item lastdata - Last application data
71
72 =item startdate - Start of call (UNIX-style integer timestamp)
73
74 =item answerdate - Answer time of call (UNIX-style integer timestamp)
75
76 =item enddate - End time of call (UNIX-style integer timestamp)
77
78 =item duration - Total time in system, in seconds
79
80 =item billsec - Total time call is up, in seconds
81
82 =item disposition - What happened to the call: ANSWERED, NO ANSWER, BUSY 
83
84 =item amaflags - What flags to use: BILL, IGNORE etc, specified on a per channel basis like accountcode. 
85
86 =cut
87
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.
94
95 =item accountcode - CDR account number to use: account
96
97 =item uniqueid - Unique channel identifier (Unitel/RSLCOM Event ID)
98
99 =item userfield - CDR user-defined field
100
101 =item cdr_type - CDR type - see L<FS::cdr_type> (Usage = 1, S&E = 7, OC&C = 8)
102
103 =item charged_party - Service number to be billed
104
105 =item upstream_currency - Wholesale currency from upstream
106
107 =item upstream_price - Wholesale price from upstream
108
109 =item upstream_rateplanid - Upstream rate plan ID
110
111 =item rated_price - Rated (or re-rated) price
112
113 =item distance - km (need units field?)
114
115 =item islocal - Local - 1, Non Local = 0
116
117 =item calltypenum - Type of call - see L<FS::cdr_calltype>
118
119 =item description - Description (cdr_type 7&8 only) (used for cust_bill_pkg.itemdesc)
120
121 =item quantity - Number of items (cdr_type 7&8 only)
122
123 =item carrierid - Upstream Carrier ID (see L<FS::cdr_carrier>) 
124
125 =cut
126
127 #Telstra =1, Optus = 2, RSL COM = 3
128
129 =item upstream_rateid - Upstream Rate ID
130
131 =item svcnum - Link to customer service (see L<FS::cust_svc>)
132
133 =item freesidestatus - NULL, done (or something)
134
135 =item freesiderewritestatus - NULL, done (or something)
136
137 =item cdrbatch
138
139 =back
140
141 =head1 METHODS
142
143 =over 4
144
145 =item new HASHREF
146
147 Creates a new CDR.  To add the CDR to the database, see L<"insert">.
148
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.
151
152 =cut
153
154 # the new method can be inherited from FS::Record, if a table method is defined
155
156 sub table { 'cdr'; }
157
158 sub table_info {
159   {
160     'fields' => {
161 #XXX fill in some (more) nice names
162         #'acctid'                => '',
163         'calldate'              => 'Call date',
164         'clid'                  => 'Caller ID',
165         'src'                   => 'Source',
166         'dst'                   => 'Destination',
167         'dcontext'              => 'Dest. context',
168         'channel'               => 'Channel',
169         'dstchannel'            => 'Destination channel',
170         #'lastapp'               => '',
171         #'lastdata'              => '',
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',
180         #'uniqueid'              => '',
181         'userfield'             => 'User field',
182         #'cdrtypenum'            => '',
183         'charged_party'         => 'Charged party',
184         #'upstream_currency'     => '',
185         'upstream_price'        => 'Upstream price',
186         #'upstream_rateplanid'   => '',
187         #'ratedetailnum'         => '',
188         'rated_price'           => 'Rated price',
189         #'distance'              => '',
190         #'islocal'               => '',
191         #'calltypenum'           => '',
192         #'description'           => '',
193         #'quantity'              => '',
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',
201     },
202
203   };
204
205 }
206
207 =item insert
208
209 Adds this record to the database.  If there is an error, returns the error,
210 otherwise returns false.
211
212 =cut
213
214 # the insert method can be inherited from FS::Record
215
216 =item delete
217
218 Delete this record from the database.
219
220 =cut
221
222 # the delete method can be inherited from FS::Record
223
224 =item replace OLD_RECORD
225
226 Replaces the OLD_RECORD with this one in the database.  If there is an error,
227 returns the error, otherwise returns false.
228
229 =cut
230
231 # the replace method can be inherited from FS::Record
232
233 =item check
234
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
237 and replace methods.
238
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
241 of the data.
242
243 =cut
244
245 sub check {
246   my $self = shift;
247
248 # we don't want to "reject" a CDR like other sorts of input...
249 #  my $error = 
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')
285 #  ;
286 #  return $error if $error;
287
288   $self->calldate( $self->startdate_sql )
289     if !$self->calldate && $self->startdate;
290
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  );
295   }
296   if ( $self->billsec eq '' && $self->enddate && $self->answerdate ) {
297     $self->billsec(  $self->enddate - $self->answerdate );
298   } 
299
300   $self->set_charged_party;
301
302   #check the foreign keys even?
303   #do we want to outright *reject* the CDR?
304   my $error =
305        $self->ut_numbern('acctid')
306
307   #add a config option to turn these back on if someone needs 'em
308   #
309   #  #Usage = 1, S&E = 7, OC&C = 8
310   #  || $self->ut_foreign_keyn('cdrtypenum',  'cdr_type',     'cdrtypenum' )
311   #
312   #  #the big list in appendix 2
313   #  || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
314   #
315   #  # Telstra =1, Optus = 2, RSL COM = 3
316   #  || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
317   ;
318   return $error if $error;
319
320   $self->SUPER::check;
321 }
322
323 =item is_tollfree
324
325   Returns true when the cdr represents a toll free number and false otherwise.
326
327 =cut
328
329 sub is_tollfree {
330   my $self = shift;
331   ( $self->dst =~ /^(\+?1)?8(8|([02-7])\3)/ ) ? 1 : 0;
332 }
333
334 =item set_charged_party
335
336 If the charged_party field is already set, does nothing.  Otherwise:
337
338 If the cdr-charged_party-accountcode config option is enabled, sets the
339 charged_party to the accountcode.
340
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.
343
344 =cut
345
346 sub set_charged_party {
347   my $self = shift;
348
349   my $conf = new FS::Conf;
350
351   unless ( $self->charged_party ) {
352
353     if ( $conf->exists('cdr-charged_party-accountcode') && $self->accountcode ){
354
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 );
359
360     } else {
361
362       if ( $self->is_tollfree ) {
363         $self->charged_party($self->dst);
364       } else {
365         $self->charged_party($self->src);
366       }
367
368     }
369
370   }
371
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');
375 #
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;
379
380 }
381
382 =item set_status_and_rated_price STATUS [ RATED_PRICE [ SVCNUM ] ]
383
384 Sets the status to the provided string.  If there is an error, returns the
385 error, otherwise returns false.
386
387 =cut
388
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
395     });
396     my $error;
397     if($term) {
398       warn "replacing existing cdr status (".$self->acctid.")\n" if $term;
399       $error = $term->delete;
400       return $error if $error;
401     }
402     $term = FS::cdr_termination->new({
403         acctid      => $self->acctid,
404         termpart    => 1,
405         rated_price => $rated_price,
406         status      => $status,
407         svcnum      => $svcnum,
408     });
409     return $term->insert;
410   }
411   else {
412     $self->freesidestatus($status);
413     $self->rated_price($rated_price);
414     $self->svcnum($svcnum) if $svcnum;
415     return $self->replace();
416   }
417 }
418
419 =item calldate_unix 
420
421 Parses the calldate in SQL string format and returns a UNIX timestamp.
422
423 =cut
424
425 sub calldate_unix {
426   str2time(shift->calldate);
427 }
428
429 =item startdate_sql
430
431 Parses the startdate in UNIX timestamp format and returns a string in SQL
432 format.
433
434 =cut
435
436 sub startdate_sql {
437   my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
438   $mon++;
439   $year += 1900;
440   "$year-$mon-$mday $hour:$min:$sec";
441 }
442
443 =item cdr_carrier
444
445 Returns the FS::cdr_carrier object associated with this CDR, or false if no
446 carrierid is defined.
447
448 =cut
449
450 my %carrier_cache = ();
451
452 sub cdr_carrier {
453   my $self = shift;
454   return '' unless $self->carrierid;
455   $carrier_cache{$self->carrierid} ||=
456     qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
457 }
458
459 =item carriername 
460
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.
463
464 =cut
465
466 sub carriername {
467   my $self = shift;
468   my $cdr_carrier = $self->cdr_carrier;
469   $cdr_carrier ? $cdr_carrier->carriername : '';
470 }
471
472 =item cdr_calltype
473
474 Returns the FS::cdr_calltype object associated with this CDR, or false if no
475 calltypenum is defined.
476
477 =cut
478
479 my %calltype_cache = ();
480
481 sub cdr_calltype {
482   my $self = shift;
483   return '' unless $self->calltypenum;
484   $calltype_cache{$self->calltypenum} ||=
485     qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
486 }
487
488 =item calltypename 
489
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.
492
493 =cut
494
495 sub calltypename {
496   my $self = shift;
497   my $cdr_calltype = $self->cdr_calltype;
498   $cdr_calltype ? $cdr_calltype->calltypename : '';
499 }
500
501 =item downstream_csv [ OPTION => VALUE, ... ]
502
503 =cut
504
505 my %export_names = (
506   'simple'  => {
507     'name'           => 'Simple',
508     'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
509   },
510   'simple2' => {
511     'name'           => 'Simple with source',
512     'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
513                        #"Date,Time,Name,Called From,Destination,Duration,Price",
514   },
515   'default' => {
516     'name'           => 'Default',
517     'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
518   },
519   'source_default' => {
520     'name'           => 'Default with source',
521     'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
522   },
523   'accountcode_default' => {
524     'name'           => 'Default plus accountcode',
525     'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
526   },
527 );
528
529 my $duration_sub = sub {
530   my($cdr, %opt) = @_;
531   if ( $opt{minutes} ) {
532     $opt{minutes}. ( $opt{granularity} ? 'm' : ' call' );
533   } else {
534     #config if anyone really wants decimal minutes back
535     #sprintf('%.2fm', $cdr->billsec / 60 );
536     int($cdr->billsec / 60).'m '. ($cdr->billsec % 60).'s';
537   }
538 };
539
540 my %export_formats = (
541   'simple' => [
542     sub { time2str('%D', shift->calldate_unix ) },   #DATE
543     sub { time2str('%r', shift->calldate_unix ) },   #TIME
544     'userfield',                                     #USER
545     'dst',                                           #NUMBER_DIALED
546     $duration_sub,                                   #DURATION
547     #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
548     sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
549   ],
550   'simple2' => [
551     sub { time2str('%D', shift->calldate_unix ) },   #DATE
552     sub { time2str('%r', shift->calldate_unix ) },   #TIME
553     #'userfield',                                     #USER
554     'src',                                           #called from
555     'dst',                                           #NUMBER_DIALED
556     $duration_sub,                                   #DURATION
557     #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
558     sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
559   ],
560   'default' => [
561
562     #DATE
563     sub { time2str('%D', shift->calldate_unix ) },
564           # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
565
566     #TIME
567     sub { time2str('%r', shift->calldate_unix ) },
568           # 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
569
570     #DEST ("Number")
571     sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
572
573     #REGIONNAME ("Destination")
574     sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
575
576     #DURATION
577     $duration_sub,
578
579     #PRICE
580     sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; },
581
582   ],
583 );
584 $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
585 $export_formats{'accountcode_default'} =
586   [ @{ $export_formats{'default'} }[0,1],
587     'accountcode',
588     @{ $export_formats{'default'} }[2..5],
589   ];
590
591 sub downstream_csv {
592   my( $self, %opt ) = @_;
593
594   my $format = $opt{'format'};
595   return "Unknown format $format" unless exists $export_formats{$format};
596
597   #my $conf = new FS::Conf;
598   #$opt{'money_char'} ||= $conf->config('money_char') || '$';
599   $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
600
601   eval "use Text::CSV_XS;";
602   die $@ if $@;
603   my $csv = new Text::CSV_XS;
604
605   my @columns =
606     map {
607           ref($_) ? &{$_}($self, %opt) : $self->$_();
608         }
609     @{ $export_formats{$format} };
610
611   my $status = $csv->combine(@columns);
612   die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
613     unless $status;
614
615   $csv->string;
616
617 }
618
619 =back
620
621 =head1 CLASS METHODS
622
623 =over 4
624
625 =item invoice_formats
626
627 Returns an ordered list of key value pairs containing invoice format names
628 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
629
630 =cut
631
632 sub invoice_formats {
633   map { ($_ => $export_names{$_}->{'name'}) }
634     grep { $export_names{$_}->{'invoice_header'} }
635     keys %export_names;
636 }
637
638 =item invoice_header FORMAT
639
640 Returns a scalar containing the CSV column header for invoice format FORMAT.
641
642 =cut
643
644 sub invoice_header {
645   my $format = shift;
646   $export_names{$format}->{'invoice_header'};
647 }
648
649 =item import_formats
650
651 Returns an ordered list of key value pairs containing import format names
652 as keys (for use with batch_import) and "pretty" format names as values.
653
654 =cut
655
656 #false laziness w/part_pkg & part_export
657
658 my %cdr_info;
659 foreach my $INC ( @INC ) {
660   warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
661   foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
662     warn "attempting to load CDR format info from $file\n" if $DEBUG;
663     $file =~ /\/(\w+)\.pm$/ or do {
664       warn "unrecognized file in $INC/FS/cdr/: $file\n";
665       next;
666     };
667     my $mod = $1;
668     my $info = eval "use FS::cdr::$mod; ".
669                     "\\%FS::cdr::$mod\::info;";
670     if ( $@ ) {
671       die "error using FS::cdr::$mod (skipping): $@\n" if $@;
672       next;
673     }
674     unless ( keys %$info ) {
675       warn "no %info hash found in FS::cdr::$mod, skipping\n";
676       next;
677     }
678     warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
679     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
680       warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
681       next;
682     }
683     $cdr_info{$mod} = $info;
684   }
685 }
686
687 tie my %import_formats, 'Tie::IxHash',
688   map  { $_ => $cdr_info{$_}->{'name'} }
689   sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
690   grep { exists($cdr_info{$_}->{'import_fields'}) }
691   keys %cdr_info;
692
693 sub import_formats {
694   %import_formats;
695 }
696
697 sub _cdr_min_parser_maker {
698   my $field = shift;
699   my @fields = ref($field) ? @$field : ($field);
700   @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
701   return sub {
702     my( $cdr, $min ) = @_;
703     my $sec = eval { _cdr_min_parse($min) };
704     die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
705     $cdr->$_($sec) foreach @fields;
706   };
707 }
708
709 sub _cdr_min_parse {
710   my $min = shift;
711   sprintf('%.0f', $min * 60 );
712 }
713
714 sub _cdr_date_parser_maker {
715   my $field = shift;
716   my %options = @_;
717   my @fields = ref($field) ? @$field : ($field);
718   return sub {
719     my( $cdr, $datestring ) = @_;
720     my $unixdate = eval { _cdr_date_parse($datestring, %options) };
721     die "error parsing date for @fields from $datestring: $@\n" if $@;
722     $cdr->$_($unixdate) foreach @fields;
723   };
724 }
725
726 sub _cdr_date_parse {
727   my $date = shift;
728   my %options = @_;
729
730   return '' unless length($date); #that's okay, it becomes NULL
731   return '' if $date eq 'NA'; #sansay
732
733   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 ) {
734     my $time = str2time($date);
735     return $time if $time > 100000; #just in case
736   }
737
738   my($year, $mon, $day, $hour, $min, $sec);
739
740   #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
741   #taqua  #2007-10-31 08:57:24.113000000
742
743   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|$)/ ) {
744     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
745   } 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|$)/ ) {
746     ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
747   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
748     # broadsoft: 20081223201938.314
749     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
750   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/ ) {
751     # WIP: 20100329121420
752     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
753   } else {
754      die "unparsable date: $date"; #maybe we shouldn't die...
755   }
756
757   return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
758             && $hour == 0 && $min == 0 && $sec == 0;
759
760   if ($options{gmt}) {
761     timegm($sec, $min, $hour, $day, $mon-1, $year);
762   } else {
763     timelocal($sec, $min, $hour, $day, $mon-1, $year);
764   }
765 }
766
767 =item batch_import HASHREF
768
769 Imports CDR records.  Available options are:
770
771 =over 4
772
773 =item file
774
775 Filename
776
777 =item format
778
779 =item params
780
781 Hash reference of preset fields, typically cdrbatch
782
783 =item empty_ok
784
785 Set true to prevent throwing an error on empty imports
786
787 =back
788
789 =cut
790
791 my %import_options = (
792   'table'         => 'cdr',
793
794   'batch_keycol'  => 'cdrbatchnum',
795   'batch_table'   => 'cdr_batch',
796   'batch_namecol' => 'cdrbatch',
797
798   'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
799                      keys %cdr_info
800                },
801
802                           #drop the || 'csv' to allow auto xls for csv types?
803   'format_types' => { map { $_ => ( lc($cdr_info{$_}->{'type'}) || 'csv' ); }
804                           keys %cdr_info
805                     },
806
807   'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
808                             keys %cdr_info
809                       },
810
811   'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
812                               keys %cdr_info
813                         },
814
815   'format_fixedlength_formats' =>
816     { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
817           keys %cdr_info
818     },
819 );
820
821 sub _import_options {
822   \%import_options;
823 }
824
825 sub batch_import {
826   my $opt = shift;
827
828   my $iopt = _import_options;
829   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
830
831   FS::Record::batch_import( $opt );
832
833 }
834
835 =item process_batch_import
836
837 =cut
838
839 sub process_batch_import {
840   my $job = shift;
841
842   my $opt = _import_options;
843 #  $opt->{'params'} = [ 'format', 'cdrbatch' ];
844
845   FS::Record::process_batch_import( $job, $opt, @_ );
846
847 }
848 #  if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
849 #    @columns = map { s/^ +//; $_; } @columns;
850 #  }
851
852 # _ upgrade_data
853 #
854 # Used by FS::Upgrade to migrate to a new database.
855
856 sub _upgrade_data {
857   my ($class, %opts) = @_;
858
859   warn "$me upgrading $class\n" if $DEBUG;
860
861   my $sth = dbh->prepare(
862     'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
863   ) or die dbh->errstr;
864
865   $sth->execute or die $sth->errstr;
866
867   my %cdrbatchnum = ();
868   while (my $row = $sth->fetchrow_arrayref) {
869     my $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
870     my $error = $cdr_batch->insert;
871     die $error if $error;
872     $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
873   }
874
875   $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
876
877   foreach my $cdrbatch (keys %cdrbatchnum) {
878     $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
879   }
880
881 }
882
883 =back
884
885 =head1 BUGS
886
887 =head1 SEE ALSO
888
889 L<FS::Record>, schema.html from the base documentation.
890
891 =cut
892
893 1;
894