fix dev operation @ localhost, RT#13852
[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     foreach my $cdr ( $svc_phone->get_cdrs(
231       'inbound'        => 1,
232       'default_prefix' => $self->option('default_prefix'),
233       'status'         => '', # unprocessed only
234       'for_update'     => 1,
235       )
236     ) {
237
238       my $reason = $self->check_chargable( $cdr,
239                                            'option_cache' => \%opt_cache,
240                                          );
241       if ( $reason ) {
242         warn "not charging for CDR ($reason)\n" if $DEBUG;
243         next;
244       }
245
246       if ( $DEBUG > 1 ) {
247         warn "rating inbound CDR $cdr\n".
248              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
249       }
250
251       my $seconds = $use_duration ? $cdr->duration : $cdr->billsec;
252
253       $seconds += $granularity - ( $seconds % $granularity )
254         if $seconds      # don't granular-ize 0 billsec calls (bills them)
255         && $granularity; # 0 is per call
256       my $minutes = sprintf("%.1f",$seconds / 60); 
257       $minutes =~ s/\.0$// if $granularity == 60; # count whole minutes, convert to integer
258       $minutes = 1 unless $granularity; # per call
259
260       my $charge_min = $minutes;
261       my $charge = 0;
262
263       $included_min -= $minutes;
264       if ( $included_min > 0 ) {
265         $charge_min = 0;
266       }
267       else {
268          $charge_min = 0 - $included_min;
269          $included_min = 0;
270       }
271       
272       $charge = sprintf('%.4f', ( $self->option('min_charge') * $charge_min )
273                                 + 0.00000001 ); #so 1.00005 rounds to 1.0001
274
275       if ( $charge > 0 ) {
276         $charges += $charge;
277         my @call_details = (
278           $cdr->downstream_csv( 'format'      => $output_format,
279                                 'charge'      => $charge,
280                                 'seconds'     => ($use_duration
281                                                    ? $cdr->duration
282                                                    : $cdr->billsec
283                                                  ),
284                                 'granularity' => $granularity,
285                               )
286         );
287 #        push @$details,
288 #          { format      => 'C',
289 #            detail      => $call_details[0],
290 #            amount      => $charge,
291 #            classnum    => $cdr->calltypenum, #classnum
292 #            #phonenum    => $self->phonenum,
293 #            accountcode => $cdr->accountcode,
294 #            startdate   => $cdr->startdate,
295 #            duration    => $seconds,
296 #            # regionname?? => '', #regionname, not set for inbound calls
297 #          };
298       }
299
300       # eventually use FS::cdr::rate for this
301       my $error = $cdr->set_status_and_rated_price(
302         'done',
303         $charge,
304         $cust_svc->svcnum,
305         'rated_seconds'     => $use_duration ? $cdr->duration : $cdr->billsec,
306         'rated_granularity' => $granularity, 
307         'rated_classnum'    => $cdr->calltypenum,
308         'inbound'        => 1,
309       );
310       die $error if $error;
311       $formatter->append($cdr);
312
313     } #$cdr
314   } # $cust_svc
315 #  unshift @$details, { format => 'C',
316 #                       detail => FS::cdr::invoice_header($output_format),
317 #                     }
318 #    if @$details;
319   
320   $formatter->finish;
321   unshift @$details, $formatter->header if @$details;
322
323   $charges;
324 }
325
326 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
327 sub check_chargable {
328   my( $self, $cdr, %flags ) = @_;
329
330   #should have some better way of checking these options from a hash
331   #or something
332
333   my @opt = qw(
334     use_amaflags
335     use_carrierid
336     use_cdrtypenum
337     ignore_cdrtypenum
338     disposition_in
339     ignore_disposition
340     skip_dcontext
341     skip_dstchannel_prefix
342     skip_dst_length_less
343     skip_lastapp
344   );
345   foreach my $opt (grep !exists($flags{option_cache}->{$_}), @opt ) {
346     $flags{option_cache}->{$opt} = $self->option($opt, 1);
347   }
348   my %opt = %{ $flags{option_cache} };
349
350   return 'amaflags != 2'
351     if $opt{'use_amaflags'} && $cdr->amaflags != 2;
352
353   return "disposition NOT IN ( $opt{'disposition_in'} )"
354     if $opt{'disposition_in'} =~ /\S/
355     && !grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $opt{'disposition_in'});
356     
357   return "disposition IN ( $opt{'ignore_disposition'} )"
358     if $opt{'ignore_disposition'} =~ /\S/
359     && grep { $cdr->disposition eq $_ } split(/\s*,\s*/, $opt{'ignore_disposition'});
360
361   return "carrierid != $opt{'use_carrierid'}"
362     if length($opt{'use_carrierid'})
363     && $cdr->carrierid ne $opt{'use_carrierid'}; #ne otherwise 0 matches ''
364
365   return "cdrtypenum != $opt{'use_cdrtypenum'}"
366     if length($opt{'use_cdrtypenum'})
367     && $cdr->cdrtypenum ne $opt{'use_cdrtypenum'}; #ne otherwise 0 matches ''
368     
369   return "cdrtypenum == $opt{'ignore_cdrtypenum'}"
370     if length($opt{'ignore_cdrtypenum'})
371     && $cdr->cdrtypenum eq $opt{'ignore_cdrtypenum'}; #eq otherwise 0 matches ''
372
373   return "dcontext IN ( $opt{'skip_dcontext'} )"
374     if $opt{'skip_dcontext'} =~ /\S/
375     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $opt{'skip_dcontext'});
376
377   my $len_prefix = length($opt{'skip_dstchannel_prefix'});
378   return "dstchannel starts with $opt{'skip_dstchannel_prefix'}"
379     if $len_prefix
380     && substr($cdr->dstchannel,0,$len_prefix) eq $opt{'skip_dstchannel_prefix'};
381
382   my $dst_length = $opt{'skip_dst_length_less'};
383   return "destination less than $dst_length digits"
384     if $dst_length && length($cdr->dst) < $dst_length;
385
386   return "lastapp is $opt{'skip_lastapp'}"
387     if length($opt{'skip_lastapp'}) && $cdr->lastapp eq $opt{'skip_lastapp'};
388
389   #all right then, rate it
390   '';
391 }
392
393 sub is_free {
394   0;
395 }
396
397 #  This equates svc_phone records; perhaps svc_phone should have a field
398 #  to indicate it represents a line
399 sub calc_units {    
400   my($self, $cust_pkg ) = @_;
401   my $count = 
402       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
403   $count;
404 }
405
406 1;
407