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