This commit was manufactured by cvs2svn to create tag 'freeside_2_1_1'.
[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                        default_prefix
158                        disable_tollfree
159                        use_amaflags use_disposition
160                        use_disposition_taqua use_carrierid use_cdrtypenum
161                        skip_dcontext skip_dstchannel_prefix
162                        skip_dst_length_less skip_lastapp
163                        use_duration
164                        output_format usage_mandate summarize_usage usage_section
165                        bill_every_call
166                      )
167                   ],
168   'weight' => 40,
169 );
170
171 sub calc_setup {
172   my($self, $cust_pkg ) = @_;
173   $self->option('setup_fee');
174 }
175
176 sub calc_recur {
177   my $self = shift;
178   my($cust_pkg, $sdate, $details, $param ) = @_;
179
180   my $charges = 0;
181
182   $charges += $self->calc_usage(@_);
183   $charges += $self->calc_recur_Common(@_);
184
185   $charges;
186
187 }
188
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->option('recur_temporality', 1) eq 'preceding'
207     && ( $last_bill eq '' || $last_bill == 0 );
208
209   my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
210
211   my %included_min = ();
212
213   my $charges = 0;
214
215 #  my $downstream_cdr = '';
216
217   my $disable_tollfree  = $self->option('disable_tollfree');
218   my $ignore_unrateable = $self->option('ignore_unrateable', 'Hush!');
219   my $use_duration      = $self->option('use_duration');
220
221   my $output_format     = $self->option('output_format', 'Hush!') || 'default';
222
223   #for check_chargable, so we don't keep looking up options inside the loop
224   my %opt_cache = ();
225
226   eval "use Text::CSV_XS;";
227   die $@ if $@;
228   my $csv = new Text::CSV_XS;
229
230   foreach my $cust_svc (
231     grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
232   ) {
233     my $svc_phone = $cust_svc->svc_x;
234
235     foreach my $cdr ( $svc_phone->get_cdrs(
236       'for_update'     => 1,
237       'status'         => '', # unprocessed only
238       'default_prefix' => $self->option('default_prefix'),
239       'inbound'        => 1,
240       )
241     ) {
242       if ( $DEBUG > 1 ) {
243         warn "rating inbound CDR $cdr\n".
244              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
245       }
246       my $granularity = length($self->option('sec_granularity'))
247                           ? $self->option('sec_granularity')
248                           : 60;
249
250       my $seconds = $use_duration ? $cdr->duration : $cdr->billsec;
251
252       $seconds += $granularity - ( $seconds % $granularity )
253         if $seconds      # don't granular-ize 0 billsec calls (bills them)
254         && $granularity; # 0 is per call
255       my $minutes = sprintf("%.1f",$seconds / 60); 
256       $minutes =~ s/\.0$// if $granularity == 60; # count whole minutes, convert to integer
257       $minutes = 1 unless $granularity; # per call
258       my $charge = sprintf('%.2f', ( $self->option('min_charge') * $minutes )
259                                 + 0.00000001 ); #so 1.00005 rounds to 1.0001
260       next if !$charge;
261       $charges += $charge;
262       my @call_details = ($cdr->downstream_csv( 'format' => $output_format,
263                                              'charge'  => $charge,
264                                              'minutes' => $minutes,
265                                              'granularity' => $granularity,
266                                            )
267                         );
268       push @$details,
269         [ 'C',
270           $call_details[0],
271           $charge,
272           $cdr->calltypenum, #classnum
273           $self->phonenum,
274           $seconds,
275           '', #regionname, not set for inbound calls
276         ];
277
278     my $error = $cdr->set_status_and_rated_price( 'done',
279                                                   $charge,
280                                                   $cust_svc->svcnum,
281                                                   'inbound' => 1 );
282     die $error if $error;
283
284     } #$cdr
285   } # $cust_svc
286   unshift @$details, [ 'C',
287                        FS::cdr::invoice_header($output_format),
288                        '',
289                        '',
290                        '',
291                        '',
292                        '',
293                      ]
294     if @$details;
295
296   $charges;
297 }
298
299 #returns a reason why not to rate this CDR, or false if the CDR is chargeable
300 sub check_chargable {
301   my( $self, $cdr, %flags ) = @_;
302
303   #should have some better way of checking these options from a hash
304   #or something
305
306   my @opt = qw(
307     use_amaflags
308     use_disposition
309     use_disposition_taqua
310     use_carrierid
311     use_cdrtypenum
312     skip_dcontext
313     skip_dstchannel_prefix
314     skip_dst_length_less
315     skip_lastapp
316   );
317   foreach my $opt (grep !exists($flags{option_cache}->{$_}), @opt ) {
318     $flags{option_cache}->{$opt} = $self->option($opt, 1);
319   }
320   my %opt = %{ $flags{option_cache} };
321
322   return 'amaflags != 2'
323     if $opt{'use_amaflags'} && $cdr->amaflags != 2;
324
325   return 'disposition != ANSWERED'
326     if $opt{'use_disposition'} && $cdr->disposition ne 'ANSWERED';
327
328   return "disposition != 100"
329     if $opt{'use_disposition_taqua'} && $cdr->disposition != 100;
330
331   return "carrierid != $opt{'use_carrierid'}"
332     if length($opt{'use_carrierid'})
333     && $cdr->carrierid ne $opt{'use_carrierid'} #ne otherwise 0 matches ''
334     && ! $flags{'da_rewrote'};
335
336   return "cdrtypenum != $opt{'use_cdrtypenum'}"
337     if length($opt{'use_cdrtypenum'})
338     && $cdr->cdrtypenum ne $opt{'use_cdrtypenum'}; #ne otherwise 0 matches ''
339
340   return "dcontext IN ( $opt{'skip_dcontext'} )"
341     if $opt{'skip_dcontext'} =~ /\S/
342     && grep { $cdr->dcontext eq $_ } split(/\s*,\s*/, $opt{'skip_dcontext'});
343
344   my $len_prefix = length($opt{'skip_dstchannel_prefix'});
345   return "dstchannel starts with $opt{'skip_dstchannel_prefix'}"
346     if $len_prefix
347     && substr($cdr->dstchannel,0,$len_prefix) eq $opt{'skip_dstchannel_prefix'};
348
349   my $dst_length = $opt{'skip_dst_length_less'};
350   return "destination less than $dst_length digits"
351     if $dst_length && length($cdr->dst) < $dst_length;
352
353   return "lastapp is $opt{'skip_lastapp'}"
354     if length($opt{'skip_lastapp'}) && $cdr->lastapp eq $opt{'skip_lastapp'};
355
356   #all right then, rate it
357   '';
358 }
359
360 sub is_free {
361   0;
362 }
363
364 #  This equates svc_phone records; perhaps svc_phone should have a field
365 #  to indicate it represents a line
366 sub calc_units {    
367   my($self, $cust_pkg ) = @_;
368   my $count = 
369       scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
370   $count;
371 }
372
373 1;
374