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