initial commit of this just cause i want a revision history
[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::Record qw(qsearchs qsearch);
8 use FS::part_pkg::flat;
9 #use FS::rate;
10 use FS::rate_prefix;
11
12 @ISA = qw(FS::part_pkg::flat);
13
14 $DEBUG = 1;
15
16 tie my %region_method, 'Tie::IxHash',
17   'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
18   'upstream_rateid' => 'Rate calls by mapping the upstream rate ID (# rate plan ID?) directly to an internal rate (rate_detail)', #upstream_rateplanid
19 ;
20
21 #tie my %cdr_location, 'Tie::IxHash',
22 #  'internal' => 'Internal: CDR records imported into the internal CDR table',
23 #  'external' => 'External: CDR records queried directly from an external '.
24 #                'Asterisk (or other?) CDR table',
25 #;
26
27 %info = (
28   'name' => 'VoIP rating by plan of CDR records in an internal (or external?) SQL table',
29   'fields' => {
30     'setup_fee'     => { 'name' => 'Setup fee for this package',
31                          'default' => 0,
32                        },
33     'recur_flat'     => { 'name' => 'Base recurring fee for this package',
34                           'default' => 0,
35                         },
36     'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
37                                    ' of service at cancellation',
38                          'type' => 'checkbox',
39                        },
40     'ratenum'   => { 'name' => 'Rate plan',
41                      'type' => 'select',
42                      'select_table' => 'rate',
43                      'select_key'   => 'ratenum',
44                      'select_label' => 'ratename',
45                    },
46     'region_method' => { 'name' => 'Region rating method',
47                          'type' => 'select',
48                          'select_options' => \%region_method,
49                        },
50
51     #XXX also have option for an external db??
52 #    'cdr_location' => { 'name' => 'CDR database location'
53 #                        'type' => 'select',
54 #                        'select_options' => \%cdr_location,
55 #                        'select_callback' => {
56 #                          'external' => {
57 #                            'enable' => [ 'datasrc', 'username', 'password' ],
58 #                          },
59 #                          'internal' => {
60 #                            'disable' => [ 'datasrc', 'username', 'password' ],
61 #                          }
62 #                        },
63 #                      },
64 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
65 #                   'disabled' => 'Y',
66 #                 },
67 #    'username' => { 'name' => 'External database username',
68 #                    'disabled' => 'Y',
69 #                  },
70 #    'password' => { 'name' => 'External database password',
71 #                    'disabled' => 'Y',
72 #                  },
73
74   },
75   'fieldorder' => [qw( setup_fee recur_flat unused_credit ratenum ignore_unrateable )],
76   'weight' => 40,
77 );
78
79 sub calc_setup {
80   my($self, $cust_pkg ) = @_;
81   $self->option('setup_fee');
82 }
83
84 #false laziness w/voip_sqlradacct... resolve it if that one ever gets used again
85 sub calc_recur {
86   my($self, $cust_pkg, $sdate, $details ) = @_;
87
88   my $last_bill = $cust_pkg->last_bill;
89
90   my $ratenum = $cust_pkg->part_pkg->option('ratenum');
91
92   my %included_min = ();
93
94   my $charges = 0;
95
96   # also look for a specific domain??? (username@telephonedomain)
97   foreach my $cust_svc (
98     grep { $_->part_svc->svcdb eq 'svc_acct' } $cust_pkg->cust_svc
99   ) {
100
101     foreach my $cdr (
102       $cust_svc->get_cdrs( $last_bill, $$sdate )
103     ) {
104       if ( $DEBUG > 1 ) {
105         warn "rating CDR $cdr\n".
106              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
107       }
108
109       my( $regionnum, $rate_detail );
110       if ( $self->option('region_method') eq 'prefix'
111            || ! $self->option('region_method')
112          )
113       {
114
115         ###
116         # look up rate details based on called station id
117         ###
118   
119         my $dest = $cdr->{'calledstationid'};  # XXX
120   
121         #remove non-phone# stuff and whitespace
122         $dest =~ s/\s//g;
123         my $proto = '';
124         $dest =~ s/^(\w+):// and $proto = $1; #sip:
125         my $siphost = '';
126         $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
127   
128         #determine the country code
129         my $countrycode;
130         if (    $dest =~ /^011(((\d)(\d))(\d))(\d+)$/
131              || $dest =~ /^\+(((\d)(\d))(\d))(\d+)$/
132            )
133         {
134   
135           my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
136           #first look for 1 digit country code
137           if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
138             $countrycode = $one;
139             $dest = $u1.$u2.$rest;
140           } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
141             $countrycode = $two;
142             $dest = $u2.$rest;
143           } else { #3 digit country code
144             $countrycode = $three;
145             $dest = $rest;
146           }
147   
148         } else {
149           $countrycode = '1';
150           $dest =~ s/^1//;# if length($dest) > 10;
151         }
152   
153         warn "rating call to +$countrycode $dest\n" if $DEBUG;
154   
155         #find a rate prefix, first look at most specific (4 digits) then 3, etc.,
156         # finally trying the country code only
157         my $rate_prefix = '';
158         for my $len ( reverse(1..6) ) {
159           $rate_prefix = qsearchs('rate_prefix', {
160             'countrycode' => $countrycode,
161             #'npa'         => { op=> 'LIKE', value=> substr($dest, 0, $len) }
162             'npa'         => substr($dest, 0, $len),
163           } ) and last;
164         }
165         $rate_prefix ||= qsearchs('rate_prefix', {
166           'countrycode' => $countrycode,
167           'npa'         => '',
168         });
169   
170         die "Can't find rate for call to +$countrycode $dest\n"
171           unless $rate_prefix;
172   
173         $regionnum = $rate_prefix->regionnum;
174         $rate_detail = qsearchs('rate_detail', {
175           'ratenum'        => $ratenum,
176           'dest_regionnum' => $regionnum,
177         } );
178   
179         warn "  found rate for regionnum $regionnum ".
180              "and rate detail $rate_detail\n"
181           if $DEBUG;
182
183       } elsif ( $self->option('region_method') eq 'upstream_rateid' ) { #upstream_rateplanid
184
185         $regionnum = ''; #XXXXX regionnum should be something
186
187         $rate_detail = $cdr->cdr_upstream_rate->rate_detail;
188
189         warn "  found rate for ". #regionnum $regionnum and ".
190              "rate detail $rate_detail\n"
191           if $DEBUG;
192
193       } else {
194         die "don't know how to rate CDRs using method: ".
195             $self->option('region_method'). "\n";
196       }
197
198       ###
199       # find the price and add detail to the invoice
200       ###
201
202       $included_min{$regionnum} = $rate_detail->min_included
203         unless exists $included_min{$regionnum};
204
205       my $granularity = $rate_detail->sec_granularity;
206       my $seconds = $cdr->{'acctsessiontime'}; # XXX
207       $seconds += $granularity - ( $seconds % $granularity );
208       my $minutes = sprintf("%.1f", $seconds / 60);
209       $minutes =~ s/\.0$// if $granularity == 60;
210
211       $included_min{$regionnum} -= $minutes;
212
213       my $charge = 0;
214       if ( $included_min{$regionnum} < 0 ) {
215         my $charge_min = 0 - $included_min{$regionnum};
216         $included_min{$regionnum} = 0;
217         $charge = sprintf('%.2f', $rate_detail->min_charge * $charge_min );
218         $charges += $charge;
219       }
220
221       # XXXXXXX
222 #      my $rate_region = $rate_prefix->rate_region;
223 #      warn "  (rate region $rate_region)\n" if $DEBUG;
224 #
225 #      my @call_details = (
226 #        #time2str("%Y %b %d - %r", $session->{'acctstarttime'}),
227 #        time2str("%c", $cdr->{'acctstarttime'}),  #XXX
228 #        $minutes.'m',
229 #        '$'.$charge,
230 #        "+$countrycode $dest",
231 #        $rate_region->regionname,
232 #      );
233 #
234 #      warn "  adding details on charge to invoice: ".
235 #           join(' - ', @call_details )
236 #        if $DEBUG;
237 #
238 #      push @$details, join(' - ', @call_details); #\@call_details,
239
240     } # $cdr
241
242   } # $cust_svc
243
244   $self->option('recur_flat') + $charges;
245
246 }
247
248 sub is_free {
249   0;
250 }
251
252 sub base_recur {
253   my($self, $cust_pkg) = @_;
254   $self->option('recur_flat');
255 }
256
257 1;
258