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