parse text startdate and enddate in CDRs, RT#8906
[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   for my $f ( grep { $self->$_ =~ /[a-z ]/i } qw( startdate enddate ) ) {
289     $self->$f( str2time($self->$f) );
290   }
291
292   $self->calldate( $self->startdate_sql )
293     if !$self->calldate && $self->startdate;
294
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  );
299   }
300   if ( $self->billsec eq '' && $self->enddate && $self->answerdate ) {
301     $self->billsec(  $self->enddate - $self->answerdate );
302   } 
303
304   $self->set_charged_party;
305
306   #check the foreign keys even?
307   #do we want to outright *reject* the CDR?
308   my $error =
309        $self->ut_numbern('acctid')
310
311   #add a config option to turn these back on if someone needs 'em
312   #
313   #  #Usage = 1, S&E = 7, OC&C = 8
314   #  || $self->ut_foreign_keyn('cdrtypenum',  'cdr_type',     'cdrtypenum' )
315   #
316   #  #the big list in appendix 2
317   #  || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
318   #
319   #  # Telstra =1, Optus = 2, RSL COM = 3
320   #  || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
321   ;
322   return $error if $error;
323
324   $self->SUPER::check;
325 }
326
327 =item is_tollfree
328
329   Returns true when the cdr represents a toll free number and false otherwise.
330
331 =cut
332
333 sub is_tollfree {
334   my $self = shift;
335   ( $self->dst =~ /^(\+?1)?8(8|([02-7])\3)/ ) ? 1 : 0;
336 }
337
338 =item set_charged_party
339
340 If the charged_party field is already set, does nothing.  Otherwise:
341
342 If the cdr-charged_party-accountcode config option is enabled, sets the
343 charged_party to the accountcode.
344
345 Otherwise sets the charged_party normally: to the src field in most cases,
346 or to the dst field if it is a toll free number.
347
348 =cut
349
350 sub set_charged_party {
351   my $self = shift;
352
353   my $conf = new FS::Conf;
354
355   unless ( $self->charged_party ) {
356
357     if ( $conf->exists('cdr-charged_party-accountcode') && $self->accountcode ){
358
359       my $charged_party = $self->accountcode;
360       $charged_party =~ s/^0+//
361         if $conf->exists('cdr-charged_party-accountcode-trim_leading_0s');
362       $self->charged_party( $charged_party );
363
364     } else {
365
366       if ( $self->is_tollfree ) {
367         $self->charged_party($self->dst);
368       } else {
369         $self->charged_party($self->src);
370       }
371
372     }
373
374   }
375
376 #  my $prefix = $conf->config('cdr-charged_party-truncate_prefix');
377 #  my $prefix_len = length($prefix);
378 #  my $trunc_len = $conf->config('cdr-charged_party-truncate_length');
379 #
380 #  $self->charged_party( substr($self->charged_party, 0, $trunc_len) )
381 #    if $prefix_len && $trunc_len
382 #    && substr($self->charged_party, 0, $prefix_len) eq $prefix;
383
384 }
385
386 =item set_status_and_rated_price STATUS [ RATED_PRICE [ SVCNUM ] ]
387
388 Sets the status to the provided string.  If there is an error, returns the
389 error, otherwise returns false.
390
391 =cut
392
393 sub set_status_and_rated_price {
394   my($self, $status, $rated_price, $svcnum, %opt) = @_;
395   if($opt{'inbound'}) {
396     my $term = qsearchs('cdr_termination', {
397         acctid   => $self->acctid, 
398         termpart => 1 # inbound
399     });
400     my $error;
401     if($term) {
402       warn "replacing existing cdr status (".$self->acctid.")\n" if $term;
403       $error = $term->delete;
404       return $error if $error;
405     }
406     $term = FS::cdr_termination->new({
407         acctid      => $self->acctid,
408         termpart    => 1,
409         rated_price => $rated_price,
410         status      => $status,
411         svcnum      => $svcnum,
412     });
413     return $term->insert;
414   }
415   else {
416     $self->freesidestatus($status);
417     $self->rated_price($rated_price);
418     $self->svcnum($svcnum) if $svcnum;
419     return $self->replace();
420   }
421 }
422
423 =item calldate_unix 
424
425 Parses the calldate in SQL string format and returns a UNIX timestamp.
426
427 =cut
428
429 sub calldate_unix {
430   str2time(shift->calldate);
431 }
432
433 =item startdate_sql
434
435 Parses the startdate in UNIX timestamp format and returns a string in SQL
436 format.
437
438 =cut
439
440 sub startdate_sql {
441   my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
442   $mon++;
443   $year += 1900;
444   "$year-$mon-$mday $hour:$min:$sec";
445 }
446
447 =item cdr_carrier
448
449 Returns the FS::cdr_carrier object associated with this CDR, or false if no
450 carrierid is defined.
451
452 =cut
453
454 my %carrier_cache = ();
455
456 sub cdr_carrier {
457   my $self = shift;
458   return '' unless $self->carrierid;
459   $carrier_cache{$self->carrierid} ||=
460     qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
461 }
462
463 =item carriername 
464
465 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
466 no FS::cdr_carrier object is assocated with this CDR.
467
468 =cut
469
470 sub carriername {
471   my $self = shift;
472   my $cdr_carrier = $self->cdr_carrier;
473   $cdr_carrier ? $cdr_carrier->carriername : '';
474 }
475
476 =item cdr_calltype
477
478 Returns the FS::cdr_calltype object associated with this CDR, or false if no
479 calltypenum is defined.
480
481 =cut
482
483 my %calltype_cache = ();
484
485 sub cdr_calltype {
486   my $self = shift;
487   return '' unless $self->calltypenum;
488   $calltype_cache{$self->calltypenum} ||=
489     qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
490 }
491
492 =item calltypename 
493
494 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
495 no FS::cdr_calltype object is assocated with this CDR.
496
497 =cut
498
499 sub calltypename {
500   my $self = shift;
501   my $cdr_calltype = $self->cdr_calltype;
502   $cdr_calltype ? $cdr_calltype->calltypename : '';
503 }
504
505 =item downstream_csv [ OPTION => VALUE, ... ]
506
507 =cut
508
509 my %export_names = (
510   'simple'  => {
511     'name'           => 'Simple',
512     'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
513   },
514   'simple2' => {
515     'name'           => 'Simple with source',
516     'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
517                        #"Date,Time,Name,Called From,Destination,Duration,Price",
518   },
519   'default' => {
520     'name'           => 'Default',
521     'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
522   },
523   'source_default' => {
524     'name'           => 'Default with source',
525     'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
526   },
527   'accountcode_default' => {
528     'name'           => 'Default plus accountcode',
529     'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
530   },
531 );
532
533 my %export_formats = ();
534 sub export_formats {
535   #my $self = shift;
536
537   return %export_formats if keys %export_formats;
538
539   my $conf = new FS::Conf;
540   my $date_format = $conf->config('date_format') || '%m/%d/%Y';
541
542   my $duration_sub = sub {
543     my($cdr, %opt) = @_;
544     if ( $opt{minutes} ) {
545       $opt{minutes}. ( $opt{granularity} ? 'm' : ' call' );
546     } else {
547       #config if anyone really wants decimal minutes back
548       #sprintf('%.2fm', $cdr->billsec / 60 );
549       int($cdr->billsec / 60).'m '. ($cdr->billsec % 60).'s';
550     }
551   };
552
553   %export_formats = (
554     'simple' => [
555       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
556       sub { time2str('%r', shift->calldate_unix ) },   #TIME
557       'userfield',                                     #USER
558       'dst',                                           #NUMBER_DIALED
559       $duration_sub,                                   #DURATION
560       #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
561       sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
562     ],
563     'simple2' => [
564       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
565       sub { time2str('%r', shift->calldate_unix ) },   #TIME
566       #'userfield',                                     #USER
567       'src',                                           #called from
568       'dst',                                           #NUMBER_DIALED
569       $duration_sub,                                   #DURATION
570       #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
571       sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; }, #PRICE
572     ],
573     'default' => [
574
575       #DATE
576       sub { time2str($date_format, shift->calldate_unix ) },
577             # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
578
579       #TIME
580       sub { time2str('%r', shift->calldate_unix ) },
581             # 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
582
583       #DEST ("Number")
584       sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
585
586       #REGIONNAME ("Destination")
587       sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
588
589       #DURATION
590       $duration_sub,
591
592       #PRICE
593       sub { my($cdr, %opt) = @_; $opt{money_char}. $opt{charge}; },
594
595     ],
596   );
597   $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
598   $export_formats{'accountcode_default'} =
599     [ @{ $export_formats{'default'} }[0,1],
600       'accountcode',
601       @{ $export_formats{'default'} }[2..5],
602     ];
603
604   %export_formats
605 }
606
607 sub downstream_csv {
608   my( $self, %opt ) = @_;
609
610   my $format = $opt{'format'};
611   my %formats = $self->export_formats;
612   return "Unknown format $format" unless exists $formats{$format};
613
614   #my $conf = new FS::Conf;
615   #$opt{'money_char'} ||= $conf->config('money_char') || '$';
616   $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
617
618   eval "use Text::CSV_XS;";
619   die $@ if $@;
620   my $csv = new Text::CSV_XS;
621
622   my @columns =
623     map {
624           ref($_) ? &{$_}($self, %opt) : $self->$_();
625         }
626     @{ $formats{$format} };
627
628   my $status = $csv->combine(@columns);
629   die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
630     unless $status;
631
632   $csv->string;
633
634 }
635
636 =back
637
638 =head1 CLASS METHODS
639
640 =over 4
641
642 =item invoice_formats
643
644 Returns an ordered list of key value pairs containing invoice format names
645 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
646
647 =cut
648
649 sub invoice_formats {
650   map { ($_ => $export_names{$_}->{'name'}) }
651     grep { $export_names{$_}->{'invoice_header'} }
652     keys %export_names;
653 }
654
655 =item invoice_header FORMAT
656
657 Returns a scalar containing the CSV column header for invoice format FORMAT.
658
659 =cut
660
661 sub invoice_header {
662   my $format = shift;
663   $export_names{$format}->{'invoice_header'};
664 }
665
666 =item import_formats
667
668 Returns an ordered list of key value pairs containing import format names
669 as keys (for use with batch_import) and "pretty" format names as values.
670
671 =cut
672
673 #false laziness w/part_pkg & part_export
674
675 my %cdr_info;
676 foreach my $INC ( @INC ) {
677   warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
678   foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
679     warn "attempting to load CDR format info from $file\n" if $DEBUG;
680     $file =~ /\/(\w+)\.pm$/ or do {
681       warn "unrecognized file in $INC/FS/cdr/: $file\n";
682       next;
683     };
684     my $mod = $1;
685     my $info = eval "use FS::cdr::$mod; ".
686                     "\\%FS::cdr::$mod\::info;";
687     if ( $@ ) {
688       die "error using FS::cdr::$mod (skipping): $@\n" if $@;
689       next;
690     }
691     unless ( keys %$info ) {
692       warn "no %info hash found in FS::cdr::$mod, skipping\n";
693       next;
694     }
695     warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
696     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
697       warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
698       next;
699     }
700     $cdr_info{$mod} = $info;
701   }
702 }
703
704 tie my %import_formats, 'Tie::IxHash',
705   map  { $_ => $cdr_info{$_}->{'name'} }
706   sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
707   grep { exists($cdr_info{$_}->{'import_fields'}) }
708   keys %cdr_info;
709
710 sub import_formats {
711   %import_formats;
712 }
713
714 sub _cdr_min_parser_maker {
715   my $field = shift;
716   my @fields = ref($field) ? @$field : ($field);
717   @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
718   return sub {
719     my( $cdr, $min ) = @_;
720     my $sec = eval { _cdr_min_parse($min) };
721     die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
722     $cdr->$_($sec) foreach @fields;
723   };
724 }
725
726 sub _cdr_min_parse {
727   my $min = shift;
728   sprintf('%.0f', $min * 60 );
729 }
730
731 sub _cdr_date_parser_maker {
732   my $field = shift;
733   my %options = @_;
734   my @fields = ref($field) ? @$field : ($field);
735   return sub {
736     my( $cdr, $datestring ) = @_;
737     my $unixdate = eval { _cdr_date_parse($datestring, %options) };
738     die "error parsing date for @fields from $datestring: $@\n" if $@;
739     $cdr->$_($unixdate) foreach @fields;
740   };
741 }
742
743 sub _cdr_date_parse {
744   my $date = shift;
745   my %options = @_;
746
747   return '' unless length($date); #that's okay, it becomes NULL
748   return '' if $date eq 'NA'; #sansay
749
750   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 ) {
751     my $time = str2time($date);
752     return $time if $time > 100000; #just in case
753   }
754
755   my($year, $mon, $day, $hour, $min, $sec);
756
757   #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
758   #taqua  #2007-10-31 08:57:24.113000000
759
760   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|$)/ ) {
761     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
762   } 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|$)/ ) {
763     ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
764   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
765     # broadsoft: 20081223201938.314
766     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
767   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/ ) {
768     # WIP: 20100329121420
769     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
770   } else {
771      die "unparsable date: $date"; #maybe we shouldn't die...
772   }
773
774   return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
775             && $hour == 0 && $min == 0 && $sec == 0;
776
777   if ($options{gmt}) {
778     timegm($sec, $min, $hour, $day, $mon-1, $year);
779   } else {
780     timelocal($sec, $min, $hour, $day, $mon-1, $year);
781   }
782 }
783
784 =item batch_import HASHREF
785
786 Imports CDR records.  Available options are:
787
788 =over 4
789
790 =item file
791
792 Filename
793
794 =item format
795
796 =item params
797
798 Hash reference of preset fields, typically cdrbatch
799
800 =item empty_ok
801
802 Set true to prevent throwing an error on empty imports
803
804 =back
805
806 =cut
807
808 my %import_options = (
809   'table'         => 'cdr',
810
811   'batch_keycol'  => 'cdrbatchnum',
812   'batch_table'   => 'cdr_batch',
813   'batch_namecol' => 'cdrbatch',
814
815   'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
816                      keys %cdr_info
817                },
818
819                           #drop the || 'csv' to allow auto xls for csv types?
820   'format_types' => { map { $_ => ( lc($cdr_info{$_}->{'type'}) || 'csv' ); }
821                           keys %cdr_info
822                     },
823
824   'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
825                             keys %cdr_info
826                       },
827
828   'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
829                               keys %cdr_info
830                         },
831
832   'format_fixedlength_formats' =>
833     { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
834           keys %cdr_info
835     },
836 );
837
838 sub _import_options {
839   \%import_options;
840 }
841
842 sub batch_import {
843   my $opt = shift;
844
845   my $iopt = _import_options;
846   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
847
848   FS::Record::batch_import( $opt );
849
850 }
851
852 =item process_batch_import
853
854 =cut
855
856 sub process_batch_import {
857   my $job = shift;
858
859   my $opt = _import_options;
860 #  $opt->{'params'} = [ 'format', 'cdrbatch' ];
861
862   FS::Record::process_batch_import( $job, $opt, @_ );
863
864 }
865 #  if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
866 #    @columns = map { s/^ +//; $_; } @columns;
867 #  }
868
869 # _ upgrade_data
870 #
871 # Used by FS::Upgrade to migrate to a new database.
872
873 sub _upgrade_data {
874   my ($class, %opts) = @_;
875
876   warn "$me upgrading $class\n" if $DEBUG;
877
878   my $sth = dbh->prepare(
879     'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
880   ) or die dbh->errstr;
881
882   $sth->execute or die $sth->errstr;
883
884   my %cdrbatchnum = ();
885   while (my $row = $sth->fetchrow_arrayref) {
886     my $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
887     my $error = $cdr_batch->insert;
888     die $error if $error;
889     $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
890   }
891
892   $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
893
894   foreach my $cdrbatch (keys %cdrbatchnum) {
895     $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
896   }
897
898 }
899
900 =back
901
902 =head1 BUGS
903
904 =head1 SEE ALSO
905
906 L<FS::Record>, schema.html from the base documentation.
907
908 =cut
909
910 1;
911