CDR rewriting and included-calls feature, #16271
[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 Tie::IxHash;
7 use Date::Format;
8 use Text::CSV_XS;
9 use FS::Conf;
10 use FS::Record qw(qsearchs qsearch);
11 use FS::cdr;
12 use FS::detail_format;
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     'calls_included' => { 'name' => 'Number of calls included at no usage charge', },
104
105     'min_included' => { 'name' => 'Minutes included when using the "single price per minute" rating method or when using the "prefix" rating method ("region group" billing)',
106                     },
107
108     'min_charge' => { 'name' => 'Charge per minute when using "single price per minute" rating method',
109                     },
110
111     'sec_granularity' => { 'name' => 'Granularity when using "single price per minute" rating method',
112                            'type' => 'select',
113                            'select_options' => \%granularity,
114                          },
115
116     'ignore_unrateable' => { 'name' => 'Handling of calls without a rate in the rate table',
117                              'type' => 'select',
118                              'select_options' => \%unrateable_opts,
119                            },
120
121     'default_prefix' => { 'name'    => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
122                           'default' => '+1',
123                         },
124
125     'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
126                        'type' => 'checkbox'
127                      },
128
129     'domestic_prefix' => { 'name'    => 'Destination prefix for domestic CDR records',
130                            'default' => '1',
131                          },
132
133 #    'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
134 #                                    'type' => 'checkbox',
135 #                                  },
136
137     'international_prefix' => { 'name'    => 'Destination prefix for international CDR records',
138                                 'default' => '011',
139                               },
140
141     'disable_tollfree' => { 'name' => 'Disable automatic toll-free processing',
142                             'type' => 'checkbox',
143                           },
144
145     'use_amaflags' => { 'name' => 'Only charge for CDRs where the amaflags field is set to "2" ("BILL"/"BILLING").',
146                         'type' => 'checkbox',
147                       },
148
149     'use_carrierid' => { 'name' => 'Only charge for CDRs where the Carrier ID is set to: ',
150                          },
151
152     'use_cdrtypenum' => { 'name' => 'Only charge for CDRs where the CDR Type is set to: ',
153                          },
154     
155     'ignore_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is set to: ',
156                          },
157     
158     'ignore_disposition' => { 'name' => 'Do not charge for CDRs where the Disposition is set to any of these (comma-separated) values: ',
159                          },
160     
161     'disposition_in' => { 'name' => 'Only charge for CDRs where the Disposition is set to any of these (comma-separated) values: ',
162                          },
163
164     'skip_dst_prefix' => { 'name' => 'Do not charge for CDRs where the destination number starts with any of these values: ',
165     },
166
167     'skip_dcontext' => { 'name' => 'Do not charge for CDRs where the dcontext is set to any of these (comma-separated) values: ',
168                        },
169
170     'skip_dstchannel_prefix' => { 'name' => 'Do not charge for CDRs where the dstchannel starts with:',
171                                 },
172
173     'skip_src_length_more' => { 'name' => 'Do not charge for CDRs where the source is more than this many digits:',
174                               },
175
176     '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',
177                                                   'type' => 'checkbox',
178                                                 },
179
180     'accountcode_tollfree_ratenum' => {
181       'name' => 'Optional alternate rate plan when accountcode is toll free: ',
182       'type' => 'select',
183       'select_table'  => 'rate',
184       'select_key'    => 'ratenum',
185       'select_label'  => 'ratename',
186       'disable_empty' => 0,
187       'empty_label'   => '',
188     },
189
190     'skip_dst_length_less' => { 'name' => 'Do not charge for CDRs where the destination is less than this many digits:',
191                               },
192
193     'noskip_dst_length_accountcode_tollfree' => { 'name' => 'Do charge for CDRs where dst is less than the specified digits, when accountcode is toll free',
194                                                   'type' => 'checkbox',
195                                                 },
196
197     'skip_lastapp' => { 'name' => 'Do not charge for CDRs where the lastapp matches this value: ',
198                       },
199
200     'skip_max_callers' => { 'name' => 'Do not charge for CDRs where max_callers is less than or equal to this value: ',
201                           },
202
203     'use_duration'   => { 'name' => 'Calculate usage based on the duration field instead of the billsec field',
204                           'type' => 'checkbox',
205                         },
206
207     '411_rewrite' => { 'name' => 'Rewrite these (comma-separated) destination numbers to 411 for rating purposes (also ignore any carrierid check): ',
208                       },
209
210     #false laziness w/cdr_termination.pm
211     'output_format' => { 'name' => 'CDR invoice display format',
212                          'type' => 'select',
213                          'select_options' => { FS::cdr::invoice_formats() },
214                          'default'        => 'default', #XXX test
215                        },
216
217     'usage_section' => { 'name' => 'Section in which to place usage charges (whether separated or not): ',
218                        },
219
220     'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
221                           'type' => 'checkbox',
222                         },
223
224     'usage_mandate' => { 'name' => 'Always put usage details in separate section',
225                           'type' => 'checkbox',
226                        },
227     #eofalse
228
229     'bill_every_call' => { 'name' => 'Generate an invoice immediately for every call (as well any setup fee, upon first payment).  Useful for prepaid.',
230                            'type' => 'checkbox',
231                          },
232
233     'bill_inactive_svcs' => { 'name' => 'Bill for all phone numbers that were active during the billing period',
234                               'type' => 'checkbox',
235                             },
236
237     '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.',
238                            'type' => 'checkbox',
239                          },
240
241     #XXX also have option for an external db?  these days we suck them into ours
242 #    'cdr_location' => { 'name' => 'CDR database location'
243 #                        'type' => 'select',
244 #                        'select_options' => \%cdr_location,
245 #                        'select_callback' => {
246 #                          'external' => {
247 #                            'enable' => [ 'datasrc', 'username', 'password' ],
248 #                          },
249 #                          'internal' => {
250 #                            'disable' => [ 'datasrc', 'username', 'password' ],
251 #                          }
252 #                        },
253 #                      },
254 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
255 #                   'disabled' => 'Y',
256 #                 },
257 #    'username' => { 'name' => 'External database username',
258 #                    'disabled' => 'Y',
259 #                  },
260 #    'password' => { 'name' => 'External database password',
261 #                    'disabled' => 'Y',
262 #                  },
263
264   },
265   'fieldorder' => [qw(
266                        recur_temporality
267                        recur_method cutoff_day ),
268                        FS::part_pkg::prorate_Mixin::fieldorder,
269                     qw(
270                        cdr_svc_method
271                        rating_method ratenum intrastate_ratenum 
272                        calls_included
273                        min_charge min_included sec_granularity
274                        ignore_unrateable
275                        default_prefix
276                        disable_src
277                        domestic_prefix international_prefix
278                        disable_tollfree
279                        use_amaflags
280                        use_carrierid 
281                        use_cdrtypenum ignore_cdrtypenum
282                        ignore_disposition disposition_in
283                        skip_dcontext skip_dst_prefix 
284                        skip_dstchannel_prefix skip_src_length_more 
285                        noskip_src_length_accountcode_tollfree
286                        accountcode_tollfree_ratenum
287                        skip_dst_length_less
288                        noskip_dst_length_accountcode_tollfree
289                        skip_lastapp
290                        skip_max_callers
291                        use_duration
292                        411_rewrite
293                        output_format usage_mandate summarize_usage usage_section
294                        bill_every_call bill_inactive_svcs
295                        count_available_phones suspend_bill 
296                      )
297                   ],
298   'weight' => 40,
299 );
300
301 sub price_info {
302     my $self = shift;
303     my $str = $self->SUPER::price_info;
304     $str .= " plus usage" if $str;
305     $str;
306 }
307
308 sub calc_recur {
309   my $self = shift;
310   my($cust_pkg, $sdate, $details, $param ) = @_;
311
312   my $charges = 0;
313
314   $charges += $self->calc_usage(@_);
315   $charges += $self->calc_recur_Common(@_);
316
317   $charges;
318
319 }
320
321 # use the default
322 #sub calc_cancel {
323 #  my $self = shift;
324 #  my($cust_pkg, $sdate, $details, $param ) = @_;
325 #
326 #  $self->calc_usage(@_);
327 #}
328
329 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
330
331 sub calc_usage {
332   my $self = shift;
333   my($cust_pkg, $sdate, $details, $param ) = @_;
334
335   #my $last_bill = $cust_pkg->last_bill;
336   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
337
338   return 0
339     if $self->recur_temporality eq 'preceding'
340     && ( $last_bill eq '' || $last_bill == 0 );
341
342   my $charges = 0;
343
344   my $included_min = $self->option('min_included', 1) || 0; #single price rating
345   my $included_calls = $self->option('calls_included', 1) || 0;
346
347   my $cdr_svc_method    = $self->option('cdr_svc_method',1)||'svc_phone.phonenum';
348   my $rating_method     = $self->option('rating_method') || 'prefix';
349   my $region_group_included_min = $self->option('min_included',1) || 0;
350   my %region_group_included_min = ();
351
352   my $output_format     = $self->option('output_format', 'Hush!')
353                           || ( $rating_method eq 'upstream_simple'
354                                  ? 'simple'
355                                  : 'default'
356                              );
357
358   my $formatter = FS::detail_format->new($output_format, buffer => $details);
359
360   my $use_duration = $self->option('use_duration');
361
362   my($svc_table, $svc_field) = split('\.', $cdr_svc_method);
363
364   my @cust_svc;
365   if( $self->option('bill_inactive_svcs',1) ) {
366     #XXX in this mode do we need to restrict the set of CDRs by date also?
367     @cust_svc = $cust_pkg->h_cust_svc($$sdate, $last_bill);
368   }
369   else {
370     @cust_svc = $cust_pkg->cust_svc;
371   }
372   @cust_svc = grep { $_->part_svc->svcdb eq $svc_table } @cust_svc;
373
374   foreach my $cust_svc (@cust_svc) {
375
376     my $svc_x;
377     if( $self->option('bill_inactive_svcs',1) ) {
378       $svc_x = $cust_svc->h_svc_x($$sdate, $last_bill);
379     }
380     else {
381       $svc_x = $cust_svc->svc_x;
382     }
383
384     my %options = (
385         'disable_src'    => $self->option('disable_src'),
386         'default_prefix' => $self->option('default_prefix'),
387         'cdrtypenum'     => $self->option('use_cdrtypenum'),
388         'status'         => '',
389         'for_update'     => 1,
390       );  # $last_bill, $$sdate )
391     $options{'by_svcnum'} = 1 if $svc_field eq 'svcnum';
392
393     #my @invoice_details_sort;
394
395     #first rate any outstanding CDRs not yet rated
396     foreach my $cdr (
397       $svc_x->get_cdrs( %options )
398     ) {
399
400       my $error = $cdr->rate(
401         'part_pkg'                          => $self,
402         'svcnum'                            => $svc_x->svcnum,
403         'single_price_included_min'         => \$included_min,
404         'region_group_included_min'         => \$region_group_included_min,
405         'region_group_included_min_hashref' => \%region_group_included_min,
406       );
407       die $error if $error; #??
408
409     } # $cdr
410
411     #then add details to invoices & get a total
412     $options{'status'} = 'rated';
413
414     foreach my $cdr (
415       $svc_x->get_cdrs( %options ) 
416     ) {
417       my $error;
418       # at this point we officially Do Not Care about the rating method
419       if ( $included_calls > 0 ) {
420         $included_calls--;
421         #$charges += 0, obviously
422         #but don't set the rated price to zero--there should be a record
423         $error = $cdr->set_status('no-charge');
424       }
425       else {
426         $charges += $cdr->rated_price;
427         $error = $cdr->set_status('done');
428       }
429       die $error if $error;
430       $formatter->append($cdr);
431     }
432   }
433
434   $formatter->finish; #writes into $details
435   unshift @$details, $formatter->header if @$details;
436
437   $charges;
438 }
439
440 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
441 sub check_chargable {
442   my( $self, $cdr, %flags ) = @_;
443
444   return 'amaflags != 2'
445     if $self->option_cacheable('use_amaflags') && $cdr->amaflags != 2;
446
447   return "disposition NOT IN ( $self->option_cacheable('disposition_in') )"
448     if $self->option_cacheable('disposition_in') =~ /\S/
449     && !grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $self->option_cacheable('disposition_in'));
450   
451   return "disposition IN ( $self->option_cacheable('ignore_disposition') )"
452     if $self->option_cacheable('ignore_disposition') =~ /\S/
453     && grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $self->option_cacheable('ignore_disposition'));
454
455   foreach(split(/\s*,\s*/, $self->option_cacheable('skip_dst_prefix'))) {
456     return "dst starts with '$_'"
457     if length($_) && substr($cdr->dst,0,length($_)) eq $_;
458   }
459
460   return "carrierid != $self->option_cacheable('use_carrierid')"
461     if length($self->option_cacheable('use_carrierid'))
462     && $cdr->carrierid ne $self->option_cacheable('use_carrierid') #ne otherwise 0 matches ''
463     && ! $flags{'da_rewrote'};
464
465   # unlike everything else, use_cdrtypenum is applied in FS::svc_x::get_cdrs.
466   return "cdrtypenum != $self->option_cacheable('use_cdrtypenum')"
467     if length($self->option_cacheable('use_cdrtypenum'))
468     && $cdr->cdrtypenum ne $self->option_cacheable('use_cdrtypenum'); #ne otherwise 0 matches ''
469   
470   return "cdrtypenum == $self->option_cacheable('ignore_cdrtypenum')"
471     if length($self->option_cacheable('ignore_cdrtypenum'))
472     && $cdr->cdrtypenum eq $self->option_cacheable('ignore_cdrtypenum'); #eq otherwise 0 matches ''
473
474   return "dcontext IN ( $self->option_cacheable('skip_dcontext') )"
475     if $self->option_cacheable('skip_dcontext') =~ /\S/
476     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $self->option_cacheable('skip_dcontext'));
477
478   my $len_prefix = length($self->option_cacheable('skip_dstchannel_prefix'));
479   return "dstchannel starts with $self->option_cacheable('skip_dstchannel_prefix')"
480     if $len_prefix
481     && substr($cdr->dstchannel,0,$len_prefix) eq $self->option_cacheable('skip_dstchannel_prefix');
482
483   my $dst_length = $self->option_cacheable('skip_dst_length_less');
484   return "destination less than $dst_length digits"
485     if $dst_length && length($cdr->dst) < $dst_length
486     && ! ( $self->option_cacheable('noskip_dst_length_accountcode_tollfree')
487             && $cdr->is_tollfree('accountcode')
488          );
489
490   return "lastapp is $self->option_cacheable('skip_lastapp')"
491     if length($self->option_cacheable('skip_lastapp')) && $cdr->lastapp eq $self->option_cacheable('skip_lastapp');
492
493   my $src_length = $self->option_cacheable('skip_src_length_more');
494   if ( $src_length ) {
495
496     if ( $self->option_cacheable('noskip_src_length_accountcode_tollfree') ) {
497
498       if ( $cdr->is_tollfree('accountcode') ) {
499         return "source less than or equal to $src_length digits"
500           if length($cdr->src) <= $src_length;
501       } else {
502         return "source more than $src_length digits"
503           if length($cdr->src) > $src_length;
504       }
505
506     } else {
507       return "source more than $src_length digits"
508         if length($cdr->src) > $src_length;
509     }
510
511   }
512
513   return "max_callers <= ". $self->option_cacheable('skip_max_callers')
514     if length($self->option_cacheable('skip_max_callers'))
515       and length($cdr->max_callers)
516       and $cdr->max_callers <= $self->option_cacheable('skip_max_callers');
517
518   #all right then, rate it
519   '';
520 }
521
522 sub is_free {
523   0;
524 }
525
526 #  This equates svc_phone records; perhaps svc_phone should have a field
527 #  to indicate it represents a line
528 sub calc_units {    
529   my($self, $cust_pkg ) = @_;
530   my $count = 0;
531   if ( $self->option('count_available_phones', 1)) {
532     map { $count += ( $_->quantity || 0 ) }
533       grep { $_->part_svc->svcdb eq 'svc_phone' }
534       $cust_pkg->part_pkg->pkg_svc;
535   } else {
536     $count = 
537       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
538   }
539   $count;
540 }
541
542 # tells whether cust_bill_pkg_detail should return a single line for 
543 # each phonenum
544 sub sum_usage {
545   my $self = shift;
546   $self->option('output_format') =~ /^sum_/;
547 }
548
549 # and whether cust_bill should show a detail line for the service label 
550 # (separate from usage details)
551 sub hide_svc_detail {
552   my $self = shift;
553   $self->option('output_format') =~ /^sum_/;
554 }
555
556
557 1;
558