optimize CDR rating after timed rate perf regression, RT#15739
[freeside.git] / FS / FS / cdr.pm
1 package FS::cdr;
2
3 use strict;
4 use vars qw( @ISA @EXPORT_OK $DEBUG $me
5              $conf $cdr_prerate %cdr_prerate_cdrtypenums
6            );
7 use Exporter;
8 use List::Util qw(first min);
9 use Tie::IxHash;
10 use Date::Parse;
11 use Date::Format;
12 use Time::Local;
13 use List::Util qw( first min );
14 use FS::UID qw( dbh );
15 use FS::Conf;
16 use FS::Record qw( qsearch qsearchs );
17 use FS::cdr_type;
18 use FS::cdr_calltype;
19 use FS::cdr_carrier;
20 use FS::cdr_batch;
21 use FS::cdr_termination;
22 use FS::rate;
23 use FS::rate_prefix;
24 use FS::rate_detail;
25
26 @ISA = qw(FS::Record);
27 @EXPORT_OK = qw( _cdr_date_parser_maker _cdr_min_parser_maker );
28
29 $DEBUG = 0;
30 $me = '[FS::cdr]';
31
32 #ask FS::UID to run this stuff for us later
33 FS::UID->install_callback( sub { 
34   $conf = new FS::Conf;
35
36   my @cdr_prerate_cdrtypenums;
37   $cdr_prerate = $conf->exists('cdr-prerate');
38   @cdr_prerate_cdrtypenums = $conf->config('cdr-prerate-cdrtypenums')
39     if $cdr_prerate;
40   %cdr_prerate_cdrtypenums = map { $_=>1 } @cdr_prerate_cdrtypenums;
41 });
42
43 =head1 NAME
44
45 FS::cdr - Object methods for cdr records
46
47 =head1 SYNOPSIS
48
49   use FS::cdr;
50
51   $record = new FS::cdr \%hash;
52   $record = new FS::cdr { 'column' => 'value' };
53
54   $error = $record->insert;
55
56   $error = $new_record->replace($old_record);
57
58   $error = $record->delete;
59
60   $error = $record->check;
61
62 =head1 DESCRIPTION
63
64 An FS::cdr object represents an Call Data Record, typically from a telephony
65 system or provider of some sort.  FS::cdr inherits from FS::Record.  The
66 following fields are currently supported:
67
68 =over 4
69
70 =item acctid - primary key
71
72 =item calldate - Call timestamp (SQL timestamp)
73
74 =item clid - Caller*ID with text
75
76 =item src - Caller*ID number / Source number
77
78 =item dst - Destination extension
79
80 =item dcontext - Destination context
81
82 =item channel - Channel used
83
84 =item dstchannel - Destination channel if appropriate
85
86 =item lastapp - Last application if appropriate
87
88 =item lastdata - Last application data
89
90 =item startdate - Start of call (UNIX-style integer timestamp)
91
92 =item answerdate - Answer time of call (UNIX-style integer timestamp)
93
94 =item enddate - End time of call (UNIX-style integer timestamp)
95
96 =item duration - Total time in system, in seconds
97
98 =item billsec - Total time call is up, in seconds
99
100 =item disposition - What happened to the call: ANSWERED, NO ANSWER, BUSY 
101
102 =item amaflags - What flags to use: BILL, IGNORE etc, specified on a per channel basis like accountcode. 
103
104 =cut
105
106   #ignore the "omit" and "documentation" AMAs??
107   #AMA = Automated Message Accounting. 
108   #default: Sets the system default. 
109   #omit: Do not record calls. 
110   #billing: Mark the entry for billing 
111   #documentation: Mark the entry for documentation.
112
113 =item accountcode - CDR account number to use: account
114
115 =item uniqueid - Unique channel identifier (Unitel/RSLCOM Event ID)
116
117 =item userfield - CDR user-defined field
118
119 =item cdr_type - CDR type - see L<FS::cdr_type> (Usage = 1, S&E = 7, OC&C = 8)
120
121 =item charged_party - Service number to be billed
122
123 =item upstream_currency - Wholesale currency from upstream
124
125 =item upstream_price - Wholesale price from upstream
126
127 =item upstream_rateplanid - Upstream rate plan ID
128
129 =item rated_price - Rated (or re-rated) price
130
131 =item distance - km (need units field?)
132
133 =item islocal - Local - 1, Non Local = 0
134
135 =item calltypenum - Type of call - see L<FS::cdr_calltype>
136
137 =item description - Description (cdr_type 7&8 only) (used for cust_bill_pkg.itemdesc)
138
139 =item quantity - Number of items (cdr_type 7&8 only)
140
141 =item carrierid - Upstream Carrier ID (see L<FS::cdr_carrier>) 
142
143 =cut
144
145 #Telstra =1, Optus = 2, RSL COM = 3
146
147 =item upstream_rateid - Upstream Rate ID
148
149 =item svcnum - Link to customer service (see L<FS::cust_svc>)
150
151 =item freesidestatus - NULL, processing-tiered, rated, done
152
153 =item freesiderewritestatus - NULL, done, skipped
154
155 =item cdrbatch
156
157 =back
158
159 =head1 METHODS
160
161 =over 4
162
163 =item new HASHREF
164
165 Creates a new CDR.  To add the CDR to the database, see L<"insert">.
166
167 Note that this stores the hash reference, not a distinct copy of the hash it
168 points to.  You can ask the object for a copy with the I<hash> method.
169
170 =cut
171
172 # the new method can be inherited from FS::Record, if a table method is defined
173
174 sub table { 'cdr'; }
175
176 sub table_info {
177   {
178     'fields' => {
179 #XXX fill in some (more) nice names
180         #'acctid'                => '',
181         'calldate'              => 'Call date',
182         'clid'                  => 'Caller ID',
183         'src'                   => 'Source',
184         'dst'                   => 'Destination',
185         'dcontext'              => 'Dest. context',
186         'channel'               => 'Channel',
187         'dstchannel'            => 'Destination channel',
188         #'lastapp'               => '',
189         #'lastdata'              => '',
190         'startdate'             => 'Start date',
191         'answerdate'            => 'Answer date',
192         'enddate'               => 'End date',
193         'duration'              => 'Duration',
194         'billsec'               => 'Billable seconds',
195         'disposition'           => 'Disposition',
196         'amaflags'              => 'AMA flags',
197         'accountcode'           => 'Account code',
198         #'uniqueid'              => '',
199         'userfield'             => 'User field',
200         #'cdrtypenum'            => '',
201         'charged_party'         => 'Charged party',
202         #'upstream_currency'     => '',
203         'upstream_price'        => 'Upstream price',
204         #'upstream_rateplanid'   => '',
205         #'ratedetailnum'         => '',
206         'rated_price'           => 'Rated price',
207         #'distance'              => '',
208         #'islocal'               => '',
209         #'calltypenum'           => '',
210         #'description'           => '',
211         #'quantity'              => '',
212         'carrierid'             => 'Carrier ID',
213         #'upstream_rateid'       => '',
214         'svcnum'                => 'Freeside service',
215         'freesidestatus'        => 'Freeside status',
216         'freesiderewritestatus' => 'Freeside rewrite status',
217         'cdrbatch'              => 'Legacy batch',
218         'cdrbatchnum'           => 'Batch',
219     },
220
221   };
222
223 }
224
225 =item insert
226
227 Adds this record to the database.  If there is an error, returns the error,
228 otherwise returns false.
229
230 =cut
231
232 # the insert method can be inherited from FS::Record
233
234 =item delete
235
236 Delete this record from the database.
237
238 =cut
239
240 # the delete method can be inherited from FS::Record
241
242 =item replace OLD_RECORD
243
244 Replaces the OLD_RECORD with this one in the database.  If there is an error,
245 returns the error, otherwise returns false.
246
247 =cut
248
249 # the replace method can be inherited from FS::Record
250
251 =item check
252
253 Checks all fields to make sure this is a valid CDR.  If there is
254 an error, returns the error, otherwise returns false.  Called by the insert
255 and replace methods.
256
257 Note: Unlike most types of records, we don't want to "reject" a CDR and we want
258 to process them as quickly as possible, so we allow the database to check most
259 of the data.
260
261 =cut
262
263 sub check {
264   my $self = shift;
265
266 # we don't want to "reject" a CDR like other sorts of input...
267 #  my $error = 
268 #    $self->ut_numbern('acctid')
269 ##    || $self->ut_('calldate')
270 #    || $self->ut_text('clid')
271 #    || $self->ut_text('src')
272 #    || $self->ut_text('dst')
273 #    || $self->ut_text('dcontext')
274 #    || $self->ut_text('channel')
275 #    || $self->ut_text('dstchannel')
276 #    || $self->ut_text('lastapp')
277 #    || $self->ut_text('lastdata')
278 #    || $self->ut_numbern('startdate')
279 #    || $self->ut_numbern('answerdate')
280 #    || $self->ut_numbern('enddate')
281 #    || $self->ut_number('duration')
282 #    || $self->ut_number('billsec')
283 #    || $self->ut_text('disposition')
284 #    || $self->ut_number('amaflags')
285 #    || $self->ut_text('accountcode')
286 #    || $self->ut_text('uniqueid')
287 #    || $self->ut_text('userfield')
288 #    || $self->ut_numbern('cdrtypenum')
289 #    || $self->ut_textn('charged_party')
290 ##    || $self->ut_n('upstream_currency')
291 ##    || $self->ut_n('upstream_price')
292 #    || $self->ut_numbern('upstream_rateplanid')
293 ##    || $self->ut_n('distance')
294 #    || $self->ut_numbern('islocal')
295 #    || $self->ut_numbern('calltypenum')
296 #    || $self->ut_textn('description')
297 #    || $self->ut_numbern('quantity')
298 #    || $self->ut_numbern('carrierid')
299 #    || $self->ut_numbern('upstream_rateid')
300 #    || $self->ut_numbern('svcnum')
301 #    || $self->ut_textn('freesidestatus')
302 #    || $self->ut_textn('freesiderewritestatus')
303 #  ;
304 #  return $error if $error;
305
306   for my $f ( grep { $self->$_ =~ /\D/ } qw(startdate answerdate enddate)){
307     $self->$f( str2time($self->$f) );
308   }
309
310   $self->calldate( $self->startdate_sql )
311     if !$self->calldate && $self->startdate;
312
313   #was just for $format eq 'taqua' but can't see the harm... add something to
314   #disable if it becomes a problem
315   if ( $self->duration eq '' && $self->enddate && $self->startdate ) {
316     $self->duration( $self->enddate - $self->startdate  );
317   }
318   if ( $self->billsec eq '' && $self->enddate && $self->answerdate ) {
319     $self->billsec(  $self->enddate - $self->answerdate );
320   } 
321
322   $self->set_charged_party;
323
324   #check the foreign keys even?
325   #do we want to outright *reject* the CDR?
326   my $error =
327        $self->ut_numbern('acctid')
328
329   #add a config option to turn these back on if someone needs 'em
330   #
331   #  #Usage = 1, S&E = 7, OC&C = 8
332   #  || $self->ut_foreign_keyn('cdrtypenum',  'cdr_type',     'cdrtypenum' )
333   #
334   #  #the big list in appendix 2
335   #  || $self->ut_foreign_keyn('calltypenum', 'cdr_calltype', 'calltypenum' )
336   #
337   #  # Telstra =1, Optus = 2, RSL COM = 3
338   #  || $self->ut_foreign_keyn('carrierid', 'cdr_carrier', 'carrierid' )
339   ;
340   return $error if $error;
341
342   $self->SUPER::check;
343 }
344
345 =item is_tollfree [ COLUMN ]
346
347 Returns true when the cdr represents a toll free number and false otherwise.
348
349 By default, inspects the dst field, but an optional column name can be passed
350 to inspect other field.
351
352 =cut
353
354 sub is_tollfree {
355   my $self = shift;
356   my $field = scalar(@_) ? shift : 'dst';
357   ( $self->$field() =~ /^(\+?1)?8(8|([02-7])\3)/ ) ? 1 : 0;
358 }
359
360 =item set_charged_party
361
362 If the charged_party field is already set, does nothing.  Otherwise:
363
364 If the cdr-charged_party-accountcode config option is enabled, sets the
365 charged_party to the accountcode.
366
367 Otherwise sets the charged_party normally: to the src field in most cases,
368 or to the dst field if it is a toll free number.
369
370 =cut
371
372 sub set_charged_party {
373   my $self = shift;
374
375   my $conf = new FS::Conf;
376
377   unless ( $self->charged_party ) {
378
379     if ( $conf->exists('cdr-charged_party-accountcode') && $self->accountcode ){
380
381       my $charged_party = $self->accountcode;
382       $charged_party =~ s/^0+//
383         if $conf->exists('cdr-charged_party-accountcode-trim_leading_0s');
384       $self->charged_party( $charged_party );
385
386     } elsif ( $conf->exists('cdr-charged_party-field') ) {
387
388       my $field = $conf->config('cdr-charged_party-field');
389       $self->charged_party( $self->$field() );
390
391     } else {
392
393       if ( $self->is_tollfree ) {
394         $self->charged_party($self->dst);
395       } else {
396         $self->charged_party($self->src);
397       }
398
399     }
400
401   }
402
403 #  my $prefix = $conf->config('cdr-charged_party-truncate_prefix');
404 #  my $prefix_len = length($prefix);
405 #  my $trunc_len = $conf->config('cdr-charged_party-truncate_length');
406 #
407 #  $self->charged_party( substr($self->charged_party, 0, $trunc_len) )
408 #    if $prefix_len && $trunc_len
409 #    && substr($self->charged_party, 0, $prefix_len) eq $prefix;
410
411 }
412
413 =item set_status STATUS
414
415 Sets the status to the provided string.  If there is an error, returns the
416 error, otherwise returns false.
417
418 =cut
419
420 sub set_status {
421   my($self, $status) = @_;
422   $self->freesidestatus($status);
423   $self->replace;
424 }
425
426 =item set_status_and_rated_price STATUS RATED_PRICE [ SVCNUM [ OPTION => VALUE ... ] ]
427
428 Sets the status and rated price.
429
430 Available options are: inbound, rated_pretty_dst, rated_regionname,
431 rated_seconds, rated_minutes, rated_granularity, rated_ratedetailnum,
432 rated_classnum, rated_ratename.
433
434 If there is an error, returns the error, otherwise returns false.
435
436 =cut
437
438 sub set_status_and_rated_price {
439   my($self, $status, $rated_price, $svcnum, %opt) = @_;
440
441   if ($opt{'inbound'}) {
442
443     my $term = $self->cdr_termination( 1 ); #1: inbound
444     my $error;
445     if ( $term ) {
446       warn "replacing existing cdr status (".$self->acctid.")\n" if $term;
447       $error = $term->delete;
448       return $error if $error;
449     }
450     $term = FS::cdr_termination->new({
451         acctid      => $self->acctid,
452         termpart    => 1,
453         rated_price => $rated_price,
454         status      => $status,
455     });
456     $term->rated_seconds($opt{rated_seconds}) if exists($opt{rated_seconds});
457     $term->rated_minutes($opt{rated_minutes}) if exists($opt{rated_minutes});
458     $term->svcnum($svcnum) if $svcnum;
459     return $term->insert;
460
461   } else {
462
463     $self->freesidestatus($status);
464     $self->rated_price($rated_price);
465     $self->$_($opt{$_})
466       foreach grep exists($opt{$_}), map "rated_$_",
467         qw( pretty_dst regionname seconds minutes granularity
468             ratedetailnum classnum ratename );
469     $self->svcnum($svcnum) if $svcnum;
470     return $self->replace();
471
472   }
473 }
474
475 =item rate [ OPTION => VALUE ... ]
476
477 Rates this CDR according and sets the status to 'rated'.
478
479 Available options are: part_pkg, svcnum, single_price_included_minutes, region_group, region_group_included_minutes.
480
481 part_pkg is required.
482
483 If svcnum is specified, will also associate this CDR with the specified svcnum.
484
485 single_price_included_minutes is requried for single_price price plans
486 (otherwise unused/ignored).  It should be set to a scalar reference of the
487 number of included minutes and will be decremented by the rated minutes of this
488 CDR.
489
490 region_group_included_minutes is required for prefix price plans which have
491 included minutes (otherwise unused/ignored).  It should be set to a scalar
492 reference of the number of included minutes and will be decremented by the
493 rated minutes of this CDR.
494
495 region_group_included_minutes_hashref is required for prefix price plans which
496 have included minues (otehrwise unused/ignored).  It should be set to an empty
497 hashref at the start of a month's rating and then preserved across CDRs.
498
499 =cut
500
501 sub rate {
502   my( $self, %opt ) = @_;
503   my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
504
505   if ( $DEBUG > 1 ) {
506     warn "rating CDR $self\n".
507          join('', map { "  $_ => ". $self->{$_}. "\n" } keys %$self );
508   }
509
510   my $rating_method = $part_pkg->option_cacheable('rating_method') || 'prefix';
511   my $method = "rate_$rating_method";
512   $self->$method(%opt);
513 }
514
515 #here?
516 our %interval_cache = (); # for timed rates
517
518 sub rate_prefix {
519   my( $self, %opt ) = @_;
520   my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
521
522   my $da_rewrote = 0;
523   # this will result in those CDRs being marked as done... is that 
524   # what we want?
525   my @dirass = ();
526   if ( $part_pkg->option_cacheable('411_rewrite') ) {
527     my $dirass = $part_pkg->option_cacheable('411_rewrite');
528     $dirass =~ s/\s//g;
529     @dirass = split(',', $dirass);
530   }
531
532   if ( length($self->dst) && grep { $self->dst eq $_ } @dirass ) {
533     $self->dst('411');
534     $da_rewrote = 1;
535   }
536
537   my $reason = $part_pkg->check_chargable( $self,
538                                            'da_rewrote'   => $da_rewrote,
539                                          );
540   if ( $reason ) {
541     warn "not charging for CDR ($reason)\n" if $DEBUG;
542     return $self->set_status_and_rated_price( 'rated',
543                                               0,
544                                               $opt{'svcnum'},
545                                             );
546   }
547
548     
549   ###
550   # look up rate details based on called station id
551   # (or calling station id for toll free calls)
552   ###
553
554   my( $to_or_from, $number );
555   if ( $self->is_tollfree && ! $part_pkg->option_cacheable('disable_tollfree') )
556   { #tollfree call
557     $to_or_from = 'from';
558     $number = $self->src;
559   } else { #regular call
560     $to_or_from = 'to';
561     $number = $self->dst;
562   }
563
564   warn "parsing call $to_or_from $number\n" if $DEBUG;
565
566   #remove non-phone# stuff and whitespace
567   $number =~ s/\s//g;
568 #          my $proto = '';
569 #          $dest =~ s/^(\w+):// and $proto = $1; #sip:
570 #          my $siphost = '';
571 #          $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
572
573   #determine the country code
574   my $intl = $part_pkg->option_cacheable('international_prefix') || '011';
575   my $countrycode = '';
576   if (    $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
577        || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
578      )
579   {
580
581     my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
582     #first look for 1 digit country code
583     if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
584       $countrycode = $one;
585       $number = $u1.$u2.$rest;
586     } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
587       $countrycode = $two;
588       $number = $u2.$rest;
589     } else { #3 digit country code
590       $countrycode = $three;
591       $number = $rest;
592     }
593
594   } else {
595     my $domestic_prefix = $part_pkg->option_cacheable('domestic_prefix');
596     $countrycode = length($domestic_prefix) ? $domestic_prefix : '1';
597     $number =~ s/^$countrycode//;# if length($number) > 10;
598   }
599
600   warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
601   my $pretty_dst = "+$countrycode $number";
602   #asterisks here causes inserting the detail to barf, so:
603   $pretty_dst =~ s/\*//g;
604
605   my $eff_ratenum = $self->is_tollfree('accountcode')
606     ? $part_pkg->option_cacheable('accountcode_tollfree_ratenum')
607     : '';
608
609   my $ratename = '';
610   my $intrastate_ratenum = $part_pkg->option_cacheable('intrastate_ratenum');
611   if ( $intrastate_ratenum && !$self->is_tollfree ) {
612     $ratename = 'Interstate'; #until proven otherwise
613     # this is relatively easy only because:
614     # -assume all numbers are valid NANP numbers NOT in a fully-qualified format
615     # -disregard toll-free
616     # -disregard private or unknown numbers
617     # -there is exactly one record in rate_prefix for a given NPANXX
618     # -default to interstate if we can't find one or both of the prefixes
619     my $dstprefix = $self->dst;
620     $dstprefix =~ /^(\d{6})/;
621     $dstprefix = qsearchs('rate_prefix', {   'countrycode' => '1', 
622                                                 'npa' => $1, 
623                                          }) || '';
624     my $srcprefix = $self->src;
625     $srcprefix =~ /^(\d{6})/;
626     $srcprefix = qsearchs('rate_prefix', {   'countrycode' => '1',
627                                              'npa' => $1, 
628                                          }) || '';
629     if ($srcprefix && $dstprefix
630         && $srcprefix->state && $dstprefix->state
631         && $srcprefix->state eq $dstprefix->state) {
632       $eff_ratenum = $intrastate_ratenum;
633       $ratename = 'Intrastate'; # XXX possibly just use the ratename?
634     }
635   }
636
637   $eff_ratenum ||= $part_pkg->option_cacheable('ratenum');
638   my $rate = qsearchs('rate', { 'ratenum' => $eff_ratenum })
639     or die "ratenum $eff_ratenum not found!";
640
641   my @ltime = localtime($self->startdate);
642   my $weektime = $ltime[0] + 
643                  $ltime[1]*60 +   #minutes
644                  $ltime[2]*3600 + #hours
645                  $ltime[6]*86400; #days since sunday
646   # if there's no timed rate_detail for this time/region combination,
647   # dest_detail returns the default.  There may still be a timed rate 
648   # that applies after the starttime of the call, so be careful...
649   my $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
650                                          'phonenum'    => $number,
651                                          'weektime'    => $weektime,
652                                          'cdrtypenum'  => $self->cdrtypenum,
653                                       });
654
655   unless ( $rate_detail ) {
656
657     if ( $part_pkg->option_cacheable('ignore_unrateable') ) {
658
659       if ( $part_pkg->option_cacheable('ignore_unrateable') == 2 ) {
660         # mark the CDR as unrateable
661         return $self->set_status_and_rated_price(
662           'failed',
663           '',
664           $opt{'svcnum'},
665         );
666       } elsif ( $part_pkg->option_cacheable('ignore_unrateable') == 1 ) {
667         # warn and continue
668         warn "no rate_detail found for CDR.acctid: ". $self->acctid.
669              "; skipping\n";
670         return '';
671
672       } else {
673         die "unknown ignore_unrateable, pkgpart ". $part_pkg->pkgpart;
674       }
675
676     } else {
677
678       die "FATAL: no rate_detail found in ".
679           $rate->ratenum. ":". $rate->ratename. " rate plan ".
680           "for +$countrycode $number (CDR acctid ". $self->acctid. "); ".
681           "add a rate or set ignore_unrateable flag on the package def\n";
682     }
683
684   }
685
686   my $rate_region = $rate_detail->dest_region;
687   my $regionnum = $rate_region->regionnum;
688   warn "  found rate for regionnum $regionnum ".
689        "and rate detail $rate_detail\n"
690     if $DEBUG;
691
692   if ( !exists($interval_cache{$regionnum}) ) {
693     my @intervals = (
694       sort { $a->stime <=> $b->stime }
695         map { $_->rate_time->intervals }
696           qsearch({ 'table'     => 'rate_detail',
697                     'hashref'   => { 'ratenum' => $rate->ratenum },
698                     'extra_sql' => 'AND ratetimenum IS NOT NULL',
699                  })
700     );
701     $interval_cache{$regionnum} = \@intervals;
702     warn "  cached ".scalar(@intervals)." interval(s)\n"
703       if $DEBUG;
704   }
705
706   ###
707   # find the price and add detail to the invoice
708   ###
709
710   # About this section:
711   # We don't round _anything_ (except granularizing) 
712   # until the final $charge = sprintf("%.2f"...).
713
714   my $seconds_left = $part_pkg->option_cacheable('use_duration')
715                        ? $self->duration
716                        : $self->billsec;
717   # charge for the first (conn_sec) seconds
718   my $seconds = min($seconds_left, $rate_detail->conn_sec);
719   $seconds_left -= $seconds; 
720   $weektime     += $seconds;
721   my $charge = $rate_detail->conn_charge; 
722
723   my $etime;
724   while($seconds_left) {
725     my $ratetimenum = $rate_detail->ratetimenum; # may be empty
726
727     # find the end of the current rate interval
728     if(@{ $interval_cache{$regionnum} } == 0) {
729       # There are no timed rates in this group, so just stay 
730       # in the default rate_detail for the entire duration.
731       # Set an "end" of 1 past the end of the current call.
732       $etime = $weektime + $seconds_left + 1;
733     } 
734     elsif($ratetimenum) {
735       # This is a timed rate, so go to the etime of this interval.
736       # If it's followed by another timed rate, the stime of that 
737       # interval should match the etime of this one.
738       my $interval = $rate_detail->rate_time->contains($weektime);
739       $etime = $interval->etime;
740     }
741     else {
742       # This is a default rate, so use the stime of the next 
743       # interval in the sequence.
744       my $next_int = first { $_->stime > $weektime } 
745                       @{ $interval_cache{$regionnum} };
746       if ($next_int) {
747         $etime = $next_int->stime;
748       }
749       else {
750         # weektime is near the end of the week, so decrement 
751         # it by a full week and use the stime of the first 
752         # interval.
753         $weektime -= (3600*24*7);
754         $etime = $interval_cache{$regionnum}->[0]->stime;
755       }
756     }
757
758     my $charge_sec = min($seconds_left, $etime - $weektime);
759
760     $seconds_left -= $charge_sec;
761
762     my $included_min = $opt{'region_group_included_min_hashref'} || {};
763
764     $included_min->{$regionnum}{$ratetimenum} = $rate_detail->min_included
765       unless exists $included_min->{$regionnum}{$ratetimenum};
766
767     my $granularity = $rate_detail->sec_granularity;
768
769     my $minutes;
770     if ( $granularity ) { # charge per minute
771       # Round up to the nearest $granularity
772       if ( $charge_sec and $charge_sec % $granularity ) {
773         $charge_sec += $granularity - ($charge_sec % $granularity);
774       }
775       $minutes = $charge_sec / 60; #don't round this
776     }
777     else { # per call
778       $minutes = 1;
779       $seconds_left = 0;
780     }
781
782     $seconds += $charge_sec;
783
784     my $region_group = ($part_pkg->option_cacheable('min_included') || 0) > 0;
785
786     ${$opt{region_group_included_min}} -= $minutes 
787         if $region_group && $rate_detail->region_group;
788
789     $included_min->{$regionnum}{$ratetimenum} -= $minutes;
790     if (
791          $included_min->{$regionnum}{$ratetimenum} <= 0
792          && ( ${$opt{region_group_included_min}} <= 0
793               || ! $rate_detail->region_group
794             )
795        )
796     {
797                            #should preserve (display?) this
798       my $charge_min = 0 - $included_min->{$regionnum}{$ratetimenum};
799       $included_min->{$regionnum}{$ratetimenum} = 0;
800       $charge += ($rate_detail->min_charge * $charge_min); #still not rounded
801
802     } elsif ( ${$opt{region_group_included_min}} > 0
803               && $region_group
804               && $rate_detail->region_group 
805            )
806     {
807         $included_min->{$regionnum}{$ratetimenum} = 0 
808     }
809
810     # choose next rate_detail
811     $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
812                                         'phonenum'    => $number,
813                                         'weektime'    => $etime,
814                                         'cdrtypenum'  => $self->cdrtypenum })
815             if($seconds_left);
816     # we have now moved forward to $etime
817     $weektime = $etime;
818
819   } #while $seconds_left
820
821   # this is why we need regionnum/rate_region....
822   warn "  (rate region $rate_region)\n" if $DEBUG;
823
824   $self->set_status_and_rated_price(
825     'rated',
826     sprintf('%.2f', $charge + 0.000001), # NOW round it.
827     $opt{'svcnum'},
828     'rated_pretty_dst'    => $pretty_dst,
829     'rated_regionname'    => $rate_region->regionname,
830     'rated_seconds'       => $seconds,
831     'rated_granularity'   => $rate_detail->sec_granularity, #$granularity
832     'rated_ratedetailnum' => $rate_detail->ratedetailnum,
833     'rated_classnum'      => $rate_detail->classnum, #rated_ratedetailnum?
834     'rated_ratename'      => $ratename, #not rate_detail - Intrastate/Interstate
835   );
836
837 }
838
839 sub rate_upstream_simple {
840   my( $self, %opt ) = @_;
841
842   $self->set_status_and_rated_price(
843     'rated',
844     sprintf('%.3f', $self->upstream_price),
845     $opt{'svcnum'},
846     'rated_classnum' => $self->calltypenum,
847   );
848 }
849
850 sub rate_single_price {
851   my( $self, %opt ) = @_;
852   my $part_pkg = $opt{'part_pkg'} or return "No part_pkg specified";
853
854   # a little false laziness w/abov
855   # $rate_detail = new FS::rate_detail({sec_granularity => ... }) ?
856
857   my $granularity = length($part_pkg->option_cacheable('sec_granularity'))
858                       ? $part_pkg->option_cacheable('sec_granularity')
859                       : 60;
860
861   my $seconds = $part_pkg->option_cacheable('use_duration')
862                   ? $self->duration
863                   : $self->billsec;
864
865   $seconds += $granularity - ( $seconds % $granularity )
866     if $seconds      # don't granular-ize 0 billsec calls (bills them)
867     && $granularity  # 0 is per call
868     && $seconds % $granularity;
869   my $minutes = $granularity ? ($seconds / 60) : 1;
870
871   my $charge_min = $minutes;
872
873   ${$opt{single_price_included_min}} -= $minutes;
874   if ( ${$opt{single_price_included_min}} > 0 ) {
875     $charge_min = 0;
876   } else {
877      $charge_min = 0 - ${$opt{single_price_included_min}};
878      ${$opt{single_price_included_min}} = 0;
879   }
880
881   my $charge =
882     sprintf('%.4f', ( $part_pkg->option_cacheable('min_charge') * $charge_min )
883                     + 0.0000000001 ); #so 1.00005 rounds to 1.0001
884
885   $self->set_status_and_rated_price(
886     'rated',
887     $charge,
888     $opt{'svcnum'},
889     'rated_granularity' => $granularity,
890     'rated_seconds'     => $seconds,
891   );
892
893 }
894
895 =item cdr_termination [ TERMPART ]
896
897 =cut
898
899 sub cdr_termination {
900   my $self = shift;
901
902   if ( scalar(@_) && $_[0] ) {
903     my $termpart = shift;
904
905     qsearchs('cdr_termination', { acctid   => $self->acctid,
906                                   termpart => $termpart,
907                                 }
908             );
909
910   } else {
911
912     qsearch('cdr_termination', { acctid => $self->acctid, } );
913
914   }
915
916 }
917
918 =item calldate_unix 
919
920 Parses the calldate in SQL string format and returns a UNIX timestamp.
921
922 =cut
923
924 sub calldate_unix {
925   str2time(shift->calldate);
926 }
927
928 =item startdate_sql
929
930 Parses the startdate in UNIX timestamp format and returns a string in SQL
931 format.
932
933 =cut
934
935 sub startdate_sql {
936   my($sec,$min,$hour,$mday,$mon,$year) = localtime(shift->startdate);
937   $mon++;
938   $year += 1900;
939   "$year-$mon-$mday $hour:$min:$sec";
940 }
941
942 =item cdr_carrier
943
944 Returns the FS::cdr_carrier object associated with this CDR, or false if no
945 carrierid is defined.
946
947 =cut
948
949 my %carrier_cache = ();
950
951 sub cdr_carrier {
952   my $self = shift;
953   return '' unless $self->carrierid;
954   $carrier_cache{$self->carrierid} ||=
955     qsearchs('cdr_carrier', { 'carrierid' => $self->carrierid } );
956 }
957
958 =item carriername 
959
960 Returns the carrier name (see L<FS::cdr_carrier>), or the empty string if
961 no FS::cdr_carrier object is assocated with this CDR.
962
963 =cut
964
965 sub carriername {
966   my $self = shift;
967   my $cdr_carrier = $self->cdr_carrier;
968   $cdr_carrier ? $cdr_carrier->carriername : '';
969 }
970
971 =item cdr_calltype
972
973 Returns the FS::cdr_calltype object associated with this CDR, or false if no
974 calltypenum is defined.
975
976 =cut
977
978 my %calltype_cache = ();
979
980 sub cdr_calltype {
981   my $self = shift;
982   return '' unless $self->calltypenum;
983   $calltype_cache{$self->calltypenum} ||=
984     qsearchs('cdr_calltype', { 'calltypenum' => $self->calltypenum } );
985 }
986
987 =item calltypename 
988
989 Returns the call type name (see L<FS::cdr_calltype>), or the empty string if
990 no FS::cdr_calltype object is assocated with this CDR.
991
992 =cut
993
994 sub calltypename {
995   my $self = shift;
996   my $cdr_calltype = $self->cdr_calltype;
997   $cdr_calltype ? $cdr_calltype->calltypename : '';
998 }
999
1000 =item downstream_csv [ OPTION => VALUE, ... ]
1001
1002 =cut
1003
1004 my %export_names = (
1005   'simple'  => {
1006     'name'           => 'Simple',
1007     'invoice_header' => "Date,Time,Name,Destination,Duration,Price",
1008   },
1009   'simple2' => {
1010     'name'           => 'Simple with source',
1011     'invoice_header' => "Date,Time,Called From,Destination,Duration,Price",
1012                        #"Date,Time,Name,Called From,Destination,Duration,Price",
1013   },
1014   'basic' => {
1015     'name'           => 'Basic',
1016     'invoice_header' => "Date/Time,Called Number,Min/Sec,Price",
1017   },
1018   'default' => {
1019     'name'           => 'Default',
1020     'invoice_header' => 'Date,Time,Number,Destination,Duration,Price',
1021   },
1022   'source_default' => {
1023     'name'           => 'Default with source',
1024     'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
1025   },
1026   'accountcode_default' => {
1027     'name'           => 'Default plus accountcode',
1028     'invoice_header' => 'Date,Time,Account,Number,Destination,Duration,Price',
1029   },
1030   'description_default' => {
1031     'name'           => 'Default with description field as destination',
1032     'invoice_header' => 'Caller,Date,Time,Number,Destination,Duration,Price',
1033   },
1034   'sum_duration' => {
1035     'name'           => 'Summary, one line per service',
1036     'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
1037   },
1038   'sum_count' => {
1039     'name'           => 'Number of calls, one line per service',
1040     'invoice_header' => 'Caller,Rate,Messages,Price',
1041   },
1042   'sum_duration_prefix' => {
1043     'name'           => 'Summary, one line per destination prefix',
1044     'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
1045   },
1046 );
1047
1048 my %export_formats = ();
1049 sub export_formats {
1050   #my $self = shift;
1051
1052   return %export_formats if keys %export_formats;
1053
1054   my $conf = new FS::Conf;
1055   my $date_format = $conf->config('date_format') || '%m/%d/%Y';
1056
1057   # call duration in the largest units that accurately reflect the  granularity
1058   my $duration_sub = sub {
1059     my($cdr, %opt) = @_;
1060     my $sec = $opt{seconds} || $cdr->billsec;
1061     if ( defined $opt{granularity} && 
1062          $opt{granularity} == 0 ) { #per call
1063       return '1 call';
1064     }
1065     elsif ( defined $opt{granularity} && $opt{granularity} == 60 ) {#full minutes
1066       my $min = int($sec/60);
1067       $min++ if $sec%60;
1068       return $min.'m';
1069     }
1070     else { #anything else
1071       return sprintf("%dm %ds", $sec/60, $sec%60);
1072     }
1073   };
1074
1075   my $price_sub = sub {
1076     my ($cdr, %opt) = @_;
1077     my $price;
1078     if ( defined($opt{charge}) ) {
1079       $price = $opt{charge};
1080     }
1081     elsif ( $opt{inbound} ) {
1082       my $term = $cdr->cdr_termination(1); # 1 = inbound
1083       $price = $term->rated_price if defined $term;
1084     }
1085     else {
1086       $price = $cdr->rated_price;
1087     }
1088     length($price) ? ($opt{money_char} . $price) : '';
1089   };
1090
1091   %export_formats = (
1092     'simple' => [
1093       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
1094       sub { time2str('%r', shift->calldate_unix ) },   #TIME
1095       'userfield',                                     #USER
1096       'dst',                                           #NUMBER_DIALED
1097       $duration_sub,                                   #DURATION
1098       #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
1099       $price_sub,
1100     ],
1101     'simple2' => [
1102       sub { time2str($date_format, shift->calldate_unix ) },   #DATE
1103       sub { time2str('%r', shift->calldate_unix ) },   #TIME
1104       #'userfield',                                     #USER
1105       'src',                                           #called from
1106       'dst',                                           #NUMBER_DIALED
1107       $duration_sub,                                   #DURATION
1108       #sub { sprintf('%.3f', shift->upstream_price ) }, #PRICE
1109       $price_sub,
1110     ],
1111     'sum_duration' => [ 
1112       # for summary formats, the CDR is a fictitious object containing the 
1113       # total billsec and the phone number of the service
1114       'src',
1115       sub { my($cdr, %opt) = @_; $opt{ratename} },
1116       sub { my($cdr, %opt) = @_; $opt{count} },
1117       sub { my($cdr, %opt) = @_; int($opt{seconds}/60).'m' },
1118       $price_sub,
1119     ],
1120     'sum_count' => [
1121       'src',
1122       sub { my($cdr, %opt) = @_; $opt{ratename} },
1123       sub { my($cdr, %opt) = @_; $opt{count} },
1124       $price_sub,
1125     ],
1126     'basic' => [
1127       sub { time2str('%d %b - %I:%M %p', shift->calldate_unix) },
1128       'dst',
1129       $duration_sub,
1130       $price_sub,
1131     ],
1132     'default' => [
1133
1134       #DATE
1135       sub { time2str($date_format, shift->calldate_unix ) },
1136             # #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
1137
1138       #TIME
1139       sub { time2str('%r', shift->calldate_unix ) },
1140             # 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
1141
1142       #DEST ("Number")
1143       sub { my($cdr, %opt) = @_; $opt{pretty_dst} || $cdr->dst; },
1144
1145       #REGIONNAME ("Destination")
1146       sub { my($cdr, %opt) = @_; $opt{dst_regionname}; },
1147
1148       #DURATION
1149       $duration_sub,
1150
1151       #PRICE
1152       $price_sub,
1153     ],
1154   );
1155   $export_formats{'source_default'} = [ 'src', @{ $export_formats{'default'} }, ];
1156   $export_formats{'accountcode_default'} =
1157     [ @{ $export_formats{'default'} }[0,1],
1158       'accountcode',
1159       @{ $export_formats{'default'} }[2..5],
1160     ];
1161   my @default = @{ $export_formats{'default'} };
1162   $export_formats{'description_default'} = 
1163     [ 'src', @default[0..2], 
1164       sub { my($cdr, %opt) = @_; $cdr->description },
1165       @default[4,5] ];
1166
1167   return %export_formats;
1168 }
1169
1170 =item downstream_csv OPTION => VALUE ...
1171
1172 Returns a string of formatted call details for display on an invoice.
1173
1174 Options:
1175
1176 format
1177
1178 charge - override the 'rated_price' field of the CDR
1179
1180 seconds - override the 'billsec' field of the CDR
1181
1182 count - number of usage events included in this record, for summary formats
1183
1184 ratename - name of the rate table used to rate this call
1185
1186 granularity
1187
1188 =cut
1189
1190 sub downstream_csv {
1191   my( $self, %opt ) = @_;
1192
1193   my $format = $opt{'format'};
1194   my %formats = $self->export_formats;
1195   return "Unknown format $format" unless exists $formats{$format};
1196
1197   #my $conf = new FS::Conf;
1198   #$opt{'money_char'} ||= $conf->config('money_char') || '$';
1199   $opt{'money_char'} ||= FS::Conf->new->config('money_char') || '$';
1200
1201   eval "use Text::CSV_XS;";
1202   die $@ if $@;
1203   my $csv = new Text::CSV_XS;
1204
1205   my @columns =
1206     map {
1207           ref($_) ? &{$_}($self, %opt) : $self->$_();
1208         }
1209     @{ $formats{$format} };
1210
1211   return @columns if defined $opt{'keeparray'};
1212
1213   my $status = $csv->combine(@columns);
1214   die "FS::CDR: error combining ". $csv->error_input(). "into downstream CSV"
1215     unless $status;
1216
1217   $csv->string;
1218
1219 }
1220
1221 =back
1222
1223 =head1 CLASS METHODS
1224
1225 =over 4
1226
1227 =item invoice_formats
1228
1229 Returns an ordered list of key value pairs containing invoice format names
1230 as keys (for use with part_pkg::voip_cdr) and "pretty" format names as values.
1231
1232 =cut
1233
1234 # in the future, load this dynamically from detail_format classes
1235
1236 sub invoice_formats {
1237   map { ($_ => $export_names{$_}->{'name'}) }
1238     grep { $export_names{$_}->{'invoice_header'} }
1239     keys %export_names;
1240 }
1241
1242 =item invoice_header FORMAT
1243
1244 Returns a scalar containing the CSV column header for invoice format FORMAT.
1245
1246 =cut
1247
1248 sub invoice_header {
1249   my $format = shift;
1250   $export_names{$format}->{'invoice_header'};
1251 }
1252
1253 =item clear_status 
1254
1255 Clears cdr and any associated cdr_termination statuses - used for 
1256 CDR reprocessing.
1257
1258 =cut
1259
1260 sub clear_status {
1261   my $self = shift;
1262   my %opt = @_;
1263
1264   local $SIG{HUP} = 'IGNORE';
1265   local $SIG{INT} = 'IGNORE';
1266   local $SIG{QUIT} = 'IGNORE';
1267   local $SIG{TERM} = 'IGNORE';
1268   local $SIG{TSTP} = 'IGNORE';
1269   local $SIG{PIPE} = 'IGNORE';
1270
1271   my $oldAutoCommit = $FS::UID::AutoCommit;
1272   local $FS::UID::AutoCommit = 0;
1273   my $dbh = dbh;
1274
1275   if ( $cdr_prerate && $cdr_prerate_cdrtypenums{$self->cdrtypenum}
1276        && $self->rated_ratedetailnum #avoid putting old CDRs back in "rated"
1277        && $self->freesidestatus eq 'done'
1278        && ! $opt{'rerate'}
1279      )
1280   { #special case
1281     $self->freesidestatus('rated');
1282   } else {
1283     $self->freesidestatus('');
1284   }
1285
1286   my $error = $self->replace;
1287   if ( $error ) {
1288     $dbh->rollback if $oldAutoCommit;
1289     return $error;
1290   } 
1291
1292   foreach my $cdr_termination ( $self->cdr_termination ) {
1293       #$cdr_termination->status('');
1294       #$error = $cdr_termination->replace;
1295       $error = $cdr_termination->delete;
1296       if ( $error ) {
1297         $dbh->rollback if $oldAutoCommit;
1298         return $error;
1299       } 
1300   }
1301   
1302   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1303
1304   '';
1305 }
1306
1307 =item import_formats
1308
1309 Returns an ordered list of key value pairs containing import format names
1310 as keys (for use with batch_import) and "pretty" format names as values.
1311
1312 =cut
1313
1314 #false laziness w/part_pkg & part_export
1315
1316 my %cdr_info;
1317 foreach my $INC ( @INC ) {
1318   warn "globbing $INC/FS/cdr/*.pm\n" if $DEBUG;
1319   foreach my $file ( glob("$INC/FS/cdr/*.pm") ) {
1320     warn "attempting to load CDR format info from $file\n" if $DEBUG;
1321     $file =~ /\/(\w+)\.pm$/ or do {
1322       warn "unrecognized file in $INC/FS/cdr/: $file\n";
1323       next;
1324     };
1325     my $mod = $1;
1326     my $info = eval "use FS::cdr::$mod; ".
1327                     "\\%FS::cdr::$mod\::info;";
1328     if ( $@ ) {
1329       die "error using FS::cdr::$mod (skipping): $@\n" if $@;
1330       next;
1331     }
1332     unless ( keys %$info ) {
1333       warn "no %info hash found in FS::cdr::$mod, skipping\n";
1334       next;
1335     }
1336     warn "got CDR format info from FS::cdr::$mod: $info\n" if $DEBUG;
1337     if ( exists($info->{'disabled'}) && $info->{'disabled'} ) {
1338       warn "skipping disabled CDR format FS::cdr::$mod" if $DEBUG;
1339       next;
1340     }
1341     $cdr_info{$mod} = $info;
1342   }
1343 }
1344
1345 tie my %import_formats, 'Tie::IxHash',
1346   map  { $_ => $cdr_info{$_}->{'name'} }
1347   sort { $cdr_info{$a}->{'weight'} <=> $cdr_info{$b}->{'weight'} }
1348   grep { exists($cdr_info{$_}->{'import_fields'}) }
1349   keys %cdr_info;
1350
1351 sub import_formats {
1352   %import_formats;
1353 }
1354
1355 sub _cdr_min_parser_maker {
1356   my $field = shift;
1357   my @fields = ref($field) ? @$field : ($field);
1358   @fields = qw( billsec duration ) unless scalar(@fields) && $fields[0];
1359   return sub {
1360     my( $cdr, $min ) = @_;
1361     my $sec = eval { _cdr_min_parse($min) };
1362     die "error parsing seconds for @fields from $min minutes: $@\n" if $@;
1363     $cdr->$_($sec) foreach @fields;
1364   };
1365 }
1366
1367 sub _cdr_min_parse {
1368   my $min = shift;
1369   sprintf('%.0f', $min * 60 );
1370 }
1371
1372 sub _cdr_date_parser_maker {
1373   my $field = shift;
1374   my %options = @_;
1375   my @fields = ref($field) ? @$field : ($field);
1376   return sub {
1377     my( $cdr, $datestring ) = @_;
1378     my $unixdate = eval { _cdr_date_parse($datestring, %options) };
1379     die "error parsing date for @fields from $datestring: $@\n" if $@;
1380     $cdr->$_($unixdate) foreach @fields;
1381   };
1382 }
1383
1384 sub _cdr_date_parse {
1385   my $date = shift;
1386   my %options = @_;
1387
1388   return '' unless length($date); #that's okay, it becomes NULL
1389   return '' if $date eq 'NA'; #sansay
1390
1391   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 ) {
1392     my $time = str2time($date);
1393     return $time if $time > 100000; #just in case
1394   }
1395
1396   my($year, $mon, $day, $hour, $min, $sec);
1397
1398   #$date =~ /^\s*(\d{4})[\-\/]\(\d{1,2})[\-\/](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s*$/
1399   #taqua  #2007-10-31 08:57:24.113000000
1400
1401   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|$)/ ) {
1402     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1403   } 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|$)/ ) {
1404     # 8/26/2010 12:20:01
1405     # optionally without seconds
1406     ($mon, $day, $year, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1407     $sec = 0 if !defined($sec);
1408   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d+\.\d+)(\D|$)/ ) {
1409     # broadsoft: 20081223201938.314
1410     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1411   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})\d+(\D|$)/ ) {
1412     # Taqua OM:  20050422203450943
1413     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1414   } elsif ( $date  =~ /^\s*(\d{4})(\d{2})(\d{2})(\d{2})(\d{2})(\d{2})$/ ) {
1415     # WIP: 20100329121420
1416     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1417   } elsif ( $date =~ /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/) {
1418     # Telos
1419     ($year, $mon, $day, $hour, $min, $sec) = ( $1, $2, $3, $4, $5, $6 );
1420     $options{gmt} = 1;
1421   } else {
1422      die "unparsable date: $date"; #maybe we shouldn't die...
1423   }
1424
1425   return '' if ( $year == 1900 || $year == 1970 ) && $mon == 1 && $day == 1
1426             && $hour == 0 && $min == 0 && $sec == 0;
1427
1428   if ($options{gmt}) {
1429     timegm($sec, $min, $hour, $day, $mon-1, $year);
1430   } else {
1431     timelocal($sec, $min, $hour, $day, $mon-1, $year);
1432   }
1433 }
1434
1435 =item batch_import HASHREF
1436
1437 Imports CDR records.  Available options are:
1438
1439 =over 4
1440
1441 =item file
1442
1443 Filename
1444
1445 =item format
1446
1447 =item params
1448
1449 Hash reference of preset fields, typically cdrbatch
1450
1451 =item empty_ok
1452
1453 Set true to prevent throwing an error on empty imports
1454
1455 =back
1456
1457 =cut
1458
1459 my %import_options = (
1460   'table'         => 'cdr',
1461
1462   'batch_keycol'  => 'cdrbatchnum',
1463   'batch_table'   => 'cdr_batch',
1464   'batch_namecol' => 'cdrbatch',
1465
1466   'formats' => { map { $_ => $cdr_info{$_}->{'import_fields'}; }
1467                      keys %cdr_info
1468                },
1469
1470                           #drop the || 'csv' to allow auto xls for csv types?
1471   'format_types' => { map { $_ => lc($cdr_info{$_}->{'type'} || 'csv'); }
1472                           keys %cdr_info
1473                     },
1474
1475   'format_headers' => { map { $_ => ( $cdr_info{$_}->{'header'} || 0 ); }
1476                             keys %cdr_info
1477                       },
1478
1479   'format_sep_chars' => { map { $_ => $cdr_info{$_}->{'sep_char'}; }
1480                               keys %cdr_info
1481                         },
1482
1483   'format_fixedlength_formats' =>
1484     { map { $_ => $cdr_info{$_}->{'fixedlength_format'}; }
1485           keys %cdr_info
1486     },
1487
1488   'format_xml_formats' =>
1489     { map { $_ => $cdr_info{$_}->{'xml_format'}; }
1490           keys %cdr_info
1491     },
1492
1493   'format_row_callbacks' => { map { $_ => $cdr_info{$_}->{'row_callback'}; }
1494                                   keys %cdr_info
1495                             },
1496 );
1497
1498 sub _import_options {
1499   \%import_options;
1500 }
1501
1502 sub batch_import {
1503   my $opt = shift;
1504
1505   my $iopt = _import_options;
1506   $opt->{$_} = $iopt->{$_} foreach keys %$iopt;
1507
1508   if ( defined $opt->{'cdrtypenum'} ) {
1509         $opt->{'preinsert_callback'} = sub {
1510                 my($record,$param) = (shift,shift);
1511                 $record->cdrtypenum($opt->{'cdrtypenum'});
1512                 '';
1513         };
1514   }
1515
1516   FS::Record::batch_import( $opt );
1517
1518 }
1519
1520 =item process_batch_import
1521
1522 =cut
1523
1524 sub process_batch_import {
1525   my $job = shift;
1526
1527   my $opt = _import_options;
1528 #  $opt->{'params'} = [ 'format', 'cdrbatch' ];
1529
1530   FS::Record::process_batch_import( $job, $opt, @_ );
1531
1532 }
1533 #  if ( $format eq 'simple' ) { #should be a callback or opt in FS::cdr::simple
1534 #    @columns = map { s/^ +//; $_; } @columns;
1535 #  }
1536
1537 # _ upgrade_data
1538 #
1539 # Used by FS::Upgrade to migrate to a new database.
1540
1541 sub _upgrade_data {
1542   my ($class, %opts) = @_;
1543
1544   warn "$me upgrading $class\n" if $DEBUG;
1545
1546   my $sth = dbh->prepare(
1547     'SELECT DISTINCT(cdrbatch) FROM cdr WHERE cdrbatch IS NOT NULL'
1548   ) or die dbh->errstr;
1549
1550   $sth->execute or die $sth->errstr;
1551
1552   my %cdrbatchnum = ();
1553   while (my $row = $sth->fetchrow_arrayref) {
1554
1555     my $cdr_batch = qsearchs( 'cdr_batch', { 'cdrbatch' => $row->[0] } );
1556     unless ( $cdr_batch ) {
1557       $cdr_batch = new FS::cdr_batch { 'cdrbatch' => $row->[0] };
1558       my $error = $cdr_batch->insert;
1559       die $error if $error;
1560     }
1561
1562     $cdrbatchnum{$row->[0]} = $cdr_batch->cdrbatchnum;
1563   }
1564
1565   $sth = dbh->prepare('UPDATE cdr SET cdrbatch = NULL, cdrbatchnum = ? WHERE cdrbatch IS NOT NULL AND cdrbatch = ?') or die dbh->errstr;
1566
1567   foreach my $cdrbatch (keys %cdrbatchnum) {
1568     $sth->execute($cdrbatchnum{$cdrbatch}, $cdrbatch) or die $sth->errstr;
1569   }
1570
1571 }
1572
1573 =back
1574
1575 =head1 BUGS
1576
1577 =head1 SEE ALSO
1578
1579 L<FS::Record>, schema.html from the base documentation.
1580
1581 =cut
1582
1583 1;
1584