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