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