voip_cdr call rating by day and time, RT#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               $etime = 0;
606             } 
607             elsif($ratetimenum) {
608               # This is a timed rate, so go to the etime of this interval.
609               # If it's followed by another timed rate, the stime of that 
610               # interval should match the etime of this one.
611               my $interval = $rate_detail->rate_time->contains($weektime);
612               $etime = $interval->etime;
613             }
614             else {
615               # This is a default rate, so use the stime of the next 
616               # interval in the sequence.
617               my $next_int = first { $_->stime > $weektime } 
618                               @{ $interval_cache{$regionnum} };
619               if ($next_int) {
620                 $etime = $next_int->stime;
621               }
622               else {
623                 # weektime is near the end of the week, so decrement 
624                 # it by a full week and use the stime of the first 
625                 # interval.
626                 $weektime -= (3600*24*7);
627                 $etime = $interval_cache{$regionnum}->[0]->stime;
628               }
629             }
630
631             my $charge_sec = min($seconds_left, $etime - $weektime);
632
633             $seconds_left -= $charge_sec;
634             $seconds += $charge_sec;
635
636             $included_min{$regionnum}{$ratetimenum} = $rate_detail->min_included
637               unless exists $included_min{$regionnum}{$ratetimenum};
638
639             my $granularity = $rate_detail->sec_granularity;
640
641             # should this be done in every rate interval?
642             $charge_sec += $granularity - ( $charge_sec % $granularity )
643               if $charge_sec   # don't granular-ize 0 billsec calls (bills them)
644               && $granularity; # 0 is per call
645             my $minutes = sprintf("%.1f", $charge_sec / 60);
646             $minutes =~ s/\.0$// if $granularity == 60;
647
648             # per call rather than per minute
649             $minutes = 1 unless $granularity;
650             $seconds_left = 0 unless $granularity;
651
652             $included_min{$regionnum}{$ratetimenum} -= $minutes;
653             
654             if ( $included_min{$regionnum}{$ratetimenum} <= 0 ) {
655               my $charge_min = 0 - $included_min{$regionnum}{$ratetimenum}; #XXX should preserve
656                                                               #(display?) this
657               $included_min{$regionnum}{$ratetimenum} = 0;
658               $charge += sprintf('%.2f', ($rate_detail->min_charge * $charge_min)
659                                          + 0.00000001 ); #so 1.005 rounds to 1.01
660               $total_minutes += $minutes;
661             }
662
663             # choose next rate_detail
664             $rate_detail = $rate->dest_detail({ 'countrycode' => $countrycode,
665                                                 'phonenum'    => $number,
666                                                 'weektime'    => $etime })
667                     if($seconds_left);
668             # we have now moved forward to $etime
669             $weektime = $etime;
670
671           } #while $seconds_left
672           # this is why we need regionnum/rate_region....
673           warn "  (rate region $rate_region)\n" if $DEBUG;
674
675           $classnum = $rate_detail->classnum;
676           $charge = sprintf('%.2f', $charge);
677
678           @call_details = (
679             $cdr->downstream_csv( 'format'         => $output_format,
680                                   'granularity'    => $rate_detail->sec_granularity, 
681                                   'minutes'        => $total_minutes,
682                                   'charge'         => $charge,
683                                   'pretty_dst'     => $pretty_destnum,
684                                   'dst_regionname' => $regionname,
685                                 )
686           );
687         } #if(there is a rate_detail)
688  
689
690         if ( $charge > 0 ) {
691           #just use FS::cust_bill_pkg_detail objects?
692           warn "Incrementing \$charges by $charge.  Now $charges\n" if $DEBUG;
693           $charges += $charge;
694           my $call_details;
695           my $phonenum = $cust_svc->svc_x->phonenum;
696
697           #if ( $self->option('rating_method') eq 'upstream_simple' ) {
698           if ( scalar(@call_details) == 1 ) {
699             $call_details =
700               [ 'C',
701                 $call_details[0],
702                 $charge,
703                 $classnum,
704                 $phonenum,
705                 $seconds,
706                 $regionname,
707               ];
708           } else { #only used for $rating_method eq 'upstream' now
709             $csv->combine(@call_details);
710             $call_details =
711               [ 'C',
712                 $csv->string,
713                 $charge,
714                 $classnum,
715                 $phonenum,
716                 $seconds,
717                 $regionname,
718               ];
719           }
720           warn "  adding details on charge to invoice: [ ".
721               join(', ', @{$call_details} ). " ]"
722             if ( $DEBUG && ref($call_details) );
723           push @$details, $call_details; #\@call_details,
724         }
725
726         # if the customer flag is on, call "downstream_csv" or something
727         # like it to export the call downstream!
728         # XXX price plan option to pick format, or something...
729         #$downstream_cdr .= $cdr->downstream_csv( 'format' => 'XXX format' )
730         #  if $spool_cdr;
731
732         my $error = $cdr->set_status_and_rated_price( 'done',
733                                                       $charge,
734                                                       $cust_svc->svcnum,
735                                                     );
736         die $error if $error;
737
738       }
739
740     } # $cdr
741
742   } # $cust_svc
743
744   unshift @$details, [ 'C',
745                        FS::cdr::invoice_header($output_format),
746                        '',
747                        '',
748                        '',
749                        '',
750                        '',
751                      ]
752     if @$details && $rating_method ne 'upstream';
753
754 #  if ( $spool_cdr && length($downstream_cdr) ) {
755 #
756 #    use FS::UID qw(datasrc);
757 #    my $dir = '/usr/local/etc/freeside/export.'. datasrc. '/cdr';
758 #    mkdir $dir, 0700 unless -d $dir;
759 #    $dir .= '/'. $cust_pkg->custnum.
760 #    mkdir $dir, 0700 unless -d $dir;
761 #    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
762 #
763 #    push @{ $param->{'precommit_hooks'} },
764 #         sub {
765 #               #lock the downstream spool file and append the records 
766 #               use Fcntl qw(:flock);
767 #               use IO::File;
768 #               my $spool = new IO::File ">>$filename"
769 #                 or die "can't open $filename: $!\n";
770 #               flock( $spool, LOCK_EX)
771 #                 or die "can't lock $filename: $!\n";
772 #               seek($spool, 0, 2)
773 #                 or die "can't seek to end of $filename: $!\n";
774 #               print $spool $downstream_cdr;
775 #               flock( $spool, LOCK_UN );
776 #               close $spool;
777 #             };
778 #
779 #  } #if ( $spool_cdr && length($downstream_cdr) )
780
781   $charges;
782 }
783
784 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
785 sub check_chargable {
786   my( $self, $cdr, %flags ) = @_;
787
788   #should have some better way of checking these options from a hash
789   #or something
790
791   my @opt = qw(
792     use_amaflags
793     use_disposition
794     use_disposition_taqua
795     use_carrierid
796     use_cdrtypenum
797     skip_dcontext
798     skip_dstchannel_prefix
799     skip_src_length_more noskip_src_length_accountcode_tollfree
800     skip_dst_length_less
801     skip_lastapp
802   );
803   foreach my $opt (grep !exists($flags{option_cache}->{$_}), @opt ) {
804     $flags{option_cache}->{$opt} = $self->option($opt, 1);
805   }
806   my %opt = %{ $flags{option_cache} };
807
808   return 'amaflags != 2'
809     if $opt{'use_amaflags'} && $cdr->amaflags != 2;
810
811   return 'disposition != ANSWERED'
812     if $opt{'use_disposition'} && $cdr->disposition ne 'ANSWERED';
813
814   return "disposition != 100"
815     if $opt{'use_disposition_taqua'} && $cdr->disposition != 100;
816
817   return "carrierid != $opt{'use_carrierid'}"
818     if length($opt{'use_carrierid'})
819     && $cdr->carrierid ne $opt{'use_carrierid'} #ne otherwise 0 matches ''
820     && ! $flags{'da_rewrote'};
821
822   return "cdrtypenum != $opt{'use_cdrtypenum'}"
823     if length($opt{'use_cdrtypenum'})
824     && $cdr->cdrtypenum ne $opt{'use_cdrtypenum'}; #ne otherwise 0 matches ''
825
826   return "dcontext IN ( $opt{'skip_dcontext'} )"
827     if $opt{'skip_dcontext'} =~ /\S/
828     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $opt{'skip_dcontext'});
829
830   my $len_prefix = length($opt{'skip_dstchannel_prefix'});
831   return "dstchannel starts with $opt{'skip_dstchannel_prefix'}"
832     if $len_prefix
833     && substr($cdr->dstchannel,0,$len_prefix) eq $opt{'skip_dstchannel_prefix'};
834
835   my $dst_length = $opt{'skip_dst_length_less'};
836   return "destination less than $dst_length digits"
837     if $dst_length && length($cdr->dst) < $dst_length;
838
839   return "lastapp is $opt{'skip_lastapp'}"
840     if length($opt{'skip_lastapp'}) && $cdr->lastapp eq $opt{'skip_lastapp'};
841
842   my $src_length = $opt{'skip_src_length_more'};
843   if ( $src_length ) {
844
845     if ( $opt{'noskip_src_length_accountcode_tollfree'} ) {
846
847       if ( $cdr->is_tollfree('accountcode') ) {
848         return "source less than or equal to $src_length digits"
849           if length($cdr->src) <= $src_length;
850       } else {
851         return "source more than $src_length digits"
852           if length($cdr->src) > $src_length;
853       }
854
855     } else {
856       return "source more than $src_length digits"
857         if length($cdr->src) > $src_length;
858     }
859
860   }
861
862   #all right then, rate it
863   '';
864 }
865
866 sub is_free {
867   0;
868 }
869
870 #  This equates svc_phone records; perhaps svc_phone should have a field
871 #  to indicate it represents a line
872 sub calc_units {    
873   my($self, $cust_pkg ) = @_;
874   my $count = 0;
875   if ( $self->option('count_available_phones', 1)) {
876     map { $count += ( $_->quantity || 0 ) }
877       grep { $_->part_svc->svcdb eq 'svc_phone' }
878       $cust_pkg->part_pkg->pkg_svc;
879   } else {
880     $count = 
881       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
882   }
883   $count;
884 }
885
886 1;
887