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