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