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