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