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