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