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