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