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