respect date_format w/CDRs
[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 %export_formats = ();
530 sub export_formats {
531   #my $self = shift;
532
533   return %export_formats if keys %export_formats;
534
535   my $conf = new FS::Conf;
536   my $date_format = $conf->config('date_format') || '%m/%d/%Y';
537
538   my $duration_sub = sub {
539     my($cdr, %opt) = @_;
540     if ( $opt{minutes} ) {
541       $opt{minutes}. ( $opt{granularity} ? 'm' : ' call' );
542     } else {
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';
546     }
547   };
548
549   %export_formats = (
550     'simple' => [
551       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
552       sub { time2str('%r', shift->calldate_unix ) },   #TIME
553       'userfield',                                     #USER
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
558     ],
559     'simple2' => [
560       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
561       sub { time2str('%r', shift->calldate_unix ) },   #TIME
562       #'userfield',                                     #USER
563       'src',                                           #called from
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
568     ],
569     'default' => [
570
571       #DATE
572       sub { time2str($date_format, shift->calldate_unix ) },
573             # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
574
575       #TIME
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
578
579       #DEST ("Number")
580       sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
581
582       #REGIONNAME ("Destination")
583       sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
584
585       #DURATION
586       $duration_sub,
587
588       #PRICE
589       sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; },
590
591     ],
592   );
593   $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
594   $export_formats{'accountcode_default'} =
595     [ @{ $export_formats{'default'} }[0,1],
596       'accountcode',
597       @{ $export_formats{'default'} }[2..5],
598     ];
599
600   %export_formats
601 }
602
603 sub downstream_csv {
604   my( $self, %opt ) = @_;
605
606   my $format = $opt{'format'};
607   my %formats = $self->export_formats;
608   return "Unknown format $format" unless exists $formats{$format};
609
610   #my $conf = new FS::Conf;
611   #$opt{'money_char'} ||= $conf->config('money_char') || '$';
612   $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
613
614   eval "use Text::CSV_XS;";
615   die $@ if $@;
616   my $csv = new Text::CSV_XS;
617
618   my @columns =
619     map {
620           ref($_) ? &{$_}($self, %opt) : $self->$_();
621         }
622     @{ $formats{$format} };
623
624   my $status = $csv->combine(@columns);
625   die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
626     unless $status;
627
628   $csv->string;
629
630 }
631
632 =back
633
634 =head1 CLASS METHODS
635
636 =over 4
637
638 =item invoice_formats
639
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.
642
643 =cut
644
645 sub invoice_formats {
646   map { ($_ => $export_names{$_}->{'name'}) }
647     grep { $export_names{$_}->{'invoice_header'} }
648     keys %export_names;
649 }
650
651 =item invoice_header FORMAT
652
653 Returns a scalar containing the CSV column header for invoice format FORMAT.
654
655 =cut
656
657 sub invoice_header {
658   my $format = shift;
659   $export_names{$format}->{'invoice_header'};
660 }
661
662 =item import_formats
663
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.
666
667 =cut
668
669 #false laziness w/part_pkg & part_export
670
671 my %cdr_info;
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";
678       next;
679     };
680     my $mod = $1;
681     my $info = eval "use FS::cdr::$mod; ".
682                     "\\%FS::cdr::$mod\::info;";
683     if ( $@ ) {
684       die "error using FS::cdr::$mod (skipping): $@\n" if $@;
685       next;
686     }
687     unless ( keys %$info ) {
688       warn "no %info hash found in FS::cdr::$mod, skipping\n";
689       next;
690     }
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;
694       next;
695     }
696     $cdr_info{$mod} = $info;
697   }
698 }
699
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'}) }
704   keys %cdr_info;
705
706 sub import_formats {
707   %import_formats;
708 }
709
710 sub _cdr_min_parser_maker {
711   my $field = shift;
712   my @fields = ref($field) ? @$field : ($field);
713   @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
714   return sub {
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;
719   };
720 }
721
722 sub _cdr_min_parse {
723   my $min = shift;
724   sprintf('%.0f', $min * 60 );
725 }
726
727 sub _cdr_date_parser_maker {
728   my $field = shift;
729   my %options = @_;
730   my @fields = ref($field) ? @$field : ($field);
731   return sub {
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;
736   };
737 }
738
739 sub _cdr_date_parse {
740   my $date = shift;
741   my %options = @_;
742
743   return '' unless length($date); #that's okay, it becomes NULL
744   return '' if $date eq 'NA'; #sansay
745
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
749   }
750
751   my($year, $mon, $day, $hour, $min, $sec);
752
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
755
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 );
766   } else {
767      die "unparsable date: $date"; #maybe we shouldn't die...
768   }
769
770   return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
771             && $hour == 0 && $min == 0 && $sec == 0;
772
773   if ($options{gmt}) {
774     timegm($sec, $min, $hour, $day, $mon-1, $year);
775   } else {
776     timelocal($sec, $min, $hour, $day, $mon-1, $year);
777   }
778 }
779
780 =item batch_import HASHREF
781
782 Imports CDR records.  Available options are:
783
784 =over 4
785
786 =item file
787
788 Filename
789
790 =item format
791
792 =item params
793
794 Hash reference of preset fields, typically cdrbatch
795
796 =item empty_ok
797
798 Set true to prevent throwing an error on empty imports
799
800 =back
801
802 =cut
803
804 my %import_options = (
805   'table'         => 'cdr',
806
807   'batch_keycol'  => 'cdrbatchnum',
808   'batch_table'   => 'cdr_batch',
809   'batch_namecol' => 'cdrbatch',
810
811   'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
812                      keys %cdr_info
813                },
814
815                           #drop the || 'csv' to allow auto xls for csv types?
816   'format_types' => { map { $_ => ( lc($cdr_info{$_}->{'type'}) || 'csv' ); }
817                           keys %cdr_info
818                     },
819
820   'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
821                             keys %cdr_info
822                       },
823
824   'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
825                               keys %cdr_info
826                         },
827
828   'format_fixedlength_formats' =>
829     { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
830           keys %cdr_info
831     },
832 );
833
834 sub _import_options {
835   \%import_options;
836 }
837
838 sub batch_import {
839   my $opt = shift;
840
841   my $iopt = _import_options;
842   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
843
844   FS::Record::batch_import( $opt );
845
846 }
847
848 =item process_batch_import
849
850 =cut
851
852 sub process_batch_import {
853   my $job = shift;
854
855   my $opt = _import_options;
856 #  $opt->{'params'} = [ 'format', 'cdrbatch' ];
857
858   FS::Record::process_batch_import( $job, $opt, @_ );
859
860 }
861 #  if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
862 #    @columns = map { s/^ +//; $_; } @columns;
863 #  }
864
865 # _ upgrade_data
866 #
867 # Used by FS::Upgrade to migrate to a new database.
868
869 sub _upgrade_data {
870   my ($class, %opts) = @_;
871
872   warn "$me upgrading $class\n" if $DEBUG;
873
874   my $sth = dbh->prepare(
875     'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
876   ) or die dbh->errstr;
877
878   $sth->execute or die $sth->errstr;
879
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;
886   }
887
888   $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
889
890   foreach my $cdrbatch (keys %cdrbatchnum) {
891     $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
892   }
893
894 }
895
896 =back
897
898 =head1 BUGS
899
900 =head1 SEE ALSO
901
902 L<FS::Record>, schema.html from the base documentation.
903
904 =cut
905
906 1;
907