taqua accountcode billing, part 1 of 2, RT12181
[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 price_info {
164     my $self = shift;
165     my $str = $self->SUPER::price_info;
166     $str .= " plus usage" if $str;
167     $str;
168 }
169
170 sub calc_setup {
171   my($self, $cust_pkg ) = @_;
172   $self->option('setup_fee');
173 }
174
175 sub calc_recur {
176   my $self = shift;
177   my($cust_pkg, $sdate, $details, $param ) = @_;
178
179   my $charges = 0;
180
181   $charges += $self->calc_usage(@_);
182   $charges += $self->calc_recur_Common(@_);
183
184   $charges;
185
186 }
187
188 sub calc_cancel {
189   my $self = shift;
190   my($cust_pkg, $sdate, $details, $param ) = @_;
191
192   $self->calc_usage(@_);
193 }
194
195 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
196
197 sub calc_usage {
198   my $self = shift;
199   my($cust_pkg, $sdate, $details, $param ) = @_;
200
201   #my $last_bill = $cust_pkg->last_bill;
202   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
203
204   return 0
205     if $self->recur_temporality eq 'preceding'
206     && ( $last_bill eq '' || $last_bill == 0 );
207
208   my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
209
210   my %included_min = ();
211
212   my $charges = 0;
213
214 #  my $downstream_cdr = '';
215
216   my $disable_tollfree  = $self->option('disable_tollfree');
217   my $ignore_unrateable = $self->option('ignore_unrateable', 'Hush!');
218   my $use_duration      = $self->option('use_duration');
219
220   my $output_format     = $self->option('output_format', 'Hush!') || 'default';
221
222   #for check_chargable, so we don't keep looking up options inside the loop
223   my %opt_cache = ();
224
225   eval "use Text::CSV_XS;";
226   die $@ if $@;
227   my $csv = new Text::CSV_XS;
228
229   foreach my $cust_svc (
230     grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
231   ) {
232     my $svc_phone = $cust_svc->svc_x;
233
234     foreach my $cdr ( $svc_phone->get_cdrs(
235       'for_update'     => 1,
236       'status'         => '', # unprocessed only
237       'default_prefix' => $self->option('default_prefix'),
238       'inbound'        => 1,
239       )
240     ) {
241       if ( $DEBUG > 1 ) {
242         warn "rating inbound CDR $cdr\n".
243              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
244       }
245       my $granularity = length($self->option('sec_granularity'))
246                           ? $self->option('sec_granularity')
247                           : 60;
248
249       my $seconds = $use_duration ? $cdr->duration : $cdr->billsec;
250
251       $seconds += $granularity - ( $seconds % $granularity )
252         if $seconds      # don't granular-ize 0 billsec calls (bills them)
253         && $granularity; # 0 is per call
254       my $minutes = sprintf("%.1f",$seconds / 60); 
255       $minutes =~ s/\.0$// if $granularity == 60; # count whole minutes, convert to integer
256       $minutes = 1 unless $granularity; # per call
257       my $charge = sprintf('%.2f', ( $self->option('min_charge') * $minutes )
258                                 + 0.00000001 ); #so 1.00005 rounds to 1.0001
259       next if !$charge;
260       $charges += $charge;
261       my @call_details = ($cdr->downstream_csv( 'format' => $output_format,
262                                              'charge'  => $charge,
263                                              'minutes' => $minutes,
264                                              'granularity' => $granularity,
265                                            )
266                         );
267       push @$details,
268         [ 'C',
269           $call_details[0],
270           $charge,
271           $cdr->calltypenum, #classnum
272           $self->phonenum,
273           $cdr->accountcode,
274           $seconds,
275           '', #regionname, not set for inbound calls
276         ];
277
278     my $error = $cdr->set_status_and_rated_price( 'done',
279                                                   $charge,
280                                                   $cust_svc->svcnum,
281                                                   'inbound' => 1 );
282     die $error if $error;
283
284     } #$cdr
285   } # $cust_svc
286   unshift @$details, [ 'C',
287                        FS::cdr::invoice_header($output_format),
288                        '',
289                        '',
290                        '',
291                        '',
292                        '',
293                      ]
294     if @$details;
295
296   $charges;
297 }
298
299 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
300 sub check_chargable {
301   my( $self, $cdr, %flags ) = @_;
302
303   #should have some better way of checking these options from a hash
304   #or something
305
306   my @opt = qw(
307     use_amaflags
308     use_disposition
309     use_disposition_taqua
310     use_carrierid
311     use_cdrtypenum
312     skip_dcontext
313     skip_dstchannel_prefix
314     skip_dst_length_less
315     skip_lastapp
316   );
317   foreach my $opt (grep !exists($flags{option_cache}->{$_}), @opt ) {
318     $flags{option_cache}->{$opt} = $self->option($opt, 1);
319   }
320   my %opt = %{ $flags{option_cache} };
321
322   return 'amaflags != 2'
323     if $opt{'use_amaflags'} && $cdr->amaflags != 2;
324
325   return 'disposition != ANSWERED'
326     if $opt{'use_disposition'} && $cdr->disposition ne 'ANSWERED';
327
328   return "disposition != 100"
329     if $opt{'use_disposition_taqua'} && $cdr->disposition != 100;
330
331   return "carrierid != $opt{'use_carrierid'}"
332     if length($opt{'use_carrierid'})
333     && $cdr->carrierid ne $opt{'use_carrierid'} #ne otherwise 0 matches ''
334     && ! $flags{'da_rewrote'};
335
336   return "cdrtypenum != $opt{'use_cdrtypenum'}"
337     if length($opt{'use_cdrtypenum'})
338     && $cdr->cdrtypenum ne $opt{'use_cdrtypenum'}; #ne otherwise 0 matches ''
339
340   return "dcontext IN ( $opt{'skip_dcontext'} )"
341     if $opt{'skip_dcontext'} =~ /\S/
342     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $opt{'skip_dcontext'});
343
344   my $len_prefix = length($opt{'skip_dstchannel_prefix'});
345   return "dstchannel starts with $opt{'skip_dstchannel_prefix'}"
346     if $len_prefix
347     && substr($cdr->dstchannel,0,$len_prefix) eq $opt{'skip_dstchannel_prefix'};
348
349   my $dst_length = $opt{'skip_dst_length_less'};
350   return "destination less than $dst_length digits"
351     if $dst_length && length($cdr->dst) < $dst_length;
352
353   return "lastapp is $opt{'skip_lastapp'}"
354     if length($opt{'skip_lastapp'}) && $cdr->lastapp eq $opt{'skip_lastapp'};
355
356   #all right then, rate it
357   '';
358 }
359
360 sub is_free {
361   0;
362 }
363
364 #  This equates svc_phone records; perhaps svc_phone should have a field
365 #  to indicate it represents a line
366 sub calc_units {    
367   my($self, $cust_pkg ) = @_;
368   my $count = 
369       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
370   $count;
371 }
372
373 1;
374