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