credit for unused portion at cancellation, patch from pbowen
[freeside.git] / FS / FS / part_pkg / voip_sqlradacct.pm
1 package FS::part_pkg::voip_sqlradacct;
2
3 use strict;
4 use vars qw(@ISA $DEBUG %info);
5 use FS::Record qw(qsearchs qsearch);
6 use FS::part_pkg;
7 #use FS::rate;
8 use FS::rate_prefix;
9
10 @ISA = qw(FS::part_pkg::flat);
11
12 $DEBUG = 1;
13
14 %info = (
15   'name' => 'VoIP rating by plan of CDR records in an SQL RADIUS radacct table',
16   'fields' => {
17     'setup_fee'     => { 'name' => 'Setup fee for this package',
18                          'default' => 0,
19                        },
20     'recur_flat'     => { 'name' => 'Base monthly charge for this package',
21                           'default' => 0,
22                         },
23     'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
24                                    ' of service at cancellation',
25                          'type' => 'checkbox',
26                        },
27     'ratenum'   => { 'name' => 'Rate plan',
28                      'type' => 'select',
29                      'select_table' => 'rate',
30                      'select_key'   => 'ratenum',
31                      'select_label' => 'ratename',
32                    },
33     'ignore_unrateable' => { 'name' => 'Ignore calls for which not rate prefix can be found (otherwise they are fatal)',
34                              'type' => 'checkbox',
35                            },
36   },
37   'fieldorder' => [qw( setup_fee recur_flat unused_credit ratenum ignore_unrateable )],
38   'weight' => 40,
39 );
40
41 sub calc_setup {
42   my($self, $cust_pkg ) = @_;
43   $self->option('setup_fee');
44 }
45
46 sub calc_recur {
47   my($self, $cust_pkg, $sdate, $details ) = @_;
48
49   my $last_bill = $cust_pkg->last_bill;
50
51   my $ratenum = $cust_pkg->part_pkg->option('ratenum');
52
53   my %included_min = ();
54
55   my $charges = 0;
56
57   foreach my $cust_svc (
58     grep { $_->part_svc->svcdb eq 'svc_acct' } $cust_pkg->cust_svc
59   ) {
60
61     foreach my $session (
62       $cust_svc->get_session_history( $last_bill, $$sdate )
63     ) {
64       warn "rating session $session" if $DEBUG;
65
66       ###
67       # look up rate details based on called station id
68       ###
69
70       my $dest = $session->{'calledstationid'};
71
72       #remove non-phone# stuff and whitespace
73       $dest =~ s/\s//g;
74       my $proto = '';
75       $dest =~ s/^(\w+):// and $proto = $1; #sip:
76       my $ip = '';
77       $dest =~ s/\@((\d{1,3}\.){3}\d{1,3})$// and $ip = $1; # @10.54.32.1
78
79       #determine the country code
80       my $countrycode;
81       if ( $dest =~ /^011((\d\d)(\d))(\d+)$/ ) {
82
83         my( $three, $two, $unknown, $rest ) = ( $1, $2, $3, $4 );
84         #first look for 2 digit country code
85         if ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) {
86           $countrycode = $two;
87           $dest = $unknown.$rest;
88         } else { #3 digit country code
89           $countrycode = $three;
90           $dest = $rest;
91         }
92
93       } else {
94         $countrycode = '1';
95       }
96
97       warn "rating call to +$countrycode $dest" if $DEBUG;
98
99       #find a rate prefix, first look at most specific (4 digits) then 3, etc.,
100       # finally trying the country code only
101       my $rate_prefix = '';
102       for my $len ( reverse(1..4) ) {
103         $rate_prefix = qsearchs('rate_prefix', {
104           'countrycode' => $countrycode,
105           'npa'         => { op=> 'LIKE', value=> substr($dest, 0, $len) }
106         } ) and last;
107       }
108       $rate_prefix ||= qsearchs('rate_prefix', {
109         'countrycode' => $countrycode,
110         'npa'         => '',
111       });
112
113       unless ( $rate_prefix ) {
114         if ( $self->option('ignore_unrateable') ) {
115           warn "  skipping unrateable call to +$countrycode $dest";
116           next;
117         } else {
118           die "Can't find rate for call to +$countrycode $dest\n"
119         }
120       }
121
122       my $regionnum = $rate_prefix->regionnum;
123
124       my $rate_detail = qsearchs('rate_detail', {
125         'ratenum'        => $ratenum,
126         'dest_regionnum' => $regionnum,
127       } );
128
129       warn "  found rate for regionnum $regionnum ".
130            "and rate detail $rate_detail"
131         if $DEBUG;
132
133       ###
134       # find the price and add detail to the invoice
135       ###
136
137       $included_min{$regionnum} = $rate_detail->min_included
138         unless exists $included_min{$regionnum};
139
140       my $granularity = $rate_detail->sec_granularity;
141       my $seconds = $session->{'acctsessiontime'};
142       $seconds += $granularity - ( $seconds % $granularity );
143       my $minutes = sprintf("%.1f", $seconds / 60);
144       $minutes =~ s/\.0$// if $granularity == 60;
145
146       $included_min{$regionnum} -= $minutes;
147
148       my $charge = 0;
149       if ( $included_min{$regionnum} < 0 ) {
150         my $charge_min = 0 - $included_min{$regionnum};
151         $included_min{$regionnum} = 0;
152         $charge = sprintf('%.2f', $rate_detail->min_charge * $charge_min );
153         $charges += $charge;
154       }
155
156       warn "  adding details on charge to invoice: ".
157            join(' - ', 
158              "+$countrycode $dest",
159              $rate_prefix->rate_region->regionname,
160              $minutes.'m',
161              '$'.$charge,
162            )
163         if $DEBUG;
164
165       push @$details, 
166         #[
167         join(' - ', 
168           "+$countrycode $dest",
169           $rate_prefix->rate_region->regionname,
170           $minutes.'m',
171           '$'.$charge,
172         #]
173         )
174       ;
175
176     } # $session
177
178   } # $cust_svc
179
180   $self->option('recur_flat') + $charges;
181
182 }
183
184 sub is_free {
185   0;
186 }
187
188 sub base_recur {
189   my($self, $cust_pkg) = @_;
190   $self->option('recur_flat');
191 }
192
193 1;
194