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