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