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