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