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