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