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