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             [ 'C',
283               $call_details[0],
284               $charge,
285               $cdr->calltypenum, #classnum
286               '', #phonenum,
287               $cdr->accountcode,
288               $cdr->startdate,
289               $seconds,
290               '', #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, [ 'C',
303                        FS::cdr::invoice_header($output_format),
304                        '',
305                        '',
306                        '',
307                        '',
308                        '',
309                      ]
310     if @$details;
311
312   $charges;
313 }
314
315 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
316 sub check_chargable {
317   my( $self, $cdr, %flags ) = @_;
318
319   #should have some better way of checking these options from a hash
320   #or something
321
322   my @opt = qw(
323     use_amaflags
324     use_carrierid
325     use_cdrtypenum
326     ignore_cdrtypenum
327     disposition_in
328     ignore_disposition
329     skip_dcontext
330     skip_dstchannel_prefix
331     skip_dst_length_less
332     skip_lastapp
333   );
334   foreach my $opt (grep !exists($flags{option_cache}->{$_}), @opt ) {
335     $flags{option_cache}->{$opt} = $self->option($opt, 1);
336   }
337   my %opt = %{ $flags{option_cache} };
338
339   return 'amaflags != 2'
340     if $opt{'use_amaflags'} && $cdr->amaflags != 2;
341
342   return "disposition NOT IN ( $opt{'disposition_in'} )"
343     if $opt{'disposition_in'} =~ /\S/
344     && !grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $opt{'disposition_in'});
345     
346   return "disposition IN ( $opt{'ignore_disposition'} )"
347     if $opt{'ignore_disposition'} =~ /\S/
348     && grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $opt{'ignore_disposition'});
349
350   return "carrierid != $opt{'use_carrierid'}"
351     if length($opt{'use_carrierid'})
352     && $cdr->carrierid ne $opt{'use_carrierid'}; #ne otherwise 0 matches ''
353
354   return "cdrtypenum != $opt{'use_cdrtypenum'}"
355     if length($opt{'use_cdrtypenum'})
356     && $cdr->cdrtypenum ne $opt{'use_cdrtypenum'}; #ne otherwise 0 matches ''
357     
358   return "cdrtypenum == $opt{'ignore_cdrtypenum'}"
359     if length($opt{'ignore_cdrtypenum'})
360     && $cdr->cdrtypenum eq $opt{'ignore_cdrtypenum'}; #eq otherwise 0 matches ''
361
362   return "dcontext IN ( $opt{'skip_dcontext'} )"
363     if $opt{'skip_dcontext'} =~ /\S/
364     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $opt{'skip_dcontext'});
365
366   my $len_prefix = length($opt{'skip_dstchannel_prefix'});
367   return "dstchannel starts with $opt{'skip_dstchannel_prefix'}"
368     if $len_prefix
369     && substr($cdr->dstchannel,0,$len_prefix) eq $opt{'skip_dstchannel_prefix'};
370
371   my $dst_length = $opt{'skip_dst_length_less'};
372   return "destination less than $dst_length digits"
373     if $dst_length && length($cdr->dst) < $dst_length;
374
375   return "lastapp is $opt{'skip_lastapp'}"
376     if length($opt{'skip_lastapp'}) && $cdr->lastapp eq $opt{'skip_lastapp'};
377
378   #all right then, rate it
379   '';
380 }
381
382 sub is_free {
383   0;
384 }
385
386 #  This equates svc_phone records; perhaps svc_phone should have a field
387 #  to indicate it represents a line
388 sub calc_units {    
389   my($self, $cust_pkg ) = @_;
390   my $count = 
391       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
392   $count;
393 }
394
395 1;
396