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