rate tiers for vnes, RT#14903
[freeside.git] / FS / FS / part_pkg / voip_inbound.pm
1 package FS::part_pkg::voip_inbound;
2 use base qw( FS::part_pkg::recur_Common );
3
4 use strict;
5 use vars qw($DEBUG %info);
6 use Date::Format;
7 use Tie::IxHash;
8 use Text::CSV_XS;
9 use FS::Conf;
10 use FS::Record qw(qsearchs qsearch);
11 use FS::cdr;
12 use FS::rate_detail;
13
14 $DEBUG = 0;
15
16 tie my %temporalities, 'Tie::IxHash',
17   'upcoming'  => "Upcoming (future)",
18   'preceding' => "Preceding (past)",
19 ;
20
21 tie my %granularity, 'Tie::IxHash', FS::rate_detail::granularities();
22
23 %info = (
24   'name' => 'VoIP flat rate pricing of CDRs for inbound calls',
25   'shortname' => 'VoIP/telco CDR rating (inbound)',
26   'inherit_fields' => [ 'prorate_Mixin', 'global_Mixin' ],
27   'fields' => {
28     #false laziness w/flat.pm
29     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
30                              'type' => 'select',
31                              'select_options' => \%temporalities,
32                            },
33     'cutoff_day'    => { 'name' => 'Billing Day (1 - 28) for prorating or '.
34                                    'subscription',
35                          'default' => '1',
36                        },
37
38     'recur_method'  => { 'name' => 'Recurring fee method',
39                          'type' => 'select',
40                          'select_options' => \%FS::part_pkg::recur_Common::recur_method,
41                        },
42
43     'min_charge' => { 'name' => 'Charge per minute',
44                     },
45     
46     'min_included' => { 'name' => 'Minutes included',
47                     },
48
49     'sec_granularity' => { 'name' => 'Granularity',
50                            'type' => 'select',
51                            'select_options' => \%granularity,
52                          },
53
54     'default_prefix' => { 'name'    => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
55                           'default' => '+1',
56                         },
57
58     'use_amaflags' => { 'name' => 'Only charge for CDRs where the amaflags field is set to "2" ("BILL"/"BILLING").',
59                         'type' => 'checkbox',
60                       },
61
62     'use_carrierid' => { 'name' => 'Only charge for CDRs where the Carrier ID is set to: ',
63                          },
64
65     'use_cdrtypenum' => { 'name' => 'Only charge for CDRs where the CDR Type is set to: ',
66                          },
67     
68     'ignore_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is set to: ',
69                          },
70
71     'ignore_disposition' => { 'name' => 'Do not charge for CDRs where the Disposition is set to any of these (comma-separated) values: ',
72                          },
73     
74     'disposition_in' => { 'name' => 'Only charge for CDRs where the Disposition is set to any of these (comma-separated) values: ',
75                          },
76
77     'skip_dcontext' => { 'name' => 'Do not charge for CDRs where the dcontext is set to any of these (comma-separated) values:',
78                        },
79
80     'skip_dstchannel_prefix' => { 'name' => 'Do not charge for CDRs where the dstchannel starts with:',
81                                 },
82
83     'skip_dst_length_less' => { 'name' => 'Do not charge for CDRs where the destination is less than this many digits:',
84                               },
85
86     'skip_lastapp' => { 'name' => 'Do not charge for CDRs where the lastapp matches this value',
87                       },
88
89     'use_duration'   => { 'name' => 'Calculate usage based on the duration field instead of the billsec field',
90                           'type' => 'checkbox',
91                         },
92
93     #false laziness w/cdr_termination.pm
94     'output_format' => { 'name' => 'CDR invoice display format',
95                          'type' => 'select',
96                          'select_options' => { FS::cdr::invoice_formats() },
97                          'default'        => 'default', #XXX test
98                        },
99
100     'usage_section' => { 'name' => 'Section in which to place usage charges (whether separated or not)',
101                        },
102
103     'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
104                           'type' => 'checkbox',
105                         },
106
107     'usage_mandate' => { 'name' => 'Always put usage details in separate section',
108                           'type' => 'checkbox',
109                        },
110     #eofalse
111
112     'bill_every_call' => { 'name' => 'Generate an invoice immediately for every call.  Useful for prepaid.',
113                            'type' => 'checkbox',
114                          },
115
116     #XXX also have option for an external db
117 #    'cdr_location' => { 'name' => 'CDR database location'
118 #                        'type' => 'select',
119 #                        'select_options' => \%cdr_location,
120 #                        'select_callback' => {
121 #                          'external' => {
122 #                            'enable' => [ 'datasrc', 'username', 'password' ],
123 #                          },
124 #                          'internal' => {
125 #                            'disable' => [ 'datasrc', 'username', 'password' ],
126 #                          }
127 #                        },
128 #                      },
129 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
130 #                   'disabled' => 'Y',
131 #                 },
132 #    'username' => { 'name' => 'External database username',
133 #                    'disabled' => 'Y',
134 #                  },
135 #    'password' => { 'name' => 'External database password',
136 #                    'disabled' => 'Y',
137 #                  },
138
139   },
140   'fieldorder' => [qw(
141                        recur_temporality
142                        recur_method cutoff_day ),
143                        FS::part_pkg::prorate_Mixin::fieldorder,
144                    qw( min_charge min_included sec_granularity
145                        default_prefix
146                        use_amaflags
147                        use_carrierid
148                        use_cdrtypenum ignore_cdrtypenum
149                        ignore_disposition disposition_in
150                        skip_dcontext skip_dstchannel_prefix
151                        skip_dst_length_less skip_lastapp
152                        use_duration
153                        output_format usage_mandate summarize_usage usage_section
154                        bill_every_call
155                      )
156                   ],
157   'weight' => 42,
158 );
159
160 sub price_info {
161     my $self = shift;
162     my $str = $self->SUPER::price_info;
163     $str .= " plus usage" if $str;
164     $str;
165 }
166
167 sub calc_recur {
168   my $self = shift;
169   my($cust_pkg, $sdate, $details, $param ) = @_;
170
171   my $charges = 0;
172
173   $charges += $self->calc_usage(@_);
174   $charges += $self->calc_recur_Common(@_);
175
176   $charges;
177
178 }
179
180 sub calc_cancel {
181   my $self = shift;
182   my($cust_pkg, $sdate, $details, $param ) = @_;
183
184   $self->calc_usage(@_);
185 }
186
187 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
188
189 sub calc_usage {
190   my $self = shift;
191   my($cust_pkg, $sdate, $details, $param ) = @_;
192
193   #my $last_bill = $cust_pkg->last_bill;
194   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
195
196   return 0
197     if $self->recur_temporality eq 'preceding'
198     && ( $last_bill eq '' || $last_bill == 0 );
199
200   my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
201
202
203   my $charges = 0;
204
205 #  my $downstream_cdr = '';
206
207   my $included_min  = $self->option('min_included', 1) || 0;
208   my $use_duration  = $self->option('use_duration');
209   my $output_format = $self->option('output_format', 1) || 'default';
210   my $granularity   = length($self->option('sec_granularity'))
211                         ? $self->option('sec_granularity')
212                         : 60;
213
214   #for check_chargable, so we don't keep looking up options inside the loop
215   my %opt_cache = ();
216
217   my $csv = new Text::CSV_XS;
218
219   foreach my $cust_svc (
220     grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
221   ) {
222     my $svc_phone = $cust_svc->svc_x;
223
224     foreach my $cdr ( $svc_phone->get_cdrs(
225       'inbound'        => 1,
226       'default_prefix' => $self->option('default_prefix'),
227       'status'         => '', # unprocessed only
228       'for_update'     => 1,
229       )
230     ) {
231
232       my $reason = $self->check_chargable( $cdr,
233                                            'option_cache' => \%opt_cache,
234                                          );
235       if ( $reason ) {
236         warn "not charging for CDR ($reason)\n" if $DEBUG;
237         next;
238       }
239
240       if ( $DEBUG > 1 ) {
241         warn "rating inbound CDR $cdr\n".
242              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
243       }
244
245       my $seconds = $use_duration ? $cdr->duration : $cdr->billsec;
246
247       $seconds += $granularity - ( $seconds % $granularity )
248         if $seconds      # don't granular-ize 0 billsec calls (bills them)
249         && $granularity; # 0 is per call
250       my $minutes = sprintf("%.1f",$seconds / 60); 
251       $minutes =~ s/\.0$// if $granularity == 60; # count whole minutes, convert to integer
252       $minutes = 1 unless $granularity; # per call
253
254       my $charge_min = $minutes;
255       my $charge = 0;
256
257       $included_min -= $minutes;
258       if ( $included_min > 0 ) {
259         $charge_min = 0;
260       }
261       else {
262          $charge_min = 0 - $included_min;
263          $included_min = 0;
264       }
265       
266       $charge = sprintf('%.4f', ( $self->option('min_charge') * $charge_min )
267                                 + 0.00000001 ); #so 1.00005 rounds to 1.0001
268
269       if ( $charge > 0 ) {
270         $charges += $charge;
271         my @call_details = (
272           $cdr->downstream_csv( 'format'      => $output_format,
273                                 'charge'      => $charge,
274                                 'seconds'     => ($use_duration
275                                                    ? $cdr->duration
276                                                    : $cdr->billsec
277                                                  ),
278                                 'granularity' => $granularity,
279                               )
280         );
281         push @$details,
282           { format      => 'C',
283             detail      => $call_details[0],
284             amount      => $charge,
285             classnum    => $cdr->calltypenum, #classnum
286             #phonenum    => $self->phonenum,
287             accountcode => $cdr->accountcode,
288             startdate   => $cdr->startdate,
289             duration    => $seconds,
290             # regionname?? => '', #regionname, not set for inbound calls
291           };
292      }
293
294      my $error = $cdr->set_status_and_rated_price( 'done',
295                                                   $charge,
296                                                   $cust_svc->svcnum,
297                                                   'inbound' => 1 );
298      die $error if $error;
299
300     } #$cdr
301   } # $cust_svc
302   unshift @$details, { format => 'C',
303                        detail => FS::cdr::invoice_header($output_format),
304                      }
305     if @$details;
306
307   $charges;
308 }
309
310 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
311 sub check_chargable {
312   my( $self, $cdr, %flags ) = @_;
313
314   #should have some better way of checking these options from a hash
315   #or something
316
317   my @opt = qw(
318     use_amaflags
319     use_carrierid
320     use_cdrtypenum
321     ignore_cdrtypenum
322     disposition_in
323     ignore_disposition
324     skip_dcontext
325     skip_dstchannel_prefix
326     skip_dst_length_less
327     skip_lastapp
328   );
329   foreach my $opt (grep !exists($flags{option_cache}->{$_}), @opt ) {
330     $flags{option_cache}->{$opt} = $self->option($opt, 1);
331   }
332   my %opt = %{ $flags{option_cache} };
333
334   return 'amaflags != 2'
335     if $opt{'use_amaflags'} && $cdr->amaflags != 2;
336
337   return "disposition NOT IN ( $opt{'disposition_in'} )"
338     if $opt{'disposition_in'} =~ /\S/
339     && !grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $opt{'disposition_in'});
340     
341   return "disposition IN ( $opt{'ignore_disposition'} )"
342     if $opt{'ignore_disposition'} =~ /\S/
343     && grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $opt{'ignore_disposition'});
344
345   return "carrierid != $opt{'use_carrierid'}"
346     if length($opt{'use_carrierid'})
347     && $cdr->carrierid ne $opt{'use_carrierid'}; #ne otherwise 0 matches ''
348
349   return "cdrtypenum != $opt{'use_cdrtypenum'}"
350     if length($opt{'use_cdrtypenum'})
351     && $cdr->cdrtypenum ne $opt{'use_cdrtypenum'}; #ne otherwise 0 matches ''
352     
353   return "cdrtypenum == $opt{'ignore_cdrtypenum'}"
354     if length($opt{'ignore_cdrtypenum'})
355     && $cdr->cdrtypenum eq $opt{'ignore_cdrtypenum'}; #eq otherwise 0 matches ''
356
357   return "dcontext IN ( $opt{'skip_dcontext'} )"
358     if $opt{'skip_dcontext'} =~ /\S/
359     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $opt{'skip_dcontext'});
360
361   my $len_prefix = length($opt{'skip_dstchannel_prefix'});
362   return "dstchannel starts with $opt{'skip_dstchannel_prefix'}"
363     if $len_prefix
364     && substr($cdr->dstchannel,0,$len_prefix) eq $opt{'skip_dstchannel_prefix'};
365
366   my $dst_length = $opt{'skip_dst_length_less'};
367   return "destination less than $dst_length digits"
368     if $dst_length && length($cdr->dst) < $dst_length;
369
370   return "lastapp is $opt{'skip_lastapp'}"
371     if length($opt{'skip_lastapp'}) && $cdr->lastapp eq $opt{'skip_lastapp'};
372
373   #all right then, rate it
374   '';
375 }
376
377 sub is_free {
378   0;
379 }
380
381 #  This equates svc_phone records; perhaps svc_phone should have a field
382 #  to indicate it represents a line
383 sub calc_units {    
384   my($self, $cust_pkg ) = @_;
385   my $count = 
386       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
387   $count;
388 }
389
390 1;
391