voxline cdrs
[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::rate;
11 #use FS::rate_prefix;
12
13 @ISA = qw(FS::part_pkg::flat);
14
15 $DEBUG = 1;
16
17 tie my %rating_method, 'Tie::IxHash',
18   'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
19   '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.',
20   'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
21 ;
22
23 #tie my %cdr_location, 'Tie::IxHash',
24 #  'internal' => 'Internal: CDR records imported into the internal CDR table',
25 #  'external' => 'External: CDR records queried directly from an external '.
26 #                'Asterisk (or other?) CDR table',
27 #;
28
29 %info = (
30   'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
31   'shortname' => 'VoIP/telco CDR rating (standard)',
32   'fields' => {
33     'setup_fee'     => { 'name' => 'Setup fee for this package',
34                          'default' => 0,
35                        },
36     'recur_fee'     => { 'name' => 'Base recurring fee for this package',
37                          'default' => 0,
38                        },
39     'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
40                                    ' of service at cancellation',
41                          'type' => 'checkbox',
42                        },
43     'ratenum'   => { 'name' => 'Rate plan',
44                      'type' => 'select',
45                      'select_table' => 'rate',
46                      'select_key'   => 'ratenum',
47                      'select_label' => 'ratename',
48                    },
49     'rating_method' => { 'name' => 'Region rating method',
50                          'type' => 'radio',
51                          'options' => \%rating_method,
52                        },
53
54     'default_prefix' => { 'name'    => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
55                           'default' => '+1',
56                         },
57
58     'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
59                        'type' => 'checkbox'
60                      },
61
62     'domestic_prefix' => { 'name'    => 'Destination prefix for domestic CDR records',
63                            'default' => '1',
64                          },
65
66 #    'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
67 #                                    'type' => 'checkbox',
68 #                                  },
69
70     'international_prefix' => { 'name'    => 'Destination prefix for international CDR records',
71                                 'default' => '011',
72                               },
73
74     #XXX also have option for an external db
75 #    'cdr_location' => { 'name' => 'CDR database location'
76 #                        'type' => 'select',
77 #                        'select_options' => \%cdr_location,
78 #                        'select_callback' => {
79 #                          'external' => {
80 #                            'enable' => [ 'datasrc', 'username', 'password' ],
81 #                          },
82 #                          'internal' => {
83 #                            'disable' => [ 'datasrc', 'username', 'password' ],
84 #                          }
85 #                        },
86 #                      },
87 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
88 #                   'disabled' => 'Y',
89 #                 },
90 #    'username' => { 'name' => 'External database username',
91 #                    'disabled' => 'Y',
92 #                  },
93 #    'password' => { 'name' => 'External database password',
94 #                    'disabled' => 'Y',
95 #                  },
96
97   },
98   'fieldorder' => [qw( setup_fee recur_fee unused_credit ratenum rating_method default_prefix disable_src domestic_prefix international_prefix )],
99   'weight' => 40,
100 );
101
102 sub calc_setup {
103   my($self, $cust_pkg ) = @_;
104   $self->option('setup_fee');
105 }
106
107 #false laziness w/voip_sqlradacct... resolve it if that one ever gets used again
108 sub calc_recur {
109   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
110
111   my $last_bill = $cust_pkg->last_bill;
112
113   my $ratenum = $cust_pkg->part_pkg->option('ratenum');
114
115   my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
116
117   my %included_min = ();
118
119   my $charges = 0;
120
121   my $downstream_cdr = '';
122
123   foreach my $cust_svc (
124     grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
125   ) {
126
127     foreach my $cdr (
128       $cust_svc->get_cdrs_for_update()  # $last_bill, $$sdate )
129     ) {
130       if ( $DEBUG > 1 ) {
131         warn "rating CDR $cdr\n".
132              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
133       }
134
135       my $rate_detail;
136       my( $rate_region, $regionnum );
137       my $pretty_destnum;
138       my $charge = 0;
139       my @call_details = ();
140       if ( $self->option('rating_method') eq 'prefix'
141            || ! $self->option('rating_method')
142          )
143       {
144
145         ###
146         # look up rate details based on called station id
147         # (or calling station id for toll free calls)
148         ###
149
150         my( $to_or_from, $number );
151         if ( $cdr->dst =~ /^(\+?1)?8([02-8])\1/ ) { #tollfree call
152           $to_or_from = 'from';
153           $number = $cdr->src;
154         } else { #regular call
155           $to_or_from = 'to';
156           $number = $cdr->dst;
157         }
158   
159         #remove non-phone# stuff and whitespace
160         $number =~ s/\s//g;
161 #        my $proto = '';
162 #        $dest =~ s/^(\w+):// and $proto = $1; #sip:
163 #        my $siphost = '';
164 #        $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
165
166         my $intl = $self->option('international_prefix') || '011';
167   
168         #determine the country code
169         my $countrycode;
170         if (    $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
171              || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
172            )
173         {
174   
175           my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
176           #first look for 1 digit country code
177           if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
178             $countrycode = $one;
179             $number = $u1.$u2.$rest;
180           } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
181             $countrycode = $two;
182             $number = $u2.$rest;
183           } else { #3 digit country code
184             $countrycode = $three;
185             $number = $rest;
186           }
187   
188         } else {
189           $countrycode = $self->option('domestic_prefix') || '1';
190           $number =~ s/^$countrycode//;# if length($number) > 10;
191         }
192   
193         warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
194         $pretty_destnum = "+$countrycode $number";
195   
196         #find a rate prefix, first look at most specific (4 digits) then 3, etc.,
197         # finally trying the country code only
198         my $rate_prefix = '';
199         for my $len ( reverse(1..6) ) {
200           $rate_prefix = qsearchs('rate_prefix', {
201             'countrycode' => $countrycode,
202             #'npa'         => { op=> 'LIKE', value=> substr($number, 0, $len) }
203             'npa'         => substr($number, 0, $len),
204           } ) and last;
205         }
206         $rate_prefix ||= qsearchs('rate_prefix', {
207           'countrycode' => $countrycode,
208           'npa'         => '',
209         });
210
211         #
212         die "Can't find rate for call $to_or_from +$countrycode $number\n"
213           unless $rate_prefix;
214   
215         $regionnum = $rate_prefix->regionnum;
216         $rate_detail = qsearchs('rate_detail', {
217           'ratenum'        => $ratenum,
218           'dest_regionnum' => $regionnum,
219         } );
220   
221         $rate_region = $rate_prefix->rate_region;
222
223         warn "  found rate for regionnum $regionnum ".
224              "and rate detail $rate_detail\n"
225           if $DEBUG;
226
227       } elsif ( $self->option('rating_method') eq 'upstream' ) {
228
229         if ( $cdr->cdrtypenum == 1 ) { #rate based on upstream rateid
230
231           $rate_detail = $cdr->cdr_upstream_rate->rate_detail;
232
233           $regionnum = $rate_detail->dest_regionnum;
234           $rate_region = $rate_detail->dest_region;
235
236           $pretty_destnum = $cdr->dst;
237
238           warn "  found rate for regionnum $regionnum and ".
239                "rate detail $rate_detail\n"
240             if $DEBUG;
241
242         } else { #pass upstream price through
243
244           $charge = sprintf('%.2f', $cdr->upstream_price);
245   
246           @call_details = (
247             #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
248             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
249             'N/A', #minutes...
250             '$'.$charge,
251             #$pretty_destnum,
252             $cdr->description, #$rate_region->regionname,
253           );
254
255         }
256
257       } elsif ( $self->option('rating_method') eq 'upstream_simple' ) {
258
259         #XXX $charge = sprintf('%.2f', $cdr->upstream_price);
260         $charge = sprintf('%.3f', $cdr->upstream_price);
261         $charges += $charge;
262
263         @call_details = (
264           #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
265           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
266           sprintf('%.2f', $cdr->billsec / 60 ).'m',
267           '$'.$charge, #XXX $money_char
268           #$pretty_destnum,
269           $cdr->userfield, #$rate_region->regionname,
270           $cdr->dst,
271         );
272
273       } else {
274         die "don't know how to rate CDRs using method: ".
275             $self->option('rating_method'). "\n";
276       }
277
278       ###
279       # find the price and add detail to the invoice
280       ###
281
282       # if $rate_detail is not found, skip this CDR... i.e. 
283       # don't add it to invoice, don't set its status to NULL,
284       # don't call downstream_csv or something on it...
285       # but DO emit a warning...
286       if ( ! $rate_detail && ! scalar(@call_details) ) {
287   
288         warn "no rate_detail found for CDR.acctid:  ". $cdr->acctid.
289              "; skipping\n"
290
291       } else { # there *is* a rate_detail (or call_details), proceed...
292
293         unless ( @call_details ) {
294     
295           $included_min{$regionnum} = $rate_detail->min_included
296             unless exists $included_min{$regionnum};
297       
298           my $granularity = $rate_detail->sec_granularity;
299           my $seconds = $cdr->billsec; # length($cdr->billsec) ? $cdr->billsec : $cdr->duration;
300           $seconds += $granularity - ( $seconds % $granularity )
301             if $seconds      # don't granular-ize 0 billsec calls (bills them)
302             && $granularity; # 0 is per call
303           my $minutes = sprintf("%.1f", $seconds / 60);
304           $minutes =~ s/\.0$// if $granularity == 60;
305
306           # per call rather than per minute
307           $minutes = 1 unless $granularity;
308       
309           $included_min{$regionnum} -= $minutes;
310       
311           if ( $included_min{$regionnum} < 0 ) {
312             my $charge_min = 0 - $included_min{$regionnum};
313             $included_min{$regionnum} = 0;
314             $charge = sprintf('%.2f', $rate_detail->min_charge * $charge_min );
315             $charges += $charge;
316           }
317       
318           # this is why we need regionnum/rate_region....
319           warn "  (rate region $rate_region)\n" if $DEBUG;
320       
321           @call_details = (
322             #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
323             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
324             $granularity ? $minutes.'m' : $minutes.' call',
325             '$'.$charge,
326             $pretty_destnum,
327             $rate_region->regionname,
328           );
329
330         }
331     
332         warn "  adding details on charge to invoice: ".
333              join(' - ', @call_details )
334           if $DEBUG && $charge > 0;
335     
336         push @$details, join(' - ', @call_details) #\@call_details,
337           if $charge > 0;
338   
339         # if the customer flag is on, call "downstream_csv" or something
340         # like it to export the call downstream!
341         # XXX price plan option to pick format, or something...
342         $downstream_cdr .= $cdr->downstream_csv( 'format' => 'convergent' )
343           if $spool_cdr;
344   
345         my $error = $cdr->set_status_and_rated_price('done', $charge);
346         die $error if $error;
347   
348       }
349   
350     } # $cdr
351
352   } # $cust_svc
353
354   if ( $spool_cdr && length($downstream_cdr) ) {
355
356     use FS::UID qw(datasrc);
357     my $dir = '/usr/local/etc/freeside/export.'. datasrc. '/cdr';
358     mkdir $dir, 0700 unless -d $dir;
359     $dir .= '/'. $cust_pkg->custnum.
360     mkdir $dir, 0700 unless -d $dir;
361     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
362
363     push @{ $param->{'precommit_hooks'} },
364          sub {
365                #lock the downstream spool file and append the records 
366                use Fcntl qw(:flock);
367                use IO::File;
368                my $spool = new IO::File ">>$filename"
369                  or die "can't open $filename: $!\n";
370                flock( $spool, LOCK_EX)
371                  or die "can't lock $filename: $!\n";
372                seek($spool, 0, 2)
373                  or die "can't seek to end of $filename: $!\n";
374                print $spool $downstream_cdr;
375                flock( $spool, LOCK_UN );
376                close $spool;
377              };
378
379   } #if ( $spool_cdr && length($downstream_cdr) )
380
381   $self->option('recur_fee') + $charges;
382
383 }
384
385 sub is_free {
386   0;
387 }
388
389 sub base_recur {
390   my($self, $cust_pkg) = @_;
391   $self->option('recur_fee');
392 }
393
394 1;
395