Merge branch 'master' of git.freeside.biz:/home/git/freeside
[freeside.git] / FS / FS / part_pkg / voip_tiered.pm
1 package FS::part_pkg::voip_tiered;
2 use base qw( FS::part_pkg::voip_cdr );
3
4 use strict;
5 use vars qw( $DEBUG %info );
6 use Tie::IxHash;
7 use Date::Format;
8 use Text::CSV_XS;
9 use FS::Conf;
10 use FS::Record qw(qsearchs); # qsearch);
11 use FS::cdr;
12 use FS::rate_tier;
13 use FS::rate_detail;
14
15 use Data::Dumper;
16
17 $DEBUG = 0;
18
19 tie my %cdr_inout, 'Tie::IxHash',
20   'outbound'         => 'Outbound',
21   'inbound'          => 'Inbound',
22   'outbound_inbound' => 'Outbound and Inbound',
23 ;
24
25 tie my %granularity, 'Tie::IxHash', FS::rate_detail::granularities();
26
27 %info = (
28   'name' => 'VoIP tiered rate pricing of CDRs',
29   'shortname' => 'VoIP/telco CDR tiered rating',
30   'inherit_fields' => [ 'voip_cdr', 'prorate_Mixin', 'global_Mixin' ],
31   'fields' => {
32     'tiernum' => { 'name' => 'Tier plan',
33                    'type' => 'select',
34                    'select_table' => 'rate_tier',
35                    'select_key'   => 'tiernum',
36                    'select_label' => 'tiername',
37                  },
38     'cdr_inout' => { 'name'=> 'Call direction when using phone number matching',
39                      'type'=> 'select',
40                      'select_options' => \%cdr_inout,
41                    },
42     'min_included' => { 'name' => 'Minutes included',
43                     },
44     'sec_granularity' => { 'name' => 'Granularity',
45                            'type' => 'select',
46                            'select_options' => \%granularity,
47                          },
48     'rating_method'                          => { 'disabled' => 1 },
49     'ratenum'                                => { 'disabled' => 1 },
50     'intrastate_ratenum'                     => { 'disabled' => 1 },
51     'min_charge'                             => { 'disabled' => 1 },
52     'ignore_unrateable'                      => { 'disabled' => 1 },
53     'domestic_prefix'                        => { 'disabled' => 1 },
54     'international_prefix'                   => { 'disabled' => 1 },
55     'disable_tollfree'                       => { 'disabled' => 1 },
56     'noskip_src_length_accountcode_tollfree' => { 'disabled' => 1 },
57     'accountcode_tollfree_ratenum'           => { 'disabled' => 1 },
58     'noskip_dst_length_accountcode_tollfree' => { 'disabled' => 1 },
59   },
60   'fieldorder' => [qw(
61                        recur_temporality
62                        recur_method cutoff_day ),
63                        FS::part_pkg::prorate_Mixin::fieldorder,
64                    qw(
65                        cdr_svc_method cdr_inout
66                        tiernum
67                      )
68                   ],
69   'weight' => 44,
70 );
71
72 sub calc_usage {
73   my $self = shift;
74   my($cust_pkg, $sdate, $details, $param ) = @_;
75
76   #my $last_bill = $cust_pkg->last_bill;
77   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
78
79   return 0
80     if $self->recur_temporality eq 'preceding'
81     && ( $last_bill eq '' || $last_bill == 0 );
82
83   my $included_min    = $self->option('min_included', 1) || 0;
84   $included_min *= ($cust_pkg->quantity || 1);
85   my $cdr_svc_method  = $self->option('cdr_svc_method',1)||'svc_phone.phonenum';
86   my $cdr_inout       = ($cdr_svc_method eq 'svc_phone.phonenum')
87                           && $self->option('cdr_inout',1)
88                           || 'outbound';
89   my $use_duration    = $self->option('use_duration');
90   my $granularity     = length($self->option('sec_granularity'))
91                           ? $self->option('sec_granularity')
92                           : 60;
93
94   #for check_chargable, so we don't keep looking up options inside the loop
95   my %opt_cache = ();
96
97   my($svc_table, $svc_field) = split('\.', $cdr_svc_method);
98
99   my %options = (
100     'disable_src'    => $self->option('disable_src'),
101     'default_prefix' => $self->option('default_prefix'),
102     'cdrtypenum'     => $self->option('use_cdrtypenum'),
103     'status'         => '',
104     'for_update'     => 1,
105   );  # $last_bill, $$sdate )
106   $options{'by_svcnum'} = 1 if $svc_field eq 'svcnum';
107
108   ###
109   # pass one: find the total minutes/calls and store the CDRs
110   ###
111   my $total = 0;
112
113   my @cust_svc;
114   if( $self->option('bill_inactive_svcs',1) ) {
115     #XXX in this mode do we need to restrict the set of CDRs by date also?
116     @cust_svc = $cust_pkg->h_cust_svc($$sdate, $last_bill);
117   } else {
118     @cust_svc = $cust_pkg->cust_svc;
119   }
120   @cust_svc = grep { $_->part_svc->svcdb eq $svc_table } @cust_svc;
121
122   foreach my $cust_svc (@cust_svc) {
123
124     my $svc_x;
125     if( $self->option('bill_inactive_svcs',1) ) {
126       $svc_x = $cust_svc->h_svc_x($$sdate, $last_bill);
127     }
128     else {
129       $svc_x = $cust_svc->svc_x;
130     }
131
132     foreach my $pass (split('_', $cdr_inout)) {
133
134       $options{'inbound'} = ( $pass eq 'inbound' );
135
136       my $cdr_search = $svc_x->psearch_cdrs(%options);
137       $cdr_search->limit(1000);
138       $cdr_search->increment(0);
139       while ( my $cdr = $cdr_search->fetch ) {
140
141         if ( $DEBUG > 1 ) {
142           warn "rating CDR $cdr\n".
143                join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
144         }
145
146         my $charge = '';
147         my $seconds = '';
148
149         $seconds = $use_duration ? $cdr->duration : $cdr->billsec;
150
151         $seconds += $granularity - ( $seconds % $granularity )
152           if $seconds      # don't granular-ize 0 billsec calls (bills them)
153           && $granularity  # 0 is per call
154           && $seconds % $granularity;
155         my $minutes = $granularity ? ($seconds / 60) : 1;
156
157         my $charge_min = $minutes;
158
159         $included_min -= $minutes;
160         if ( $included_min > 0 ) {
161           $charge_min = 0;
162         } else {
163            $charge_min = 0 - $included_min;
164            $included_min = 0;
165         }
166
167         my $error = $cdr->set_status_and_rated_price(
168           'processing-tiered',
169           '', #charge,
170           $cust_svc->svcnum,
171           'inbound'       => ($pass eq 'inbound'),
172           'rated_minutes' => $charge_min,
173           'rated_seconds' => $seconds,
174         );
175         die $error if $error;
176
177         $total += $charge_min;
178
179         $cdr_search->adjust(1) if $cdr->freesidestatus eq '';
180
181       } # $cdr
182
183     } # $pass
184  
185   } # $cust_svc
186
187   ###
188   # pass two: find a tiered rate and do the rest
189   ###
190
191   my $rate_tier = qsearchs('rate_tier', { tiernum=>$self->option('tiernum') } )
192     or die "unknown tiernum ". $self->option('tiernum');
193   my $rate_tier_detail = $rate_tier->rate_tier_detail( $total )
194     or die "no base rate for tier? ($total)";
195   my $min_charge = $rate_tier_detail->min_charge;
196
197   my $output_format = $self->option('output_format', 'Hush!') || 'default';
198
199   my $formatter = FS::detail_format->new($output_format, buffer => $details);
200
201   my $charges = 0;
202
203   $options{'status'} = 'processing-tiered';
204
205   foreach my $cust_svc (@cust_svc) {
206
207     my $svc_x;
208     if( $self->option('bill_inactive_svcs',1) ) {
209       $svc_x = $cust_svc->h_svc_x($$sdate, $last_bill);
210     }
211     else {
212       $svc_x = $cust_svc->svc_x;
213     }
214
215     foreach my $pass (split('_', $cdr_inout)) {
216
217       $options{'inbound'} = ( $pass eq 'inbound' );
218       # tell the formatter what we're sending it
219       $formatter->inbound($options{'inbound'});
220
221       my $cdr_search = $svc_x->psearch_cdrs(%options);
222       $cdr_search->limit(1000);
223       $cdr_search->increment(0);
224       while ( my $cdr = $cdr_search->fetch ) {
225
226         my $object = $options{'inbound'}
227                        ? $cdr->cdr_termination( 1 ) #1: inbound
228                        : $cdr;
229
230         my $charge_min = $object->rated_minutes;
231
232         my $charge = sprintf('%.4f', ( $min_charge * $charge_min )
233                                      + 0.0000000001 ); #so 1.00005 rounds to 1.0001
234
235         if ( $charge > 0 ) {
236           $charges += $charge;
237         }
238
239         my $error = $cdr->set_status_and_rated_price(
240           'done',
241           $charge,
242           $cust_svc->svcnum,
243           'inbound'       => $options{'inbound'},
244           'rated_minutes' => $charge_min,
245           'rated_seconds' => $object->rated_seconds,
246         );
247         die $error if $error;
248
249         $formatter->append($cdr);
250
251         $cdr_search->adjust(1) if $cdr->freesidestatus eq 'processing-tiered';
252
253       } # $cdr
254
255     } # $pass
256
257   } # $cust_svc
258
259   $formatter->finish;
260   unshift @$details, $formatter->header if @$details;
261
262   $charges;
263 }
264
265 1;
266