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