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