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