inter/intra-state phone billing and custom rate import script, RT13112
[freeside.git] / FS / FS / part_pkg / voip_cdr.pm
1 package FS::part_pkg::voip_cdr;
2
3 use strict;
4 use base qw( FS::part_pkg::recur_Common );
5 use vars qw( $DEBUG %info );
6 use Date::Format;
7 use Tie::IxHash;
8 use FS::Conf;
9 use FS::Record qw(qsearchs qsearch);
10 use FS::cdr;
11 use FS::rate;
12 use FS::rate_prefix;
13 use FS::rate_detail;
14
15 use List::Util qw(first min);
16
17
18 $DEBUG = 0;
19
20 tie my %cdr_svc_method, 'Tie::IxHash',
21   'svc_phone.phonenum' => 'Phone numbers (svc_phone.phonenum)',
22   'svc_pbx.title'      => 'PBX name (svc_pbx.title)',
23   'svc_pbx.svcnum'     => 'Freeside service # (svc_pbx.svcnum)',
24 ;
25
26 tie my %rating_method, 'Tie::IxHash',
27   'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
28 #  'upstream' => 'Rate calls based on upstream data: If the call type is "1", map the upstream rate ID directly to an internal rate (rate_detail), otherwise, pass the upstream price through directly.',
29   'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
30   'single_price' => 'A single price per minute for all calls.',
31 ;
32
33 #tie my %cdr_location, 'Tie::IxHash',
34 #  'internal' => 'Internal: CDR records imported into the internal CDR table',
35 #  'external' => 'External: CDR records queried directly from an external '.
36 #                'Asterisk (or other?) CDR table',
37 #;
38
39 tie my %temporalities, 'Tie::IxHash',
40   'upcoming'  => "Upcoming (future)",
41   'preceding' => "Preceding (past)",
42 ;
43
44 tie my %granularity, 'Tie::IxHash', FS::rate_detail::granularities();
45
46 %info = (
47   'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
48   'shortname' => 'VoIP/telco CDR rating (standard)',
49   'inherit_fields' => [ 'global_Mixin' ],
50   'fields' => {
51     'suspend_bill' => { 'name' => 'Continue recurring billing while suspended',
52                         'type' => 'checkbox',
53                       },
54     #false laziness w/flat.pm
55     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
56                              'type' => 'select',
57                              'select_options' => \%temporalities,
58                            },
59
60     'cutoff_day'    => { 'name' => 'Billing Day (1 - 28) for prorating or '.
61                                    'subscription',
62                          'default' => '1',
63                        },
64     'add_full_period'=> { 'name' => 'When prorating first month, also bill '.
65                                     'for one full period after that',
66                           'type' => 'checkbox',
67                         },
68     'recur_method'  => { 'name' => 'Recurring fee method',
69                          #'type' => 'radio',
70                          #'options' => \%recur_method,
71                          'type' => 'select',
72                          'select_options' => \%FS::part_pkg::recur_Common::recur_method,
73                        },
74
75     'cdr_svc_method' => { 'name' => 'CDR service matching method',
76                           'type' => 'radio',
77                           'options' => \%cdr_svc_method,
78                         },
79
80     'rating_method' => { 'name' => 'Rating method',
81                          'type' => 'radio',
82                          'options' => \%rating_method,
83                        },
84
85     'ratenum'   => { 'name' => 'Rate plan',
86                      'type' => 'select',
87                      'select_table' => 'rate',
88                      'select_key'   => 'ratenum',
89                      'select_label' => 'ratename',
90                    },
91                    
92     'intrastate_ratenum'   => { 'name' => 'Optional alternate intrastate rate plan',
93                      'type' => 'select',
94                      'select_table' => 'rate',
95                      'select_key'   => 'ratenum',
96                      'select_label' => 'ratename',
97                      'disable_empty' => 0,
98                      'empty_label'   => '',
99                    },
100
101     'min_included' => { 'name' => 'Minutes included when using the "single price per minute" rating method or when using the "prefix" rating method ("region group" billing)',
102                     },
103
104     'min_charge' => { 'name' => 'Charge per minute when using "single price per minute" rating method',
105                     },
106
107     'sec_granularity' => { 'name' => 'Granularity when using "single price per minute" rating method',
108                            'type' => 'select',
109                            'select_options' => \%granularity,
110                          },
111
112     'ignore_unrateable' => { 'name' => 'Ignore calls without a rate in the rate tables.  By default, the system will throw a fatal error upon encountering unrateable calls.',
113                              'type' => 'checkbox',
114                            },
115
116     'default_prefix' => { 'name'    => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
117                           'default' => '+1',
118                         },
119
120     'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
121                        'type' => 'checkbox'
122                      },
123
124     'domestic_prefix' => { 'name'    => 'Destination prefix for domestic CDR records',
125                            'default' => '1',
126                          },
127
128 #    'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
129 #                                    'type' => 'checkbox',
130 #                                  },
131
132     'international_prefix' => { 'name'    => 'Destination prefix for international CDR records',
133                                 'default' => '011',
134                               },
135
136     'disable_tollfree' => { 'name' => 'Disable automatic toll-free processing',
137                             'type' => 'checkbox',
138                           },
139
140     'use_amaflags' => { 'name' => 'Do not charge for CDRs where the amaflags field is not set to "2" ("BILL"/"BILLING").',
141                         'type' => 'checkbox',
142                       },
143
144     'use_disposition' => { 'name' => 'Do not charge for CDRs where the disposition flag is not set to "ANSWERED".',
145                            'type' => 'checkbox',
146                          },
147
148     'use_disposition_taqua' => { 'name' => 'Do not charge for CDRs where the disposition is not set to "100" (Taqua).',
149                                  'type' => 'checkbox',
150                                },
151
152     'use_carrierid' => { 'name' => 'Do not charge for CDRs where the Carrier ID is not set to: ',
153                          },
154
155     'use_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is not set to: ',
156                          },
157
158     'skip_dst_prefix' => { 'name' => 'Do not charge for CDRs where the destination number starts with any of these values: ',
159     },
160
161     'skip_dcontext' => { 'name' => 'Do not charge for CDRs where the dcontext is set to any of these (comma-separated) values: ',
162                        },
163
164     'skip_dstchannel_prefix' => { 'name' => 'Do not charge for CDRs where the dstchannel starts with:',
165                                 },
166
167     'skip_src_length_more' => { 'name' => 'Do not charge for CDRs where the source is more than this many digits:',
168                               },
169
170     'noskip_src_length_accountcode_tollfree' => { 'name' => 'Do charge for CDRs where source is equal or greater than the specified digits, when accountcode is toll free',
171                                                   'type' => 'checkbox',
172                                                 },
173
174     'accountcode_tollfree_ratenum' => {
175       'name' => 'Optional alternate rate plan when accountcode is toll free: ',
176       'type' => 'select',
177       'select_table'  => 'rate',
178       'select_key'    => 'ratenum',
179       'select_label'  => 'ratename',
180       'disable_empty' => 0,
181       'empty_label'   => '',
182     },
183
184     'skip_dst_length_less' => { 'name' => 'Do not charge for CDRs where the destination is less than this many digits:',
185                               },
186
187     'noskip_dst_length_accountcode_tollfree' => { 'name' => 'Do charge for CDRs where dst is less than the specified digits, when accountcode is toll free',
188                                                   'type' => 'checkbox',
189                                                 },
190
191     'skip_lastapp' => { 'name' => 'Do not charge for CDRs where the lastapp matches this value: ',
192                       },
193
194     'skip_max_callers' => { 'name' => 'Do not charge for CDRs where max_callers is less than or equal to this value: ',
195                           },
196
197     'use_duration'   => { 'name' => 'Calculate usage based on the duration field instead of the billsec field',
198                           'type' => 'checkbox',
199                         },
200
201     '411_rewrite' => { 'name' => 'Rewrite these (comma-separated) destination numbers to 411 for rating purposes (also ignore any carrierid check): ',
202                       },
203
204     #false laziness w/cdr_termination.pm
205     'output_format' => { 'name' => 'CDR invoice display format',
206                          'type' => 'select',
207                          'select_options' => { FS::cdr::invoice_formats() },
208                          'default'        => 'default', #XXX test
209                        },
210
211     'usage_section' => { 'name' => 'Section in which to place usage charges (whether separated or not): ',
212                        },
213
214     'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
215                           'type' => 'checkbox',
216                         },
217
218     'usage_mandate' => { 'name' => 'Always put usage details in separate section',
219                           'type' => 'checkbox',
220                        },
221     #eofalse
222
223     'bill_every_call' => { 'name' => 'Generate an invoice immediately for every call (as well any setup fee, upon first payment).  Useful for prepaid.',
224                            'type' => 'checkbox',
225                          },
226
227     'bill_inactive_svcs' => { 'name' => 'Bill for all phone numbers that were active during the billing period',
228                               'type' => 'checkbox',
229                             },
230
231     'count_available_phones' => { 'name' => 'Consider for tax purposes the number of lines to be svc_phones that may be provisioned rather than those that actually are.',
232                            'type' => 'checkbox',
233                          },
234
235     #XXX also have option for an external db
236 #    'cdr_location' => { 'name' => 'CDR database location'
237 #                        'type' => 'select',
238 #                        'select_options' => \%cdr_location,
239 #                        'select_callback' => {
240 #                          'external' => {
241 #                            'enable' => [ 'datasrc', 'username', 'password' ],
242 #                          },
243 #                          'internal' => {
244 #                            'disable' => [ 'datasrc', 'username', 'password' ],
245 #                          }
246 #                        },
247 #                      },
248 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
249 #                   'disabled' => 'Y',
250 #                 },
251 #    'username' => { 'name' => 'External database username',
252 #                    'disabled' => 'Y',
253 #                  },
254 #    'password' => { 'name' => 'External database password',
255 #                    'disabled' => 'Y',
256 #                  },
257
258   },
259   'fieldorder' => [qw(
260                        recur_temporality
261                        recur_method cutoff_day
262                        add_full_period
263                        cdr_svc_method
264                        rating_method ratenum intrastate_ratenum 
265                        min_charge min_included
266                                sec_granularity
267                        ignore_unrateable
268                        default_prefix
269                        disable_src
270                        domestic_prefix international_prefix
271                        disable_tollfree
272                        use_amaflags use_disposition
273                        use_disposition_taqua use_carrierid use_cdrtypenum
274                        skip_dcontext skip_dst_prefix 
275                        skip_dstchannel_prefix skip_src_length_more 
276                        noskip_src_length_accountcode_tollfree
277                        accountcode_tollfree_ratenum
278                        skip_dst_length_less
279                        noskip_dst_length_accountcode_tollfree
280                        skip_lastapp
281                        skip_max_callers
282                        use_duration
283                        411_rewrite
284                        output_format usage_mandate summarize_usage usage_section
285                        bill_every_call bill_inactive_svcs
286                        count_available_phones suspend_bill 
287                      )
288                   ],
289   'weight' => 40,
290 );
291
292 sub price_info {
293     my $self = shift;
294     my $str = $self->SUPER::price_info;
295     $str .= " plus usage" if $str;
296     $str;
297 }
298
299 sub calc_setup {
300   my($self, $cust_pkg ) = @_;
301   $self->option('setup_fee');
302 }
303
304 sub calc_recur {
305   my $self = shift;
306   my($cust_pkg, $sdate, $details, $param ) = @_;
307
308   my $charges = 0;
309
310   $charges += $self->calc_usage(@_);
311   $charges += $self->calc_recur_Common(@_);
312
313   $charges;
314
315 }
316
317 sub calc_cancel {
318   my $self = shift;
319   my($cust_pkg, $sdate, $details, $param ) = @_;
320
321   $self->calc_usage(@_);
322 }
323
324 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
325
326 sub calc_usage {
327   my $self = shift;
328   my($cust_pkg, $sdate, $details, $param ) = @_;
329
330   #my $last_bill = $cust_pkg->last_bill;
331   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
332
333   return 0
334     if $self->recur_temporality eq 'preceding'
335     && ( $last_bill eq '' || $last_bill == 0 );
336
337   my $ratenum = $cust_pkg->part_pkg->option('ratenum');
338
339   my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
340
341   my %included_min = ();
342
343   my $charges = 0;
344
345 #  my $downstream_cdr = '';
346
347   my $cdr_svc_method    = $self->option('cdr_svc_method',1)||'svc_phone.phonenum';
348   my $rating_method     = $self->option('rating_method') || 'prefix';
349   my $intl              = $self->option('international_prefix') || '011';
350   my $domestic_prefix   = $self->option('domestic_prefix');
351   my $disable_tollfree  = $self->option('disable_tollfree');
352   my $ignore_unrateable = $self->option('ignore_unrateable', 'Hush!');
353   my $use_duration      = $self->option('use_duration');
354   my $region_group      = ($rating_method eq 'prefix' && ($self->option('min_included',1) || 0) > 0);
355   my $region_group_included_min = $region_group ? $self->option('min_included') : 0;
356
357   my $output_format     = $self->option('output_format', 'Hush!')
358                           || ( $rating_method eq 'upstream_simple'
359                                  ? 'simple'
360                                  : 'default'
361                              );
362
363   my @dirass = ();
364   if ( $self->option('411_rewrite') ) {
365     my $dirass = $self->option('411_rewrite');
366     $dirass =~ s/\s//g;
367     @dirass = split(',', $dirass);
368   }
369
370   my %interval_cache = (); # for timed rates
371
372   #for check_chargable, so we don't keep looking up options inside the loop
373   my %opt_cache = ();
374
375   eval "use Text::CSV_XS;";
376   die $@ if $@;
377   my $csv = new Text::CSV_XS;
378
379   my($svc_table, $svc_field) = split('\.', $cdr_svc_method);
380
381   my @cust_svc;
382   if( $self->option('bill_inactive_svcs',1) ) {
383     #XXX in this mode do we need to restrict the set of CDRs by date also?
384     @cust_svc = $cust_pkg->h_cust_svc($$sdate, $last_bill);
385   }
386   else {
387     @cust_svc = $cust_pkg->cust_svc;
388   }
389   @cust_svc = grep { $_->part_svc->svcdb eq $svc_table } @cust_svc;
390
391   foreach my $cust_svc (@cust_svc) {
392
393     my $svc_x;
394     if( $self->option('bill_inactive_svcs',1) ) {
395       $svc_x = $cust_svc->h_svc_x($$sdate, $last_bill);
396     }
397     else {
398       $svc_x = $cust_svc->svc_x;
399     }
400     my %options = (
401         'disable_src'    => $self->option('disable_src'),
402         'default_prefix' => $self->option('default_prefix'),
403         'status'         => '',
404         'for_update'     => 1,
405       );  # $last_bill, $$sdate )
406     $options{'by_svcnum'} = 1 if $svc_field eq 'svcnum';
407
408     my @invoice_details_sort;
409
410     foreach my $cdr (
411       $svc_x->get_cdrs( %options )
412     ) {
413       if ( $DEBUG > 1 ) {
414         warn "rating CDR $cdr\n".
415              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
416       }
417
418       my $rate_detail;
419       my( $rate_region, $regionnum );
420       my $rate;
421       my $pretty_destnum;
422       my $charge = '';
423       my $seconds = '';
424       my $weektime = '';
425       my $regionname = '';
426       my $classnum = '';
427       my $countrycode;
428       my $number;
429
430       my @call_details = ();
431       if ( $rating_method eq 'prefix' ) {
432
433         my $da_rewrote = 0;
434         if ( length($cdr->dst) && grep { $cdr->dst eq $_ } @dirass ){
435           $cdr->dst('411');
436           $da_rewrote = 1;
437         }
438
439         my $reason = $self->check_chargable( $cdr,
440                                              'da_rewrote'   => $da_rewrote,
441                                              'option_cache' => \%opt_cache,
442                                            );
443
444         if ( $reason ) {
445
446           warn "not charging for CDR ($reason)\n" if $DEBUG;
447           $charge = 0;
448
449         } else {
450           
451           ###
452           # look up rate details based on called station id
453           # (or calling station id for toll free calls)
454           ###
455
456           my( $to_or_from );
457           if ( $cdr->is_tollfree && ! $disable_tollfree )
458           { #tollfree call
459             $to_or_from = 'from';
460             $number = $cdr->src;
461           } else { #regular call
462             $to_or_from = 'to';
463             $number = $cdr->dst;
464           }
465
466           warn "parsing call $to_or_from $number\n" if $DEBUG;
467
468           #remove non-phone# stuff and whitespace
469           $number =~ s/\s//g;
470 #          my $proto = '';
471 #          $dest =~ s/^(\w+):// and $proto = $1; #sip:
472 #          my $siphost = '';
473 #          $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
474
475           #determine the country code
476           $countrycode = '';
477           if (    $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
478                || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
479              )
480           {
481
482             my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
483             #first look for 1 digit country code
484             if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
485               $countrycode = $one;
486               $number = $u1.$u2.$rest;
487             } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
488               $countrycode = $two;
489               $number = $u2.$rest;
490             } else { #3 digit country code
491               $countrycode = $three;
492               $number = $rest;
493             }
494
495           } else {
496             $countrycode = length($domestic_prefix) ? $domestic_prefix : '1';
497             $number =~ s/^$countrycode//;# if length($number) > 10;
498           }
499
500           warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
501           $pretty_destnum = "+$countrycode $number";
502           #asterisks here causes inserting the detail to barf, so:
503           $pretty_destnum =~ s/\*//g;
504
505           my $eff_ratenum = $cdr->is_tollfree('accountcode')
506             ? $cust_pkg->part_pkg->option('accountcode_tollfree_ratenum')
507             : '';
508
509           my $intrastate_ratenum = $cust_pkg->part_pkg->option('accountcode_tollfree_ratenum');
510           if ( $intrastate_ratenum && !$cdr->is_tollfree ) {
511             # this is relatively easy only because:
512             # -assume all numbers are valid NANP numbers NOT in a fully-qualified format
513             # -disregard toll-free
514             # -disregard private or unknown numbers
515             # -there is exactly one record in rate_prefix for a given NPANXX
516             # -default to interstate if we can't find one or both of the prefixes
517             my $dstprefix = $cdr->dst;
518             $dstprefix =~ /^(\d{6})/;
519             $dstprefix = qsearchs('rate_prefix', {   'countrycode' => '1', 
520                                                         'npa' => $1, 
521                                                  }) || '';
522             my $srcprefix = $cdr->src;
523             $srcprefix =~ /^(\d{6})/;
524             $srcprefix = qsearchs('rate_prefix', {   'countrycode' => '1',
525                                                      'npa' => $1, 
526                                                  }) || '';
527             $eff_ratenum = $intrastate_ratenum if ($srcprefix && $dstprefix
528                 && $srcprefix->state && $dstprefix->state
529                 && $srcprefix->state eq $dstprefix->state);
530           }
531
532           $eff_ratenum ||= $ratenum;
533           $rate = qsearchs('rate', { 'ratenum' => $eff_ratenum })
534             or die "ratenum $eff_ratenum not found!";
535
536           my @ltime = localtime($cdr->startdate);
537           $weektime = $ltime[0] + 
538                       $ltime[1]*60 +   #minutes
539                       $ltime[2]*3600 + #hours
540                       $ltime[6]*86400; #days since sunday
541           # if there's no timed rate_detail for this time/region combination,
542           # dest_detail returns the default.  There may still be a timed rate 
543           # that applies after the starttime of the call, so be careful...
544           $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
545                                               'phonenum'    => $number,
546                                               'weektime'    => $weektime,
547                                               'cdrtypenum'  => $cdr->cdrtypenum,
548                                             });
549
550           if ( $rate_detail ) {
551
552             $rate_region = $rate_detail->dest_region;
553             $regionnum = $rate_region->regionnum;
554             $regionname = $rate_region->regionname;
555             warn "  found rate for regionnum $regionnum ".
556                  "and rate detail $rate_detail\n"
557               if $DEBUG;
558
559             if ( !exists($interval_cache{$regionnum}) ) {
560               my @intervals = (
561                 sort { $a->stime <=> $b->stime }
562                 map { my $r = $_->rate_time; $r ? $r->intervals : () }
563                 $rate->rate_detail
564               );
565               $interval_cache{$regionnum} = \@intervals;
566               warn "  cached ".scalar(@intervals)." interval(s)\n"
567                 if $DEBUG;
568             }
569
570           } elsif ( $ignore_unrateable ) {
571
572             $rate_region = '';
573             $regionnum = '';
574             #code below will throw a warning & skip
575
576           } else {
577
578             die "FATAL: no rate_detail found in ".
579                 $rate->ratenum. ":". $rate->ratename. " rate plan ".
580                 "for +$countrycode $number (CDR acctid ". $cdr->acctid. "); ".
581                 "add a rate or set ignore_unrateable flag on the package def\n";
582           }
583
584         }
585
586       } elsif ( $rating_method eq 'upstream_simple' ) {
587
588         #XXX $charge = sprintf('%.2f', $cdr->upstream_price);
589         $charge = sprintf('%.3f', $cdr->upstream_price);
590         $charges += $charge;
591         warn "Incrementing \$charges by $charge.  Now $charges\n" if $DEBUG;
592
593         @call_details = ($cdr->downstream_csv( 'format' => $output_format,
594                                                'charge' => $charge,
595                                              )
596                         );
597         $classnum = $cdr->calltypenum;
598
599       } elsif ( $rating_method eq 'single_price' ) {
600
601         # a little false laziness w/below
602         # $rate_detail = new FS::rate_detail({sec_granularity => ... }) ?
603
604         my $granularity = length($self->option('sec_granularity'))
605                             ? $self->option('sec_granularity')
606                             : 60;
607
608         $seconds = $use_duration ? $cdr->duration : $cdr->billsec;
609
610         $seconds += $granularity - ( $seconds % $granularity )
611           if $seconds      # don't granular-ize 0 billsec calls (bills them)
612           && $granularity  # 0 is per call
613           && $seconds % $granularity;
614         my $minutes = $granularity ? ($seconds / 60) : 1;
615         $charge = sprintf('%.4f', ( $self->option('min_charge') * $minutes )
616                                   + 0.0000000001 ); #so 1.00005 rounds to 1.0001
617
618         warn "Incrementing \$charges by $charge.  Now $charges\n" if $DEBUG;
619         $charges += $charge;
620
621         @call_details = ($cdr->downstream_csv( 'format'  => $output_format,
622                                                'charge'  => $charge,
623                                                'seconds' => ($use_duration ? 
624                                                              $cdr->duration : 
625                                                              $cdr->billsec),
626                                                'granularity' => $granularity,
627                                              )
628                         );
629
630       } else {
631         die "don't know how to rate CDRs using method: $rating_method\n";
632       }
633
634       ###
635       # find the price and add detail to the invoice
636       ###
637
638       # if $rate_detail is not found, skip this CDR... i.e. 
639       # don't add it to invoice, don't set its status to done,
640       # don't call downstream_csv or something on it...
641       # but DO emit a warning...
642       #if ( ! $rate_detail && ! scalar(@call_details) ) {}
643       if ( ! $rate_detail && $charge eq '' ) {
644
645         warn "no rate_detail found for CDR.acctid: ". $cdr->acctid.
646              "; skipping\n"
647
648       } else { # there *is* a rate_detail (or call_details), proceed...
649         # About this section:
650         # We don't round _anything_ (except granularizing) 
651         # until the final $charge = sprintf("%.2f"...).
652
653         unless ( @call_details || ( $charge ne '' && $charge == 0 ) ) {
654
655           my $seconds_left = $use_duration ? $cdr->duration : $cdr->billsec;
656           # charge for the first (conn_sec) seconds
657           $seconds = min($seconds_left, $rate_detail->conn_sec);
658           $seconds_left -= $seconds; 
659           $weektime     += $seconds;
660           $charge = $rate_detail->conn_charge; 
661
662           my $etime;
663           while($seconds_left) {
664             my $ratetimenum = $rate_detail->ratetimenum; # may be empty
665
666             # find the end of the current rate interval
667             if(@{ $interval_cache{$regionnum} } == 0) {
668               # There are no timed rates in this group, so just stay 
669               # in the default rate_detail for the entire duration.
670               # Set an "end" of 1 past the end of the current call.
671               $etime = $weektime + $seconds_left + 1;
672             } 
673             elsif($ratetimenum) {
674               # This is a timed rate, so go to the etime of this interval.
675               # If it's followed by another timed rate, the stime of that 
676               # interval should match the etime of this one.
677               my $interval = $rate_detail->rate_time->contains($weektime);
678               $etime = $interval->etime;
679             }
680             else {
681               # This is a default rate, so use the stime of the next 
682               # interval in the sequence.
683               my $next_int = first { $_->stime > $weektime } 
684                               @{ $interval_cache{$regionnum} };
685               if ($next_int) {
686                 $etime = $next_int->stime;
687               }
688               else {
689                 # weektime is near the end of the week, so decrement 
690                 # it by a full week and use the stime of the first 
691                 # interval.
692                 $weektime -= (3600*24*7);
693                 $etime = $interval_cache{$regionnum}->[0]->stime;
694               }
695             }
696
697             my $charge_sec = min($seconds_left, $etime - $weektime);
698
699             $seconds_left -= $charge_sec;
700
701             $included_min{$regionnum}{$ratetimenum} = $rate_detail->min_included
702               unless exists $included_min{$regionnum}{$ratetimenum};
703
704             my $granularity = $rate_detail->sec_granularity;
705
706             my $minutes;
707             if ( $granularity ) { # charge per minute
708               # Round up to the nearest $granularity
709               if ( $charge_sec and $charge_sec % $granularity ) {
710                 $charge_sec += $granularity - ($charge_sec % $granularity);
711               }
712               $minutes = $charge_sec / 60; #don't round this
713             }
714             else { # per call
715               $minutes = 1;
716               $seconds_left = 0;
717             }
718
719             $seconds += $charge_sec;
720
721             $region_group_included_min -= $minutes 
722                 if $region_group && $rate_detail->region_group;
723
724             $included_min{$regionnum}{$ratetimenum} -= $minutes;
725             if ( ($region_group_included_min <= 0 || !$rate_detail->region_group)
726                           && $included_min{$regionnum}{$ratetimenum} <= 0 ) {
727               my $charge_min = 0 - $included_min{$regionnum}{$ratetimenum}; #XXX should preserve
728                                                               #(display?) this
729               $included_min{$regionnum}{$ratetimenum} = 0;
730               $charge += ($rate_detail->min_charge * $charge_min); #still not rounded
731             }
732             elsif( $region_group_included_min > 0 && $region_group
733                 && $rate_detail->region_group ) {
734                 $included_min{$regionnum}{$ratetimenum} = 0 
735             }
736
737             # choose next rate_detail
738             $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
739                                                 'phonenum'    => $number,
740                                                 'weektime'    => $etime,
741                                                 'cdrtypenum'  => $cdr->cdrtypenum })
742                     if($seconds_left);
743             # we have now moved forward to $etime
744             $weektime = $etime;
745
746           } #while $seconds_left
747           # this is why we need regionnum/rate_region....
748           warn "  (rate region $rate_region)\n" if $DEBUG;
749
750           $classnum = $rate_detail->classnum;
751           $charge = sprintf('%.2f', $charge + 0.000001); # NOW round it.
752           warn "Incrementing \$charges by $charge.  Now $charges\n" if $DEBUG;
753           $charges += $charge;
754
755           @call_details = (
756             $cdr->downstream_csv( 'format'         => $output_format,
757                                   'granularity'    => $rate_detail->sec_granularity, 
758                                   'seconds'        => ($use_duration ?
759                                                        $cdr->duration :
760                                                        $cdr->billsec),
761                                   'charge'         => $charge,
762                                   'pretty_dst'     => $pretty_destnum,
763                                   'dst_regionname' => $regionname,
764                                 )
765           );
766         } #if(there is a rate_detail)
767  
768
769         if ( $charge > 0 ) {
770           #just use FS::cust_bill_pkg_detail objects?
771           my $call_details;
772           my $phonenum = $svc_x->phonenum;
773
774           if ( scalar(@call_details) == 1 ) {
775             $call_details =
776               [ 'C',
777                 $call_details[0],
778                 $charge,
779                 $classnum,
780                 $phonenum,
781                 $cdr->accountcode,
782                 $seconds,
783                 $regionname,
784               ];
785           } else { #only used for $rating_method eq 'upstream' now
786             $csv->combine(@call_details);
787             $call_details =
788               [ 'C',
789                 $csv->string,
790                 $charge,
791                 $classnum,
792                 $phonenum,
793                 $cdr->accountcode,
794                 $seconds,
795                 $regionname,
796               ];
797           }
798           warn "  adding details on charge to invoice: [ ".
799               join(', ', @{$call_details} ). " ]"
800             if ( $DEBUG && ref($call_details) );
801           push @invoice_details_sort, [ $call_details, $cdr->calldate_unix ];
802         }
803
804         # if the customer flag is on, call "downstream_csv" or something
805         # like it to export the call downstream!
806         # XXX price plan option to pick format, or something...
807         #$downstream_cdr .= $cdr->downstream_csv( 'format' => 'XXX format' )
808         #  if $spool_cdr;
809
810         my $error = $cdr->set_status_and_rated_price( 'done',
811                                                       $charge,
812                                                       $cust_svc->svcnum,
813                                                     );
814         die $error if $error;
815
816       }
817
818     } # $cdr
819  
820     my @sorted_invoice_details = sort { @{$a}[1] <=> @{$b}[1] } @invoice_details_sort;
821     foreach my $sorted_call_detail ( @sorted_invoice_details ) {
822         push @$details, @{$sorted_call_detail}[0];
823     }
824
825   } # $cust_svc
826
827   unshift @$details, [ 'C',
828                        FS::cdr::invoice_header($output_format),
829                        '',
830                        '',
831                        '',
832                        '',
833                        '',
834                      ]
835     if @$details && $rating_method ne 'upstream';
836
837 #  if ( $spool_cdr && length($downstream_cdr) ) {
838 #
839 #    use FS::UID qw(datasrc);
840 #    my $dir = '/usr/local/etc/freeside/export.'. datasrc. '/cdr';
841 #    mkdir $dir, 0700 unless -d $dir;
842 #    $dir .= '/'. $cust_pkg->custnum.
843 #    mkdir $dir, 0700 unless -d $dir;
844 #    my $filename = time2str("$dir/CDR%Y%m%d-spool.CSV", time); #XXX invoice date instead?  would require changing the order things are generated in cust_main::bill insert cust_bill first - with transactions it could be done though
845 #
846 #    push @{ $param->{'precommit_hooks'} },
847 #         sub {
848 #               #lock the downstream spool file and append the records 
849 #               use Fcntl qw(:flock);
850 #               use IO::File;
851 #               my $spool = new IO::File ">>$filename"
852 #                 or die "can't open $filename: $!\n";
853 #               flock( $spool, LOCK_EX)
854 #                 or die "can't lock $filename: $!\n";
855 #               seek($spool, 0, 2)
856 #                 or die "can't seek to end of $filename: $!\n";
857 #               print $spool $downstream_cdr;
858 #               flock( $spool, LOCK_UN );
859 #               close $spool;
860 #             };
861 #
862 #  } #if ( $spool_cdr && length($downstream_cdr) )
863
864   $charges;
865 }
866
867 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
868 sub check_chargable {
869   my( $self, $cdr, %flags ) = @_;
870
871   #should have some better way of checking these options from a hash
872   #or something
873
874   my @opt = qw(
875     use_amaflags
876     use_disposition
877     use_disposition_taqua
878     use_carrierid
879     use_cdrtypenum
880     skip_dst_prefix
881     skip_dcontext
882     skip_dstchannel_prefix
883     skip_src_length_more noskip_src_length_accountcode_tollfree
884     skip_dst_length_less noskip_dst_length_accountcode_tollfree
885     skip_lastapp
886     skip_max_callers
887   );
888   foreach my $opt (grep !exists($flags{option_cache}->{$_}), @opt ) {
889     $flags{option_cache}->{$opt} = $self->option($opt, 1);
890   }
891   my %opt = %{ $flags{option_cache} };
892
893   return 'amaflags != 2'
894     if $opt{'use_amaflags'} && $cdr->amaflags != 2;
895
896   return 'disposition != ANSWERED'
897     if $opt{'use_disposition'} && $cdr->disposition ne 'ANSWERED';
898
899   return "disposition != 100"
900     if $opt{'use_disposition_taqua'} && $cdr->disposition != 100;
901
902   return "carrierid != $opt{'use_carrierid'}"
903     if length($opt{'use_carrierid'})
904     && $cdr->carrierid ne $opt{'use_carrierid'} #ne otherwise 0 matches ''
905     && ! $flags{'da_rewrote'};
906
907   return "cdrtypenum != $opt{'use_cdrtypenum'}"
908     if length($opt{'use_cdrtypenum'})
909     && $cdr->cdrtypenum ne $opt{'use_cdrtypenum'}; #ne otherwise 0 matches ''
910
911   foreach(split(',',$opt{'skip_dst_prefix'})) {
912     return "dst starts with '$_'"
913     if length($_) && substr($cdr->dst,0,length($_)) eq $_;
914   }
915
916   return "dcontext IN ( $opt{'skip_dcontext'} )"
917     if $opt{'skip_dcontext'} =~ /\S/
918     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $opt{'skip_dcontext'});
919
920   my $len_prefix = length($opt{'skip_dstchannel_prefix'});
921   return "dstchannel starts with $opt{'skip_dstchannel_prefix'}"
922     if $len_prefix
923     && substr($cdr->dstchannel,0,$len_prefix) eq $opt{'skip_dstchannel_prefix'};
924
925   my $dst_length = $opt{'skip_dst_length_less'};
926   return "destination less than $dst_length digits"
927     if $dst_length && length($cdr->dst) < $dst_length
928     && ! ( $opt{'noskip_dst_length_accountcode_tollfree'}
929             && $cdr->is_tollfree('accountcode')
930          );
931
932   return "lastapp is $opt{'skip_lastapp'}"
933     if length($opt{'skip_lastapp'}) && $cdr->lastapp eq $opt{'skip_lastapp'};
934
935   my $src_length = $opt{'skip_src_length_more'};
936   if ( $src_length ) {
937
938     if ( $opt{'noskip_src_length_accountcode_tollfree'} ) {
939
940       if ( $cdr->is_tollfree('accountcode') ) {
941         return "source less than or equal to $src_length digits"
942           if length($cdr->src) <= $src_length;
943       } else {
944         return "source more than $src_length digits"
945           if length($cdr->src) > $src_length;
946       }
947
948     } else {
949       return "source more than $src_length digits"
950         if length($cdr->src) > $src_length;
951     }
952
953   }
954
955   return "max_callers <= $opt{skip_max_callers}"
956     if length($opt{'skip_max_callers'})
957       and length($cdr->max_callers)
958       and $cdr->max_callers <= $opt{'skip_max_callers'};
959
960   #all right then, rate it
961   '';
962 }
963
964 sub is_free {
965   0;
966 }
967
968 #  This equates svc_phone records; perhaps svc_phone should have a field
969 #  to indicate it represents a line
970 sub calc_units {    
971   my($self, $cust_pkg ) = @_;
972   my $count = 0;
973   if ( $self->option('count_available_phones', 1)) {
974     map { $count += ( $_->quantity || 0 ) }
975       grep { $_->part_svc->svcdb eq 'svc_phone' }
976       $cust_pkg->part_pkg->pkg_svc;
977   } else {
978     $count = 
979       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
980   }
981   $count;
982 }
983
984 1;
985