c1382fb457f4118cf348b11ce9735a8c740a5d6d
[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   my $cdr_svc_method  = $self->option('cdr_svc_method',1)||'svc_phone.phonenum';
85   my $cdr_inout       = ($cdr_svc_method eq 'svc_phone.phonenum')
86                           && $self->option('cdr_inout',1)
87                           || 'outbound';
88   my $use_duration    = $self->option('use_duration');
89   my $granularity     = length($self->option('sec_granularity'))
90                           ? $self->option('sec_granularity')
91                           : 60;
92
93   #for check_chargable, so we don't keep looking up options inside the loop
94   my %opt_cache = ();
95
96   my($svc_table, $svc_field) = split('\.', $cdr_svc_method);
97
98   my %options = (
99     'disable_src'    => $self->option('disable_src'),
100     'default_prefix' => $self->option('default_prefix'),
101     'status'         => '',
102     'for_update'     => 1,
103   );  # $last_bill, $$sdate )
104   $options{'by_svcnum'} = 1 if $svc_field eq 'svcnum';
105
106   ###
107   # pass one: find the total minutes/calls and store the CDRs
108   ###
109   my $total = 0;
110
111   my @cust_svc;
112   if( $self->option('bill_inactive_svcs',1) ) {
113     #XXX in this mode do we need to restrict the set of CDRs by date also?
114     @cust_svc = $cust_pkg->h_cust_svc($$sdate, $last_bill);
115   } else {
116     @cust_svc = $cust_pkg->cust_svc;
117   }
118   @cust_svc = grep { $_->part_svc->svcdb eq $svc_table } @cust_svc;
119
120   foreach my $cust_svc (@cust_svc) {
121
122     my $svc_x;
123     if( $self->option('bill_inactive_svcs',1) ) {
124       $svc_x = $cust_svc->h_svc_x($$sdate, $last_bill);
125     }
126     else {
127       $svc_x = $cust_svc->svc_x;
128     }
129
130     foreach my $pass (split('_', $cdr_inout)) {
131
132       $options{'inbound'} = ( $pass eq 'inbound' );
133
134       foreach my $cdr (
135         $svc_x->get_cdrs( %options )
136       ) {
137         if ( $DEBUG > 1 ) {
138           warn "rating CDR $cdr\n".
139                join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
140         }
141
142         my $charge = '';
143         my $seconds = '';
144
145         $seconds = $use_duration ? $cdr->duration : $cdr->billsec;
146
147         $seconds += $granularity - ( $seconds % $granularity )
148           if $seconds      # don't granular-ize 0 billsec calls (bills them)
149           && $granularity  # 0 is per call
150           && $seconds % $granularity;
151         my $minutes = $granularity ? ($seconds / 60) : 1;
152
153         my $charge_min = $minutes;
154
155         $included_min -= $minutes;
156         if ( $included_min > 0 ) {
157           $charge_min = 0;
158         } else {
159            $charge_min = 0 - $included_min;
160            $included_min = 0;
161         }
162
163         my $error = $cdr->set_status_and_rated_price(
164           'processing-tiered',
165           '', #charge,
166           $cust_svc->svcnum,
167           'inbound'       => ($pass eq 'inbound'),
168           'rated_minutes' => $charge_min,
169           'rated_seconds' => $seconds,
170         );
171         die $error if $error;
172
173         $total += $charge_min;
174
175       } # $cdr
176
177     } # $pass
178  
179   } # $cust_svc
180
181   ###
182   # pass two: find a tiered rate and do the rest
183   ###
184
185   my $rate_tier = qsearchs('rate_tier', { tiernum=>$self->option('tiernum') } )
186     or die "unknown tiernum ". $self->option('tiernum');
187   my $rate_tier_detail = $rate_tier->rate_tier_detail( $total )
188     or die "no base rate for tier? ($total)";
189   my $min_charge = $rate_tier_detail->min_charge;
190
191   my $output_format = $self->option('output_format', 'Hush!') || 'default';
192
193   my $csv = new Text::CSV_XS;
194
195   my $charges = 0;
196   my @invoice_details_sort;
197
198   $options{'status'} = 'processing-tiered';
199
200   foreach my $cust_svc (@cust_svc) {
201
202     my $svc_x;
203     if( $self->option('bill_inactive_svcs',1) ) {
204       $svc_x = $cust_svc->h_svc_x($$sdate, $last_bill);
205     }
206     else {
207       $svc_x = $cust_svc->svc_x;
208     }
209
210     foreach my $pass (split('_', $cdr_inout)) {
211
212       $options{'inbound'} = ( $pass eq 'inbound' );
213
214       foreach my $cdr (
215         $svc_x->get_cdrs( %options )
216       ) {
217
218         my $object = $options{'inbound'}
219                        ? $cdr->cdr_termination( 1 ) #1: inbound
220                        : $cdr;
221
222         my $charge_min = $object->rated_minutes;
223
224         my $charge = sprintf('%.4f', ( $min_charge * $charge_min )
225                                      + 0.0000000001 ); #so 1.00005 rounds to 1.0001
226
227         if ( $charge > 0 ) {
228           $charges += $charge;
229
230           my $detail = $self->sum_usage ? '' :
231             $cdr->downstream_csv( 'format'  => $output_format,
232                                   'charge'  => $charge,
233                                   'seconds' => ($use_duration ? 
234                                                   $cdr->duration : 
235                                                   $cdr->billsec),
236                                   'granularity' => $granularity,
237                                 );
238
239           my $call_details =
240             { format      => 'C',
241               detail      => $detail,
242               amount      => $charge,
243               #classnum    => $cdr->calltypenum, #classnum
244               #phonenum    => $phonenum, #XXX need this to sort on them
245               accountcode => $cdr->accountcode,
246               startdate   => $cdr->startdate,
247               duration    => $object->rated_seconds,
248             };
249
250            #warn "  adding details on charge to invoice: [ ".
251           #    join(', ', @{$call_details} ). " ]"
252           #  if ( $DEBUG && ref($call_details) );
253           push @invoice_details_sort, [ $call_details, $cdr->calldate_unix ];
254         }
255
256         my $error = $cdr->set_status_and_rated_price(
257           'done',
258           $charge,
259           $cust_svc->svcnum,
260           'inbound'       => $options{'inbound'},
261           'rated_minutes' => $charge_min,
262           'rated_seconds' => $object->rated_seconds,
263         );
264         die $error if $error;
265
266       } # $cdr
267
268     } # $pass
269
270     if ( $self->sum_usage ) {
271       # then summarize all accumulated details within this svc_x
272       # and then flush them
273       push @$details, $self->sum_detail($svc_x, \@invoice_details_sort);
274       @invoice_details_sort = ();
275     }
276
277   } # $cust_svc
278
279   if ( !$self->sum_usage ) {
280     #sort them
281     my @sorted_invoice_details = 
282       sort { ${$a}[1] <=> ${$b}[1] } @invoice_details_sort;
283     foreach my $sorted_call_detail ( @sorted_invoice_details ) {
284         push @$details, ${$sorted_call_detail}[0];
285     }
286   }
287
288   unshift @$details, { format => 'C',
289                        detail => FS::cdr::invoice_header($output_format),
290                      }
291     if @$details;
292
293   $charges;
294 }
295
296 1;
297