add an option to use duration instead of billsec to calculate billable time, RT#4147
[freeside.git] / FS / FS / part_pkg / voip_cdr.pm
1 package FS::part_pkg::voip_cdr;
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::flat;
10 use FS::cdr;
11 #use FS::rate;
12 #use FS::rate_prefix;
13
14 @ISA = qw(FS::part_pkg::flat);
15
16 $DEBUG = 1;
17
18 tie my %rating_method, 'Tie::IxHash',
19   'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
20   'upstream' => 'Rate calls based on upstream data: If the call type is "1", map the upstream rate ID directly to an internal rate (rate_detail), otherwise, pass the upstream price through directly.',
21   'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
22 ;
23
24 #tie my %cdr_location, 'Tie::IxHash',
25 #  'internal' => 'Internal: CDR records imported into the internal CDR table',
26 #  'external' => 'External: CDR records queried directly from an external '.
27 #                'Asterisk (or other?) CDR table',
28 #;
29
30 tie my %temporalities, 'Tie::IxHash',
31   'upcoming'  => "Upcoming (future)",
32   'preceding' => "Preceding (past)",
33 ;
34
35 %info = (
36   'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
37   'shortname' => 'VoIP/telco CDR rating (standard)',
38   'fields' => {
39     'setup_fee'     => { 'name' => 'Setup fee for this package',
40                          'default' => 0,
41                        },
42     'recur_fee'     => { 'name' => 'Base recurring fee for this package',
43                          'default' => 0,
44                        },
45
46     #false laziness w/flat.pm
47     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
48                              'type' => 'select',
49                              'select_options' => \%temporalities,
50                            },
51
52     'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
53                                    ' of service at cancellation',
54                          'type' => 'checkbox',
55                        },
56     'ratenum'   => { 'name' => 'Rate plan',
57                      'type' => 'select',
58                      'select_table' => 'rate',
59                      'select_key'   => 'ratenum',
60                      'select_label' => 'ratename',
61                    },
62     'rating_method' => { 'name' => 'Region rating method',
63                          'type' => 'radio',
64                          'options' => \%rating_method,
65                        },
66
67     'default_prefix' => { 'name'    => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
68                           'default' => '+1',
69                         },
70
71     'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
72                        'type' => 'checkbox'
73                      },
74
75     'domestic_prefix' => { 'name'    => 'Destination prefix for domestic CDR records',
76                            'default' => '1',
77                          },
78
79 #    'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
80 #                                    'type' => 'checkbox',
81 #                                  },
82
83     'international_prefix' => { 'name'    => 'Destination prefix for international CDR records',
84                                 'default' => '011',
85                               },
86
87     'disable_tollfree' => { 'name' => 'Disable automatic toll-free processing',
88                             'type' => 'checkbox',
89                           },
90
91     'use_amaflags' => { 'name' => 'Do not charge for CDRs where the amaflags field is not set to "2" ("BILL"/"BILLING").',
92                         'type' => 'checkbox',
93                       },
94
95     'use_disposition' => { 'name' => 'Do not charge for CDRs where the disposition flag is not set to "ANSWERED".',
96                            'type' => 'checkbox',
97                          },
98
99     'use_disposition_taqua' => { 'name' => 'Do not charge for CDRs where the disposition is not set to "100" (Taqua).',
100                                  'type' => 'checkbox',
101                                },
102
103     'use_carrierid' => { 'name' => 'Do not charge for CDRs where the Carrier ID is not set to: ',
104                          },
105
106     'use_cdrtypenum' => { 'name' => 'Do not charge for CDRs where the CDR Type is not set to: ',
107                          },
108
109     'use_duration'   => { 'name' => 'Calculate usage based on the duration field instead of the billsec field',
110                           'type' => 'checkbox',
111                         },
112
113     '411_rewrite' => { 'name' => 'Rewrite these (comma-separated) destination numbers to 411 for rating purposes: ',
114                       },
115
116     'output_format' => { 'name' => 'Simple output format',
117                          'type' => 'select',
118                          'select_options' => { FS::cdr::invoice_formats() },
119                        },
120
121     'usage_section' => { 'name' => 'Section in which to place separate usage charges',
122                        },
123
124     'summarize_usage' => { 'name' => 'Include usage summary with recurring charges when usage is in separate section',
125                           'type' => 'checkbox',
126                         },
127
128     #XXX also have option for an external db
129 #    'cdr_location' => { 'name' => 'CDR database location'
130 #                        'type' => 'select',
131 #                        'select_options' => \%cdr_location,
132 #                        'select_callback' => {
133 #                          'external' => {
134 #                            'enable' => [ 'datasrc', 'username', 'password' ],
135 #                          },
136 #                          'internal' => {
137 #                            'disable' => [ 'datasrc', 'username', 'password' ],
138 #                          }
139 #                        },
140 #                      },
141 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
142 #                   'disabled' => 'Y',
143 #                 },
144 #    'username' => { 'name' => 'External database username',
145 #                    'disabled' => 'Y',
146 #                  },
147 #    'password' => { 'name' => 'External database password',
148 #                    'disabled' => 'Y',
149 #                  },
150
151   },
152   'fieldorder' => [qw(
153                        setup_fee recur_fee recur_temporality unused_credit
154                        rating_method ratenum 
155                        default_prefix
156                        disable_src
157                        domestic_prefix international_prefix
158                        disable_tollfree
159                        use_amaflags use_disposition
160                        use_disposition_taqua use_carrierid use_cdrtypenum
161                        use_duration
162                        411_rewrite
163                        output_format summarize_usage usage_section
164                      )
165                   ],
166   'weight' => 40,
167 );
168
169 sub calc_setup {
170   my($self, $cust_pkg ) = @_;
171   $self->option('setup_fee');
172 }
173
174 #false laziness w/voip_sqlradacct calc_recur resolve it if that one ever gets used again
175 sub calc_recur {
176   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
177
178   #my $last_bill = $cust_pkg->last_bill;
179   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
180
181   return 0
182     if $self->option('recur_temporality', 1) eq 'preceding' && $last_bill == 0;
183
184   my $ratenum = $cust_pkg->part_pkg->option('ratenum');
185
186   my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
187
188   my %included_min = ();
189
190   my $charges = 0;
191
192   my $downstream_cdr = '';
193
194   my $output_format = $self->option('output_format', 'Hush!')
195                       || 'simple';
196
197   eval "use Text::CSV_XS;";
198   die $@ if $@;
199   my $csv = new Text::CSV_XS;
200
201   foreach my $cust_svc (
202     grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
203   ) {
204
205     foreach my $cdr (
206       $cust_svc->get_cdrs_for_update( 'disable_src'    => $self->option('disable_src'),
207                                       'default_prefix' => $self->option('default_prefix'),
208                                     )  # $last_bill, $$sdate )
209     ) {
210       if ( $DEBUG > 1 ) {
211         warn "rating CDR $cdr\n".
212              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
213       }
214
215       my $rate_detail;
216       my( $rate_region, $regionnum );
217       my $pretty_destnum;
218       my $charge = '';
219       my $classnum = '';
220       my @call_details = ();
221       if ( $self->option('rating_method') eq 'prefix'
222            || ! $self->option('rating_method')
223          )
224       {
225
226         #should have some better way of checking these options than a long
227         #if-else tree...
228         my $notchg = "not charging for CDR";
229
230         if ( $self->option('use_amaflags') && $cdr->amaflags != 2 ) {
231
232           warn "$notchg (amaflags != 2)\n" if $DEBUG;
233           $charge = 0;
234
235         } elsif ( $self->option('use_disposition')
236                   && $cdr->disposition ne 'ANSWERED' ) {
237
238           warn "$notchg (disposition != ANSWERED)\n" if $DEBUG;
239           $charge = 0;
240
241         } elsif ( $self->option('use_disposition_taqua')
242                   && $cdr->disposition != 100 ) {
243
244           warn "$notchg (disposition != 100)\n" if $DEBUG;
245           $charge = 0;
246
247         } elsif ( $self->option('use_carrierid')
248                   && $cdr->carrierid != $self->option('use_carrierid') ) {
249
250           warn "$notchg (carrierid != ". $self->option('use_carrierid'). ")\n"
251             if $DEBUG;
252           $charge = 0;
253
254         } elsif ( $self->option('use_cdrtypenum')
255                   && $cdr->cdrtypenum != $self->option('use_cdrtypenum') ) {
256
257           warn "$notchg (cdrtypenum != ". $self->option('use_cdrtypenum'). ")\n"
258             if $DEBUG;
259           $charge = 0;
260
261         } else {
262
263           ###
264           # look up rate details based on called station id
265           # (or calling station id for toll free calls)
266           ###
267
268           if ( $self->option('411_rewrite') ) {
269             my @dirass = split(/\s*,\s*/, $self->option('411_rewrite'));
270             $cdr->dst('411') if grep $cdr->dst eq $_, @dirass;
271           }
272
273           my( $to_or_from, $number );
274           if ( $cdr->dst =~ /^(\+?1)?8([02-8])\1/
275                && ! $self->option('disable_tollfree')
276               )
277           { #tollfree call
278             $to_or_from = 'from';
279             $number = $cdr->src;
280           } else { #regular call
281             $to_or_from = 'to';
282             $number = $cdr->dst;
283           }
284
285           warn "parsing call $to_or_from $number\n" if $DEBUG;
286
287           #remove non-phone# stuff and whitespace
288           $number =~ s/\s//g;
289 #          my $proto = '';
290 #          $dest =~ s/^(\w+):// and $proto = $1; #sip:
291 #          my $siphost = '';
292 #          $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
293
294           my $intl = $self->option('international_prefix') || '011';
295
296           #determine the country code
297           my $countrycode;
298           if (    $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
299                || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
300              )
301           {
302
303             my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
304             #first look for 1 digit country code
305             if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
306               $countrycode = $one;
307               $number = $u1.$u2.$rest;
308             } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
309               $countrycode = $two;
310               $number = $u2.$rest;
311             } else { #3 digit country code
312               $countrycode = $three;
313               $number = $rest;
314             }
315
316           } else {
317             $countrycode = $self->option('domestic_prefix') || '1';
318             $number =~ s/^$countrycode//;# if length($number) > 10;
319           }
320
321           warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
322           $pretty_destnum = "+$countrycode $number";
323
324           #find a rate prefix, first look at most specific (4 digits) then 3, etc.,
325           # finally trying the country code only
326           my $rate_prefix = '';
327           for my $len ( reverse(1..6) ) {
328             $rate_prefix = qsearchs('rate_prefix', {
329               'countrycode' => $countrycode,
330               #'npa'         => { op=> 'LIKE', value=> substr($number, 0, $len) }
331               'npa'         => substr($number, 0, $len),
332             } ) and last;
333           }
334           $rate_prefix ||= qsearchs('rate_prefix', {
335             'countrycode' => $countrycode,
336             'npa'         => '',
337           });
338
339           #
340           die "Can't find rate for call $to_or_from +$countrycode $number\n"
341             unless $rate_prefix;
342
343           $regionnum = $rate_prefix->regionnum;
344           $rate_detail = qsearchs('rate_detail', {
345             'ratenum'        => $ratenum,
346             'dest_regionnum' => $regionnum,
347           } );
348
349           $rate_region = $rate_prefix->rate_region;
350
351           warn "  found rate for regionnum $regionnum ".
352                "and rate detail $rate_detail\n"
353             if $DEBUG;
354
355         }
356
357       } elsif ( $self->option('rating_method') eq 'upstream' ) {
358
359         if ( $cdr->cdrtypenum == 1 ) { #rate based on upstream rateid
360
361           $rate_detail = $cdr->cdr_upstream_rate->rate_detail;
362
363           $regionnum = $rate_detail->dest_regionnum;
364           $rate_region = $rate_detail->dest_region;
365
366           $pretty_destnum = $cdr->dst;
367
368           warn "  found rate for regionnum $regionnum and ".
369                "rate detail $rate_detail\n"
370             if $DEBUG;
371
372         } else { #pass upstream price through
373
374           $charge = sprintf('%.2f', $cdr->upstream_price);
375           $charges += $charge;
376  
377           @call_details = (
378             #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
379             time2str("%c", $cdr->calldate_unix),  #XXX this should probably be a config option dropdown so they can select US vs- rest of world dates or whatnot
380             'N/A', #minutes...
381             '$'.$charge,
382             #$pretty_destnum,
383             $cdr->description, #$rate_region->regionname,
384           );
385
386         }
387
388       } elsif ( $self->option('rating_method') eq 'upstream_simple' ) {
389
390         #XXX $charge = sprintf('%.2f', $cdr->upstream_price);
391         $charge = sprintf('%.3f', $cdr->upstream_price);
392         $charges += $charge;
393
394         @call_details = ($cdr->downstream_csv( 'format' => $output_format ));
395
396       } else {
397         die "don't know how to rate CDRs using method: ".
398             $self->option('rating_method'). "\n";
399       }
400
401       ###
402       # find the price and add detail to the invoice
403       ###
404
405       # if $rate_detail is not found, skip this CDR... i.e. 
406       # don't add it to invoice, don't set its status to NULL,
407       # don't call downstream_csv or something on it...
408       # but DO emit a warning...
409       #if ( ! $rate_detail && ! scalar(@call_details) ) {
410       if ( ! $rate_detail && $charge eq '' ) {
411
412         warn "no rate_detail found for CDR.acctid:  ". $cdr->acctid.
413              "; skipping\n"
414
415       } else { # there *is* a rate_detail (or call_details), proceed...
416
417         unless ( @call_details || ( $charge ne '' && $charge == 0 ) ) {
418
419           $included_min{$regionnum} = $rate_detail->min_included
420             unless exists $included_min{$regionnum};
421
422           my $granularity = $rate_detail->sec_granularity;
423
424                       # length($cdr->billsec) ? $cdr->billsec : $cdr->duration;
425           my $seconds = $self->option('use_duration')
426                           ? $cdr->duration
427                           : $cdr->billsec;
428
429           $seconds += $granularity - ( $seconds % $granularity )
430             if $seconds      # don't granular-ize 0 billsec calls (bills them)
431             && $granularity; # 0 is per call
432           my $minutes = sprintf("%.1f", $seconds / 60);
433           $minutes =~ s/\.0$// if $granularity == 60;
434
435           # per call rather than per minute
436           $minutes = 1 unless $granularity;
437
438           $included_min{$regionnum} -= $minutes;
439
440           if ( $included_min{$regionnum} < 0 ) {
441             my $charge_min = 0 - $included_min{$regionnum};
442             $included_min{$regionnum} = 0;
443             $charge = sprintf('%.2f', $rate_detail->min_charge * $charge_min );
444             $charges += $charge;
445           }
446
447           # this is why we need regionnum/rate_region....
448           warn "  (rate region $rate_region)\n" if $DEBUG;
449
450           @call_details = (
451             #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
452             time2str("%c", $cdr->calldate_unix),  #XXX this should probably be a config option dropdown so they can select US vs- rest of world dates or whatnot
453             $granularity ? $minutes.'m' : $minutes.' call',
454             '$'.$charge,
455             $pretty_destnum,
456             $rate_region->regionname,
457           );
458
459           $classnum = $rate_detail->classnum;
460
461         }
462
463         if ( $charge > 0 ) {
464           #just use FS::cust_bill_pkg_detail objects?
465           my $call_details;
466           if ( $self->option('rating_method') eq 'upstream_simple' ) {
467             $call_details = [ 'C', $call_details[0], $charge, $classnum ];
468           }else{
469             $csv->combine(@call_details);
470             $call_details = [ 'C', $csv->string, $charge, $classnum ];
471           }
472           warn "  adding details on charge to invoice: [ ".
473               join(', ', @{$call_details} ). " ]"
474             if ( $DEBUG && ref($call_details) );
475           push @$details, $call_details; #\@call_details,
476         }
477
478         # if the customer flag is on, call "downstream_csv" or something
479         # like it to export the call downstream!
480         # XXX price plan option to pick format, or something...
481         $downstream_cdr .= $cdr->downstream_csv( 'format' => 'convergent' )
482           if $spool_cdr;
483
484         my $error = $cdr->set_status_and_rated_price('done', $charge);
485         die $error if $error;
486
487       }
488
489     } # $cdr
490
491     unshift @$details, [ 'C', FS::cdr::invoice_header( $output_format) ]
492       if (@$details && $self->option('rating_method') eq 'upstream_simple' );
493
494   } # $cust_svc
495
496   if ( $spool_cdr && length($downstream_cdr) ) {
497
498     use FS::UID qw(datasrc);
499     my $dir = '/usr/local/etc/freeside/export.'. datasrc. '/cdr';
500     mkdir $dir, 0700 unless -d $dir;
501     $dir .= '/'. $cust_pkg->custnum.
502     mkdir $dir, 0700 unless -d $dir;
503     my $filename = time2str("$dir/CDR%Y%m%d-spool.CSV", time); #XXX invoice date instead?  would require changing the order things are generated in cust_main::bill insert cust_bill first - with transactions it could be done though
504
505     push @{ $param->{'precommit_hooks'} },
506          sub {
507                #lock the downstream spool file and append the records 
508                use Fcntl qw(:flock);
509                use IO::File;
510                my $spool = new IO::File ">>$filename"
511                  or die "can't open $filename: $!\n";
512                flock( $spool, LOCK_EX)
513                  or die "can't lock $filename: $!\n";
514                seek($spool, 0, 2)
515                  or die "can't seek to end of $filename: $!\n";
516                print $spool $downstream_cdr;
517                flock( $spool, LOCK_UN );
518                close $spool;
519              };
520
521   } #if ( $spool_cdr && length($downstream_cdr) )
522
523   $self->option('recur_fee') + $charges;
524
525 }
526
527 sub is_free {
528   0;
529 }
530
531 sub base_recur {
532   my($self, $cust_pkg) = @_;
533   $self->option('recur_fee');
534 }
535
536 #  This equates svc_phone records; perhaps svc_phone should have a field
537 #  to indicate it represents a line
538 sub calc_units {    
539   my($self, $cust_pkg ) = @_;
540   scalar(grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc);
541 }
542
543 1;
544