typo
[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   'svc_pbx.ip.src'     => 'PBX name to source IP address',
24   'svc_pbx.ip.dst'     => 'PBX name to destination IP address',
25 ;
26
27 tie my %rating_method, 'Tie::IxHash',
28   'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
29 #  'upstream' => 'Rate calls based on upstream data: If the call type is "1", map the upstream rate ID directly to an internal rate (rate_detail), otherwise, pass the upstream price through directly.',
30   'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
31   'single_price' => 'A single price per minute for all calls.',
32 ;
33
34 #tie my %cdr_location, 'Tie::IxHash',
35 #  'internal' => 'Internal: CDR records imported into the internal CDR table',
36 #  'external' => 'External: CDR records queried directly from an external '.
37 #                'Asterisk (or other?) CDR table',
38 #;
39
40 tie my %temporalities, 'Tie::IxHash',
41   'upcoming'  => "Upcoming (future)",
42   'preceding' => "Preceding (past)",
43 ;
44
45 tie my %granularity, 'Tie::IxHash', FS::rate_detail::granularities();
46
47 # previously "1" was "ignore"
48 tie my %unrateable_opts, 'Tie::IxHash',
49   '' => 'Exit with a fatal error',
50   1  => 'Ignore and continue',
51   2  => 'Flag for later review',
52 ;
53
54 %info = (
55   'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
56   'shortname' => 'VoIP/telco CDR rating (standard)',
57   'inherit_fields' => [ 'prorate_Mixin', 'global_Mixin' ],
58   'fields' => {
59     'suspend_bill' => { 'name' => 'Continue recurring billing while suspended',
60                         'type' => 'checkbox',
61                       },
62     #false laziness w/flat.pm
63     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
64                              'type' => 'select',
65                              'select_options' => \%temporalities,
66                            },
67
68     'cutoff_day'    => { 'name' => 'Billing Day (1 - 28) for prorating or '.
69                                    'subscription',
70                          'default' => '1',
71                        },
72     'recur_method'  => { 'name' => 'Recurring fee method',
73                          #'type' => 'radio',
74                          #'options' => \%recur_method,
75                          'type' => 'select',
76                          'select_options' => \%FS::part_pkg::recur_Common::recur_method,
77                        },
78
79     'cdr_svc_method' => { 'name' => 'CDR service matching method',
80 #                          'type' => 'radio',
81                           'type' => 'select',
82                           'select_options' => \%cdr_svc_method,
83                         },
84
85     'rating_method' => { 'name' => 'Rating method',
86                          'type' => 'radio',
87                          'options' => \%rating_method,
88                        },
89
90     'ratenum'   => { 'name' => 'Rate plan',
91                      'type' => 'select',
92                      'select_table' => 'rate',
93                      'select_key'   => 'ratenum',
94                      'select_label' => 'ratename',
95                    },
96                    
97     'intrastate_ratenum'   => { 'name' => 'Optional alternate intrastate rate plan',
98                      'type' => 'select',
99                      'select_table' => 'rate',
100                      'select_key'   => 'ratenum',
101                      'select_label' => 'ratename',
102                      'disable_empty' => 0,
103                      'empty_label'   => '',
104                    },
105
106     'calls_included' => { 'name' => 'Number of calls included at no usage charge', },
107
108     'min_included' => { 'name' => 'Minutes included when using the "single price per minute" or "prefix" rating method',
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: ',
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 invoice display format',
215                          'type' => 'select',
216                          'select_options' => { FS::cdr::invoice_formats() },
217                          'default'        => 'default', #XXX test
218                        },
219
220     'usage_section' => { 'name' => 'Section in which to place usage charges (whether separated or not): ',
221                        },
222
223     'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
224                           'type' => 'checkbox',
225                         },
226
227     'usage_mandate' => { 'name' => 'Always put usage details in separate section',
228                           'type' => 'checkbox',
229                        },
230     #eofalse
231
232     'usage_nozero' => { 'name' => 'Omit details for included / no-charge calls.',
233                         'type' => 'checkbox',
234                       },
235
236     'bill_every_call' => { 'name' => 'Generate an invoice immediately for every call (as well any setup fee, upon first payment).  Useful for prepaid.',
237                            'type' => 'checkbox',
238                          },
239
240     'bill_inactive_svcs' => { 'name' => 'Bill for all phone numbers that were active during the billing period',
241                               'type' => 'checkbox',
242                             },
243
244     '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.',
245                            'type' => 'checkbox',
246                          },
247
248     #XXX also have option for an external db?  these days we suck them into ours
249 #    'cdr_location' => { 'name' => 'CDR database location'
250 #                        'type' => 'select',
251 #                        'select_options' => \%cdr_location,
252 #                        'select_callback' => {
253 #                          'external' => {
254 #                            'enable' => [ 'datasrc', 'username', 'password' ],
255 #                          },
256 #                          'internal' => {
257 #                            'disable' => [ 'datasrc', 'username', 'password' ],
258 #                          }
259 #                        },
260 #                      },
261 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
262 #                   'disabled' => 'Y',
263 #                 },
264 #    'username' => { 'name' => 'External database username',
265 #                    'disabled' => 'Y',
266 #                  },
267 #    'password' => { 'name' => 'External database password',
268 #                    'disabled' => 'Y',
269 #                  },
270
271   },
272   'fieldorder' => [qw(
273                        recur_temporality
274                        recur_method cutoff_day ),
275                        FS::part_pkg::prorate_Mixin::fieldorder,
276                     qw(
277                        cdr_svc_method
278                        rating_method ratenum intrastate_ratenum 
279                        calls_included
280                        min_charge min_included sec_granularity
281                        ignore_unrateable
282                        default_prefix
283                        disable_src
284                        domestic_prefix international_prefix
285                        disable_tollfree
286                        use_amaflags
287                        use_carrierid 
288                        use_cdrtypenum ignore_cdrtypenum
289                        ignore_disposition disposition_in
290                        skip_dcontext skip_dst_prefix 
291                        skip_dstchannel_prefix skip_src_length_more 
292                        noskip_src_length_accountcode_tollfree
293                        accountcode_tollfree_ratenum
294                        skip_dst_length_less
295                        noskip_dst_length_accountcode_tollfree
296                        skip_lastapp
297                        skip_max_callers
298                        use_duration
299                        411_rewrite
300                        output_format usage_mandate summarize_usage usage_section
301                        bill_every_call bill_inactive_svcs
302                        count_available_phones suspend_bill 
303                      )
304                   ],
305   'weight' => 40,
306 );
307
308 sub price_info {
309     my $self = shift;
310     my $str = $self->SUPER::price_info;
311     $str .= " plus usage" if $str;
312     $str;
313 }
314
315 sub calc_recur {
316   my $self = shift;
317   my($cust_pkg, $sdate, $details, $param ) = @_;
318
319   my $charges = 0;
320
321   $charges += $self->calc_usage(@_);
322   $charges += $self->calc_recur_Common(@_);
323
324   $charges;
325
326 }
327
328 # use the default
329 #sub calc_cancel {
330 #  my $self = shift;
331 #  my($cust_pkg, $sdate, $details, $param ) = @_;
332 #
333 #  $self->calc_usage(@_);
334 #}
335
336 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
337
338 sub calc_usage {
339   my $self = shift;
340   my($cust_pkg, $sdate, $details, $param ) = @_;
341
342   #my $last_bill = $cust_pkg->last_bill;
343   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
344
345   return 0
346     if $self->recur_temporality eq 'preceding'
347     && ( $last_bill eq '' || $last_bill == 0 );
348
349   my $charges = 0;
350
351   my $included_min = $self->option('min_included', 1) || 0; #single price rating
352   my $included_calls = $self->option('calls_included', 1) || 0;
353
354   my $cdr_svc_method    = $self->option('cdr_svc_method',1)||'svc_phone.phonenum';
355   my $rating_method     = $self->option('rating_method') || 'prefix';
356   my $region_group_included_min = $self->option('min_included',1) || 0;
357   my %region_group_included_min = ();
358
359   my $output_format     = $self->option('output_format', 'Hush!')
360                           || ( $rating_method eq 'upstream_simple'
361                                  ? 'simple'
362                                  : 'default'
363                              );
364
365   my $usage_nozero      = $self->option('usage_nozero', 1);
366
367   my $formatter = FS::detail_format->new($output_format, buffer => $details);
368
369   my $use_duration = $self->option('use_duration');
370
371   my($svc_table, $svc_field, $by_ip_addr) = split('\.', $cdr_svc_method);
372
373   my @cust_svc;
374   if( $self->option('bill_inactive_svcs',1) ) {
375     #XXX in this mode do we need to restrict the set of CDRs by date also?
376     @cust_svc = $cust_pkg->h_cust_svc($$sdate, $last_bill);
377   }
378   else {
379     @cust_svc = $cust_pkg->cust_svc;
380   }
381   @cust_svc = grep { $_->part_svc->svcdb eq $svc_table } @cust_svc;
382
383   foreach my $cust_svc (@cust_svc) {
384
385     my $svc_x;
386     if( $self->option('bill_inactive_svcs',1) ) {
387       $svc_x = $cust_svc->h_svc_x($$sdate, $last_bill);
388     }
389     else {
390       $svc_x = $cust_svc->svc_x;
391     }
392
393     my %options = (
394         'disable_src'    => $self->option('disable_src'),
395         'default_prefix' => $self->option('default_prefix'),
396         'cdrtypenum'     => $self->option('use_cdrtypenum'),
397         'status'         => '',
398         'for_update'     => 1,
399       );  # $last_bill, $$sdate )
400     if ( $svc_field eq 'svcnum' ) {
401       $options{'by_svcnum'} = 1;
402     }
403     elsif ($svc_table eq 'svc_pbx' and $svc_field eq 'ip') {
404       $options{'by_ip_addr'} = $by_ip_addr;
405     }
406
407     #my @invoice_details_sort;
408
409     #first rate any outstanding CDRs not yet rated
410     my $cdr_search = $svc_x->psearch_cdrs(%options);
411     $cdr_search->limit(1000);
412     $cdr_search->increment(0); # because we're changing their status as we go
413     while ( my $cdr = $cdr_search->fetch ) {
414
415       my $error = $cdr->rate(
416         'part_pkg'                          => $self,
417         'svcnum'                            => $svc_x->svcnum,
418         'single_price_included_min'         => \$included_min,
419         'region_group_included_min'         => \$region_group_included_min,
420         'region_group_included_min_hashref' => \%region_group_included_min,
421       );
422       die $error if $error; #??
423
424       $cdr_search->adjust(1) if $cdr->freesidestatus eq '';
425       # it was skipped without changing status, so increment the 
426       # offset so that we don't re-fetch it on refill
427
428     } # $cdr
429
430     #then add details to invoices & get a total
431     $options{'status'} = 'rated';
432
433     $cdr_search = $svc_x->psearch_cdrs(%options);
434     $cdr_search->limit(1000);
435     $cdr_search->increment(0);
436     while ( my $cdr = $cdr_search->fetch ) {
437       my $error;
438       # at this point we officially Do Not Care about the rating method
439       if ( $included_calls > 0 ) {
440         $included_calls--;
441         #$charges += 0, obviously
442         #but don't set the rated price to zero--there should be a record
443         $error = $cdr->set_status('no-charge');
444       }
445       else {
446         $charges += $cdr->rated_price;
447         $error = $cdr->set_status('done');
448       }
449       die $error if $error;
450       $formatter->append($cdr) unless $usage_nozero && $cdr->rated_price == 0;
451
452       $cdr_search->adjust(1) if $cdr->freesidestatus eq 'rated';
453     } #$cdr
454   }
455
456   $formatter->finish; #writes into $details
457   unshift @$details, $formatter->header if @$details;
458
459   $charges;
460 }
461
462 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
463 sub check_chargable {
464   my( $self, $cdr, %flags ) = @_;
465
466   return 'amaflags != 2'
467     if $self->option_cacheable('use_amaflags') && $cdr->amaflags != 2;
468
469   return "disposition NOT IN ( $self->option_cacheable('disposition_in') )"
470     if $self->option_cacheable('disposition_in') =~ /\S/
471     && !grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $self->option_cacheable('disposition_in'));
472   
473   return "disposition IN ( $self->option_cacheable('ignore_disposition') )"
474     if $self->option_cacheable('ignore_disposition') =~ /\S/
475     && grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $self->option_cacheable('ignore_disposition'));
476
477   foreach(split(/\s*,\s*/, $self->option_cacheable('skip_dst_prefix'))) {
478     return "dst starts with '$_'"
479     if length($_) && substr($cdr->dst,0,length($_)) eq $_;
480   }
481
482   return "carrierid != $self->option_cacheable('use_carrierid')"
483     if length($self->option_cacheable('use_carrierid'))
484     && $cdr->carrierid ne $self->option_cacheable('use_carrierid') #ne otherwise 0 matches ''
485     && ! $flags{'da_rewrote'};
486
487   # unlike everything else, use_cdrtypenum is applied in FS::svc_x::get_cdrs.
488   return "cdrtypenum != $self->option_cacheable('use_cdrtypenum')"
489     if length($self->option_cacheable('use_cdrtypenum'))
490     && $cdr->cdrtypenum ne $self->option_cacheable('use_cdrtypenum'); #ne otherwise 0 matches ''
491   
492   return "cdrtypenum == $self->option_cacheable('ignore_cdrtypenum')"
493     if length($self->option_cacheable('ignore_cdrtypenum'))
494     && $cdr->cdrtypenum eq $self->option_cacheable('ignore_cdrtypenum'); #eq otherwise 0 matches ''
495
496   return "dcontext IN ( $self->option_cacheable('skip_dcontext') )"
497     if $self->option_cacheable('skip_dcontext') =~ /\S/
498     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $self->option_cacheable('skip_dcontext'));
499
500   my $len_prefix = length($self->option_cacheable('skip_dstchannel_prefix'));
501   return "dstchannel starts with $self->option_cacheable('skip_dstchannel_prefix')"
502     if $len_prefix
503     && substr($cdr->dstchannel,0,$len_prefix) eq $self->option_cacheable('skip_dstchannel_prefix');
504
505   my $dst_length = $self->option_cacheable('skip_dst_length_less');
506   return "destination less than $dst_length digits"
507     if $dst_length && length($cdr->dst) < $dst_length
508     && ! ( $self->option_cacheable('noskip_dst_length_accountcode_tollfree')
509             && $cdr->is_tollfree('accountcode')
510          );
511
512   return "lastapp is $self->option_cacheable('skip_lastapp')"
513     if length($self->option_cacheable('skip_lastapp')) && $cdr->lastapp eq $self->option_cacheable('skip_lastapp');
514
515   my $src_length = $self->option_cacheable('skip_src_length_more');
516   if ( $src_length ) {
517
518     if ( $self->option_cacheable('noskip_src_length_accountcode_tollfree') ) {
519
520       if ( $cdr->is_tollfree('accountcode') ) {
521         return "source less than or equal to $src_length digits"
522           if length($cdr->src) <= $src_length;
523       } else {
524         return "source more than $src_length digits"
525           if length($cdr->src) > $src_length;
526       }
527
528     } else {
529       return "source more than $src_length digits"
530         if length($cdr->src) > $src_length;
531     }
532
533   }
534
535   return "max_callers <= ". $self->option_cacheable('skip_max_callers')
536     if length($self->option_cacheable('skip_max_callers'))
537       and length($cdr->max_callers)
538       and $cdr->max_callers <= $self->option_cacheable('skip_max_callers');
539
540   #all right then, rate it
541   '';
542 }
543
544 sub is_free {
545   0;
546 }
547
548 #  This equates svc_phone records; perhaps svc_phone should have a field
549 #  to indicate it represents a line
550 sub calc_units {    
551   my($self, $cust_pkg ) = @_;
552   my $count = 0;
553   if ( $self->option('count_available_phones', 1)) {
554     map { $count += ( $_->quantity || 0 ) }
555       grep { $_->part_svc->svcdb eq 'svc_phone' }
556       $cust_pkg->part_pkg->pkg_svc;
557   } else {
558     $count = 
559       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
560   }
561   $count;
562 }
563
564 # tells whether cust_bill_pkg_detail should return a single line for 
565 # each phonenum
566 sub sum_usage {
567   my $self = shift;
568   $self->option('output_format') =~ /^sum_/;
569 }
570
571 # and whether cust_bill should show a detail line for the service label 
572 # (separate from usage details)
573 sub hide_svc_detail {
574   my $self = shift;
575   $self->option('output_format') =~ /^sum_/;
576 }
577
578
579 1;
580