6e9b17293172726be6ae47a59ed769b7194da6a9
[freeside.git] / FS / FS / part_pkg / voip_inbound.pm
1 package FS::part_pkg::voip_inbound;
2
3 use strict;
4 use vars qw(@ISA $DEBUG %info);
5 use Date::Format;
6 use Tie::IxHash;
7 use FS::Conf;
8 use FS::Record qw(qsearchs qsearch);
9 use FS::part_pkg::recur_Common;
10 use FS::cdr;
11 use FS::part_pkg::recur_Common;
12
13 @ISA = qw(FS::part_pkg::recur_Common);
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   'fields' => {
28     'setup_fee'     => { 'name' => 'Setup fee for this package',
29                          'default' => 0,
30                        },
31     'recur_fee'     => { 'name' => 'Base recurring fee for this package',
32                          'default' => 0,
33                        },
34
35     #false laziness w/flat.pm
36     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
37                              'type' => 'select',
38                              'select_options' => \%temporalities,
39                            },
40
41     'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
42                                    ' of service at cancellation',
43                          'type' => 'checkbox',
44                        },
45
46     'cutoff_day'    => { 'name' => 'Billing Day (1 - 28) for prorating or '.
47                                    'subscription',
48                          'default' => '1',
49                        },
50
51     'recur_method'  => { 'name' => 'Recurring fee method',
52                          'type' => 'select',
53                          'select_options' => \%FS::part_pkg::recur_Common::recur_method,
54                        },
55
56     'min_charge' => { 'name' => 'Charge per minute',
57                     },
58
59     'sec_granularity' => { 'name' => 'Granularity',
60                            'type' => 'select',
61                            'select_options' => \%granularity,
62                          },
63
64     'default_prefix' => { 'name'    => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
65                           'default' => '+1',
66                         },
67
68     'disable_tollfree' => { 'name' => 'Disable automatic toll-free processing',
69                             'type' => 'checkbox',
70                           },
71
72     'use_amaflags' => { 'name' => 'Do not charge for CDRs where the amaflags field is not set to "2" ("BILL"/"BILLING").',
73                         'type' => 'checkbox',
74                       },
75
76     'use_disposition' => { 'name' => 'Do not charge for CDRs where the disposition flag is not set to "ANSWERED".',
77                            'type' => 'checkbox',
78                          },
79
80     'use_disposition_taqua' => { 'name' => 'Do not charge for CDRs where the disposition is not set to "100" (Taqua).',
81                                  'type' => 'checkbox',
82                                },
83
84     'use_carrierid' => { 'name' => 'Do not charge for CDRs where the Carrier ID is not set to: ',
85                          },
86
87     'use_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is not set to: ',
88                          },
89
90     'skip_dcontext' => { 'name' => 'Do not charge for CDRs where the dcontext is set to any of these (comma-separated) values:',
91                        },
92
93     'skip_dstchannel_prefix' => { 'name' => 'Do not charge for CDRs where the dstchannel starts with:',
94                                 },
95
96     'skip_dst_length_less' => { 'name' => 'Do not charge for CDRs where the destination is less than this many digits:',
97                               },
98
99     'skip_lastapp' => { 'name' => 'Do not charge for CDRs where the lastapp matches this value',
100                       },
101
102     'use_duration'   => { 'name' => 'Calculate usage based on the duration field instead of the billsec field',
103                           'type' => 'checkbox',
104                         },
105
106     #false laziness w/cdr_termination.pm
107     'output_format' => { 'name' => 'CDR invoice display format',
108                          'type' => 'select',
109                          'select_options' => { FS::cdr::invoice_formats() },
110                          'default'        => 'default', #XXX test
111                        },
112
113     'usage_section' => { 'name' => 'Section in which to place usage charges (whether separated or not)',
114                        },
115
116     'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
117                           'type' => 'checkbox',
118                         },
119
120     'usage_mandate' => { 'name' => 'Always put usage details in separate section',
121                           'type' => 'checkbox',
122                        },
123     #eofalse
124
125     'bill_every_call' => { 'name' => 'Generate an invoice immediately for every call.  Useful for prepaid.',
126                            'type' => 'checkbox',
127                          },
128
129     #XXX also have option for an external db
130 #    'cdr_location' => { 'name' => 'CDR database location'
131 #                        'type' => 'select',
132 #                        'select_options' => \%cdr_location,
133 #                        'select_callback' => {
134 #                          'external' => {
135 #                            'enable' => [ 'datasrc', 'username', 'password' ],
136 #                          },
137 #                          'internal' => {
138 #                            'disable' => [ 'datasrc', 'username', 'password' ],
139 #                          }
140 #                        },
141 #                      },
142 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
143 #                   'disabled' => 'Y',
144 #                 },
145 #    'username' => { 'name' => 'External database username',
146 #                    'disabled' => 'Y',
147 #                  },
148 #    'password' => { 'name' => 'External database password',
149 #                    'disabled' => 'Y',
150 #                  },
151
152   },
153   'fieldorder' => [qw(
154                        setup_fee recur_fee recur_temporality unused_credit
155                        recur_method cutoff_day
156                        min_charge sec_granularity
157                        ignore_unrateable
158                        default_prefix
159                        disable_src
160                        disable_tollfree
161                        use_amaflags use_disposition
162                        use_disposition_taqua use_carrierid use_cdrtypenum
163                        skip_dcontext skip_dstchannel_prefix
164                        skip_dst_length_less skip_lastapp
165                        use_duration
166                        output_format usage_mandate summarize_usage usage_section
167                        bill_every_call
168                        count_available_phones
169                      )
170                   ],
171   'weight' => 40,
172 );
173
174 sub calc_setup {
175   my($self, $cust_pkg ) = @_;
176   $self->option('setup_fee');
177 }
178
179 sub calc_recur {
180   my $self = shift;
181   my($cust_pkg, $sdate, $details, $param ) = @_;
182
183   my $charges = 0;
184
185   $charges += $self->calc_usage(@_);
186   $charges += $self->calc_recur_Common(@_);
187
188   $charges;
189
190 }
191
192 sub calc_cancel {
193   my $self = shift;
194   my($cust_pkg, $sdate, $details, $param ) = @_;
195
196   $self->calc_usage(@_);
197 }
198
199 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
200
201 sub calc_usage {
202   my $self = shift;
203   my($cust_pkg, $sdate, $details, $param ) = @_;
204
205   #my $last_bill = $cust_pkg->last_bill;
206   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
207
208   return 0
209     if $self->option('recur_temporality', 1) eq 'preceding'
210     && ( $last_bill eq '' || $last_bill == 0 );
211
212   my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
213
214   my %included_min = ();
215
216   my $charges = 0;
217
218 #  my $downstream_cdr = '';
219
220   my $disable_tollfree  = $self->option('disable_tollfree');
221   my $ignore_unrateable = $self->option('ignore_unrateable', 'Hush!');
222   my $use_duration      = $self->option('use_duration');
223
224   my $output_format     = $self->option('output_format', 'Hush!') || 'default';
225
226   #for check_chargable, so we don't keep looking up options inside the loop
227   my %opt_cache = ();
228
229   eval "use Text::CSV_XS;";
230   die $@ if $@;
231   my $csv = new Text::CSV_XS;
232
233   foreach my $cust_svc (
234     grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
235   ) {
236     my $svc_phone = $cust_svc->svc_x;
237
238     foreach my $cdr ( $svc_phone->get_cdrs(
239       'for_update'     => 1,
240       'status'         => '', # unprocessed only
241       'default_prefix' => $self->option('default_prefix'),
242       'inbound'        => 1,
243       )
244     ) {
245       if ( $DEBUG > 1 ) {
246         warn "rating inbound CDR $cdr\n".
247              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
248       }
249       my $granularity = length($self->option('sec_granularity'))
250                           ? $self->option('sec_granularity')
251                           : 60;
252
253       my $seconds = $use_duration ? $cdr->duration : $cdr->billsec;
254
255       $seconds += $granularity - ( $seconds % $granularity )
256         if $seconds      # don't granular-ize 0 billsec calls (bills them)
257         && $granularity; # 0 is per call
258       my $minutes = sprintf("%.1f",$seconds / 60); 
259       $minutes =~ s/\.0$// if $granularity == 60; # count whole minutes, convert to integer
260       $minutes = 1 unless $granularity; # per call
261       my $charge = sprintf('%.2f', ( $self->option('min_charge') * $minutes )
262                                 + 0.00000001 ); #so 1.00005 rounds to 1.0001
263       next if !$charge;
264       $charges += $charge;
265       my @call_details = ($cdr->downstream_csv( 'format' => $output_format,
266                                              'charge'  => $charge,
267                                              'minutes' => $minutes,
268                                              'granularity' => $granularity,
269                                            )
270                         );
271       push @$details,
272         [ 'C',
273           $call_details[0],
274           $charge,
275           $cdr->calltypenum, #classnum
276           $self->phonenum,
277           $seconds,
278           '', #regionname, not set for inbound calls
279         ];
280
281     my $error = $cdr->set_status_and_rated_price( 'done',
282                                                   $charge,
283                                                   $cust_svc->svcnum,
284                                                   'inbound' => 1 );
285     die $error if $error;
286
287     } #$cdr
288   } # $cust_svc
289   unshift @$details, [ 'C',
290                        FS::cdr::invoice_header($output_format),
291                        '',
292                        '',
293                        '',
294                        '',
295                        '',
296                      ]
297     if @$details;
298
299   $charges;
300 }
301
302 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
303 sub check_chargable {
304   my( $self, $cdr, %flags ) = @_;
305
306   #should have some better way of checking these options from a hash
307   #or something
308
309   my @opt = qw(
310     use_amaflags
311     use_disposition
312     use_disposition_taqua
313     use_carrierid
314     use_cdrtypenum
315     skip_dcontext
316     skip_dstchannel_prefix
317     skip_dst_length_less
318     skip_lastapp
319   );
320   foreach my $opt (grep !exists($flags{option_cache}->{$_}), @opt ) {
321     $flags{option_cache}->{$opt} = $self->option($opt, 1);
322   }
323   my %opt = %{ $flags{option_cache} };
324
325   return 'amaflags != 2'
326     if $opt{'use_amaflags'} && $cdr->amaflags != 2;
327
328   return 'disposition != ANSWERED'
329     if $opt{'use_disposition'} && $cdr->disposition ne 'ANSWERED';
330
331   return "disposition != 100"
332     if $opt{'use_disposition_taqua'} && $cdr->disposition != 100;
333
334   return "carrierid != $opt{'use_carrierid'}"
335     if length($opt{'use_carrierid'})
336     && $cdr->carrierid ne $opt{'use_carrierid'} #ne otherwise 0 matches ''
337     && ! $flags{'da_rewrote'};
338
339   return "cdrtypenum != $opt{'use_cdrtypenum'}"
340     if length($opt{'use_cdrtypenum'})
341     && $cdr->cdrtypenum ne $opt{'use_cdrtypenum'}; #ne otherwise 0 matches ''
342
343   return "dcontext IN ( $opt{'skip_dcontext'} )"
344     if $opt{'skip_dcontext'} =~ /\S/
345     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $opt{'skip_dcontext'});
346
347   my $len_prefix = length($opt{'skip_dstchannel_prefix'});
348   return "dstchannel starts with $opt{'skip_dstchannel_prefix'}"
349     if $len_prefix
350     && substr($cdr->dstchannel,0,$len_prefix) eq $opt{'skip_dstchannel_prefix'};
351
352   my $dst_length = $opt{'skip_dst_length_less'};
353   return "destination less than $dst_length digits"
354     if $dst_length && length($cdr->dst) < $dst_length;
355
356   return "lastapp is $opt{'skip_lastapp'}"
357     if length($opt{'skip_lastapp'}) && $cdr->lastapp eq $opt{'skip_lastapp'};
358
359   #all right then, rate it
360   '';
361 }
362
363 sub is_free {
364   0;
365 }
366
367 #  This equates svc_phone records; perhaps svc_phone should have a field
368 #  to indicate it represents a line
369 sub calc_units {    
370   my($self, $cust_pkg ) = @_;
371   my $count = 0;
372   if ( $self->option('count_available_phones', 1)) {
373     map { $count += ( $_->quantity || 0 ) }
374       grep { $_->part_svc->svcdb eq 'svc_phone' }
375       $cust_pkg->part_pkg->pkg_svc;
376   } else {
377     $count = 
378       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
379   }
380   $count;
381 }
382
383 1;
384