add disable_tollfree option
[freeside.git] / FS / FS / part_pkg / voip_cdr.pm
1 package FS::part_pkg::voip_cdr;
2
3 use strict;
4 use vars qw(@ISA $DEBUG %info);
5 use Date::Format;
6 use Tie::IxHash;
7 use FS::Conf;
8 use FS::Record qw(qsearchs qsearch);
9 use FS::part_pkg::flat;
10 use FS::cdr;
11 #use FS::rate;
12 #use FS::rate_prefix;
13
14 @ISA = qw(FS::part_pkg::flat);
15
16 $DEBUG = 1;
17
18 tie my %rating_method, 'Tie::IxHash',
19   'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
20   '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.',
21   'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
22 ;
23
24 #tie my %cdr_location, 'Tie::IxHash',
25 #  'internal' => 'Internal: CDR records imported into the internal CDR table',
26 #  'external' => 'External: CDR records queried directly from an external '.
27 #                'Asterisk (or other?) CDR table',
28 #;
29
30 tie my %temporalities, 'Tie::IxHash',
31   'upcoming'  => "Upcoming (future)",
32   'preceding' => "Preceding (past)",
33 ;
34
35 %info = (
36   'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
37   'shortname' => 'VoIP/telco CDR rating (standard)',
38   'fields' => {
39     'setup_fee'     => { 'name' => 'Setup fee for this package',
40                          'default' => 0,
41                        },
42     'recur_fee'     => { 'name' => 'Base recurring fee for this package',
43                          'default' => 0,
44                        },
45
46     #false laziness w/flat.pm
47     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
48                              'type' => 'select',
49                              'select_options' => \%temporalities,
50                            },
51
52     'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
53                                    ' of service at cancellation',
54                          'type' => 'checkbox',
55                        },
56     'ratenum'   => { 'name' => 'Rate plan',
57                      'type' => 'select',
58                      'select_table' => 'rate',
59                      'select_key'   => 'ratenum',
60                      'select_label' => 'ratename',
61                    },
62     'rating_method' => { 'name' => 'Region rating method',
63                          'type' => 'radio',
64                          'options' => \%rating_method,
65                        },
66
67     'default_prefix' => { 'name'    => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
68                           'default' => '+1',
69                         },
70
71     'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
72                        'type' => 'checkbox'
73                      },
74
75     'domestic_prefix' => { 'name'    => 'Destination prefix for domestic CDR records',
76                            'default' => '1',
77                          },
78
79 #    'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
80 #                                    'type' => 'checkbox',
81 #                                  },
82
83     'international_prefix' => { 'name'    => 'Destination prefix for international CDR records',
84                                 'default' => '011',
85                               },
86
87     'disable_tollfree' => { 'name' => 'Disable automatic toll-free processing',
88                             'type' => 'checkbox',
89                           },
90
91     'use_amaflags' => { 'name' => 'Do not charge for CDRs where the amaflags field is not set to "2" ("BILL"/"BILLING").',
92                         'type' => 'checkbox',
93                       },
94
95     'use_disposition' => { 'name' => 'Do not charge for CDRs where the disposition flag is not set to "ANSWERED".',
96                            'type' => 'checkbox',
97                          },
98
99     'use_disposition_taqua' => { 'name' => 'Do not charge for CDRs where the disposition is not set to "100" (Taqua).',
100                                  'type' => 'checkbox',
101                                },
102
103     'use_carrierid' => { 'name' => 'Do not charge for CDRs where the Carrier ID is not set to: ',
104                          },
105
106     'use_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is not set to: ',
107                          },
108
109     '411_rewrite' => { 'name' => 'Rewrite these (comma-separated) destination numbers to 411 for rating purposes: ',
110                       },
111
112     'output_format' => { 'name' => 'Simple output format',
113                          'type' => 'select',
114                          'select_options' => { FS::cdr::invoice_formats() },
115                        },
116
117     'usage_section' => { 'name' => 'Section in which to place separate usage charges',
118                        },
119
120     'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
121                           'type' => 'checkbox',
122                         },
123
124     #XXX also have option for an external db
125 #    'cdr_location' => { 'name' => 'CDR database location'
126 #                        'type' => 'select',
127 #                        'select_options' => \%cdr_location,
128 #                        'select_callback' => {
129 #                          'external' => {
130 #                            'enable' => [ 'datasrc', 'username', 'password' ],
131 #                          },
132 #                          'internal' => {
133 #                            'disable' => [ 'datasrc', 'username', 'password' ],
134 #                          }
135 #                        },
136 #                      },
137 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
138 #                   'disabled' => 'Y',
139 #                 },
140 #    'username' => { 'name' => 'External database username',
141 #                    'disabled' => 'Y',
142 #                  },
143 #    'password' => { 'name' => 'External database password',
144 #                    'disabled' => 'Y',
145 #                  },
146
147   },
148   'fieldorder' => [qw(
149                        setup_fee recur_fee recur_temporality unused_credit
150                        rating_method ratenum 
151                        default_prefix
152                        disable_src
153                        domestic_prefix international_prefix
154                        disable_tollfree
155                        use_amaflags use_disposition
156                        use_disposition_taqua use_carrierid use_cdrtypenum
157                        411_rewrite
158                        output_format summarize_usage usage_section
159                      )
160                   ],
161   'weight' => 40,
162 );
163
164 sub calc_setup {
165   my($self, $cust_pkg ) = @_;
166   $self->option('setup_fee');
167 }
168
169 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
170 sub calc_recur {
171   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
172
173   #my $last_bill = $cust_pkg->last_bill;
174   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
175
176   return 0
177     if $self->option('recur_temporality', 1) eq 'preceding' && $last_bill == 0;
178
179   my $ratenum = $cust_pkg->part_pkg->option('ratenum');
180
181   my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
182
183   my %included_min = ();
184
185   my $charges = 0;
186
187   my $downstream_cdr = '';
188
189   my $output_format = $self->option('output_format', 'Hush!')
190                       || 'simple';
191
192   eval "use Text::CSV_XS;";
193   die $@ if $@;
194   my $csv = new Text::CSV_XS;
195
196   foreach my $cust_svc (
197     grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
198   ) {
199
200     foreach my $cdr (
201       $cust_svc->get_cdrs_for_update( 'disable_src'    => $self->option('disable_src'),
202                                       'default_prefix' => $self->option('default_prefix'),
203                                     )  # $last_bill, $$sdate )
204     ) {
205       if ( $DEBUG > 1 ) {
206         warn "rating CDR $cdr\n".
207              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
208       }
209
210       my $rate_detail;
211       my( $rate_region, $regionnum );
212       my $pretty_destnum;
213       my $charge = '';
214       my $classnum = '';
215       my @call_details = ();
216       if ( $self->option('rating_method') eq 'prefix'
217            || ! $self->option('rating_method')
218          )
219       {
220
221         #should have some better way of checking these options than a long
222         #if-else tree...
223         my $notchg = "not charging for CDR";
224
225         if ( $self->option('use_amaflags') && $cdr->amaflags != 2 ) {
226
227           warn "$notchg (amaflags != 2)\n" if $DEBUG;
228           $charge = 0;
229
230         } elsif ( $self->option('use_disposition')
231                   && $cdr->disposition ne 'ANSWERED' ) {
232
233           warn "$notchg (disposition != ANSWERED)\n" if $DEBUG;
234           $charge = 0;
235
236         } elsif ( $self->option('use_disposition_taqua')
237                   && $cdr->disposition != 100 ) {
238
239           warn "$notchg (disposition != 100)\n" if $DEBUG;
240           $charge = 0;
241
242         } elsif ( $self->option('use_carrierid')
243                   && $cdr->carrierid != $self->option('use_carrierid') ) {
244
245           warn "$notchg (carrierid != ". $self->option('use_carrierid'). ")\n"
246             if $DEBUG;
247           $charge = 0;
248
249         } elsif ( $self->option('use_cdrtypenum')
250                   && $cdr->cdrtypenum != $self->option('use_cdrtypenum') ) {
251
252           warn "$notchg (cdrtypenum != ". $self->option('use_cdrtypenum'). ")\n"
253             if $DEBUG;
254           $charge = 0;
255
256         } else {
257
258           ###
259           # look up rate details based on called station id
260           # (or calling station id for toll free calls)
261           ###
262
263           if ( $self->option('411_rewrite') ) {
264             my @dirass = split(/\s*,\s*/, $self->option('411_rewrite'));
265             $cdr->dst('411') if grep $cdr->dst eq $_, @dirass;
266           }
267
268           my( $to_or_from, $number );
269           if ( $cdr->dst =~ /^(\+?1)?8([02-8])\1/
270                && ! $self->option('disable_tollfree')
271               )
272           { #tollfree call
273             $to_or_from = 'from';
274             $number = $cdr->src;
275           } else { #regular call
276             $to_or_from = 'to';
277             $number = $cdr->dst;
278           }
279
280           warn "parsing call $to_or_from $number\n" if $DEBUG;
281
282           #remove non-phone# stuff and whitespace
283           $number =~ s/\s//g;
284 #          my $proto = '';
285 #          $dest =~ s/^(\w+):// and $proto = $1; #sip:
286 #          my $siphost = '';
287 #          $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
288
289           my $intl = $self->option('international_prefix') || '011';
290
291           #determine the country code
292           my $countrycode;
293           if (    $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
294                || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
295              )
296           {
297
298             my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
299             #first look for 1 digit country code
300             if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
301               $countrycode = $one;
302               $number = $u1.$u2.$rest;
303             } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
304               $countrycode = $two;
305               $number = $u2.$rest;
306             } else { #3 digit country code
307               $countrycode = $three;
308               $number = $rest;
309             }
310
311           } else {
312             $countrycode = $self->option('domestic_prefix') || '1';
313             $number =~ s/^$countrycode//;# if length($number) > 10;
314           }
315
316           warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
317           $pretty_destnum = "+$countrycode $number";
318
319           #find a rate prefix, first look at most specific (4 digits) then 3, etc.,
320           # finally trying the country code only
321           my $rate_prefix = '';
322           for my $len ( reverse(1..6) ) {
323             $rate_prefix = qsearchs('rate_prefix', {
324               'countrycode' => $countrycode,
325               #'npa'         => { op=> 'LIKE', value=> substr($number, 0, $len) }
326               'npa'         => substr($number, 0, $len),
327             } ) and last;
328           }
329           $rate_prefix ||= qsearchs('rate_prefix', {
330             'countrycode' => $countrycode,
331             'npa'         => '',
332           });
333
334           #
335           die "Can't find rate for call $to_or_from +$countrycode $number\n"
336             unless $rate_prefix;
337
338           $regionnum = $rate_prefix->regionnum;
339           $rate_detail = qsearchs('rate_detail', {
340             'ratenum'        => $ratenum,
341             'dest_regionnum' => $regionnum,
342           } );
343
344           $rate_region = $rate_prefix->rate_region;
345
346           warn "  found rate for regionnum $regionnum ".
347                "and rate detail $rate_detail\n"
348             if $DEBUG;
349
350         }
351
352       } elsif ( $self->option('rating_method') eq 'upstream' ) {
353
354         if ( $cdr->cdrtypenum == 1 ) { #rate based on upstream rateid
355
356           $rate_detail = $cdr->cdr_upstream_rate->rate_detail;
357
358           $regionnum = $rate_detail->dest_regionnum;
359           $rate_region = $rate_detail->dest_region;
360
361           $pretty_destnum = $cdr->dst;
362
363           warn "  found rate for regionnum $regionnum and ".
364                "rate detail $rate_detail\n"
365             if $DEBUG;
366
367         } else { #pass upstream price through
368
369           $charge = sprintf('%.2f', $cdr->upstream_price);
370           $charges += $charge;
371  
372           @call_details = (
373             #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
374             time2str("%c", $cdr->calldate_unix),  #XXX this should probably be a config option dropdown so they can select US vs- rest of world dates or whatnot
375             'N/A', #minutes...
376             '$'.$charge,
377             #$pretty_destnum,
378             $cdr->description, #$rate_region->regionname,
379           );
380
381         }
382
383       } elsif ( $self->option('rating_method') eq 'upstream_simple' ) {
384
385         #XXX $charge = sprintf('%.2f', $cdr->upstream_price);
386         $charge = sprintf('%.3f', $cdr->upstream_price);
387         $charges += $charge;
388
389         @call_details = ($cdr->downstream_csv( 'format' => $output_format ));
390
391       } else {
392         die "don't know how to rate CDRs using method: ".
393             $self->option('rating_method'). "\n";
394       }
395
396       ###
397       # find the price and add detail to the invoice
398       ###
399
400       # if $rate_detail is not found, skip this CDR... i.e. 
401       # don't add it to invoice, don't set its status to NULL,
402       # don't call downstream_csv or something on it...
403       # but DO emit a warning...
404       #if ( ! $rate_detail && ! scalar(@call_details) ) {
405       if ( ! $rate_detail && $charge eq '' ) {
406
407         warn "no rate_detail found for CDR.acctid:  ". $cdr->acctid.
408              "; skipping\n"
409
410       } else { # there *is* a rate_detail (or call_details), proceed...
411
412         unless ( @call_details || ( $charge ne '' && $charge == 0 ) ) {
413
414           $included_min{$regionnum} = $rate_detail->min_included
415             unless exists $included_min{$regionnum};
416
417           my $granularity = $rate_detail->sec_granularity;
418           my $seconds = $cdr->billsec; # length($cdr->billsec) ? $cdr->billsec : $cdr->duration;
419           $seconds += $granularity - ( $seconds % $granularity )
420             if $seconds      # don't granular-ize 0 billsec calls (bills them)
421             && $granularity; # 0 is per call
422           my $minutes = sprintf("%.1f", $seconds / 60);
423           $minutes =~ s/\.0$// if $granularity == 60;
424
425           # per call rather than per minute
426           $minutes = 1 unless $granularity;
427
428           $included_min{$regionnum} -= $minutes;
429
430           if ( $included_min{$regionnum} < 0 ) {
431             my $charge_min = 0 - $included_min{$regionnum};
432             $included_min{$regionnum} = 0;
433             $charge = sprintf('%.2f', $rate_detail->min_charge * $charge_min );
434             $charges += $charge;
435           }
436
437           # this is why we need regionnum/rate_region....
438           warn "  (rate region $rate_region)\n" if $DEBUG;
439
440           @call_details = (
441             #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
442             time2str("%c", $cdr->calldate_unix),  #XXX this should probably be a config option dropdown so they can select US vs- rest of world dates or whatnot
443             $granularity ? $minutes.'m' : $minutes.' call',
444             '$'.$charge,
445             $pretty_destnum,
446             $rate_region->regionname,
447           );
448
449           $classnum = $rate_detail->classnum;
450
451         }
452
453         if ( $charge > 0 ) {
454           #just use FS::cust_bill_pkg_detail objects?
455           my $call_details;
456           if ( $self->option('rating_method') eq 'upstream_simple' ) {
457             $call_details = [ 'C', $call_details[0], $charge, $classnum ];
458           }else{
459             $csv->combine(@call_details);
460             $call_details = [ 'C', $csv->string, $charge, $classnum ];
461           }
462           warn "  adding details on charge to invoice: [ ".
463               join(', ', @{$call_details} ). " ]"
464             if ( $DEBUG && ref($call_details) );
465           push @$details, $call_details; #\@call_details,
466         }
467
468         # if the customer flag is on, call "downstream_csv" or something
469         # like it to export the call downstream!
470         # XXX price plan option to pick format, or something...
471         $downstream_cdr .= $cdr->downstream_csv( 'format' => 'convergent' )
472           if $spool_cdr;
473
474         my $error = $cdr->set_status_and_rated_price('done', $charge);
475         die $error if $error;
476
477       }
478
479     } # $cdr
480
481     unshift @$details, [ 'C', FS::cdr::invoice_header( $output_format) ]
482       if (@$details && $self->option('rating_method') eq 'upstream_simple' );
483
484   } # $cust_svc
485
486   if ( $spool_cdr && length($downstream_cdr) ) {
487
488     use FS::UID qw(datasrc);
489     my $dir = '/usr/local/etc/freeside/export.'. datasrc. '/cdr';
490     mkdir $dir, 0700 unless -d $dir;
491     $dir .= '/'. $cust_pkg->custnum.
492     mkdir $dir, 0700 unless -d $dir;
493     my $filename = time2str("$dir/CDR%Y%m%d-spool.CSV", time); #XXX invoice date instead?  would require changing the order things are generated in cust_main::bill insert cust_bill first - with transactions it could be done though
494
495     push @{ $param->{'precommit_hooks'} },
496          sub {
497                #lock the downstream spool file and append the records 
498                use Fcntl qw(:flock);
499                use IO::File;
500                my $spool = new IO::File ">>$filename"
501                  or die "can't open $filename: $!\n";
502                flock( $spool, LOCK_EX)
503                  or die "can't lock $filename: $!\n";
504                seek($spool, 0, 2)
505                  or die "can't seek to end of $filename: $!\n";
506                print $spool $downstream_cdr;
507                flock( $spool, LOCK_UN );
508                close $spool;
509              };
510
511   } #if ( $spool_cdr && length($downstream_cdr) )
512
513   $self->option('recur_fee') + $charges;
514
515 }
516
517 sub is_free {
518   0;
519 }
520
521 sub base_recur {
522   my($self, $cust_pkg) = @_;
523   $self->option('recur_fee');
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   scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
531 }
532
533 1;
534