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