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