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