add use_amaflags and use_disposition flags to voip_cdr price plan
[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::rate;
11 #use FS::rate_prefix;
12
13 @ISA = qw(FS::part_pkg::flat);
14
15 $DEBUG = 1;
16
17 tie my %rating_method, 'Tie::IxHash',
18   'prefix' => 'Rate calls by using destination prefix to look up a region and rate according to the internal prefix and rate tables',
19   '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.',
20   'upstream_simple' => 'Simply pass through and charge the "upstream_price" amount.',
21 ;
22
23 #tie my %cdr_location, 'Tie::IxHash',
24 #  'internal' => 'Internal: CDR records imported into the internal CDR table',
25 #  'external' => 'External: CDR records queried directly from an external '.
26 #                'Asterisk (or other?) CDR table',
27 #;
28
29 %info = (
30   'name' => 'VoIP rating by plan of CDR records in an internal (or external) SQL table',
31   'shortname' => 'VoIP/telco CDR rating (standard)',
32   'fields' => {
33     'setup_fee'     => { 'name' => 'Setup fee for this package',
34                          'default' => 0,
35                        },
36     'recur_fee'     => { 'name' => 'Base recurring fee for this package',
37                          'default' => 0,
38                        },
39     'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
40                                    ' of service at cancellation',
41                          'type' => 'checkbox',
42                        },
43     'ratenum'   => { 'name' => 'Rate plan',
44                      'type' => 'select',
45                      'select_table' => 'rate',
46                      'select_key'   => 'ratenum',
47                      'select_label' => 'ratename',
48                    },
49     'rating_method' => { 'name' => 'Region rating method',
50                          'type' => 'radio',
51                          'options' => \%rating_method,
52                        },
53
54     'default_prefix' => { 'name'    => 'Default prefix optionally prepended to customer DID numbers when searching for CDR records',
55                           'default' => '+1',
56                         },
57
58     'disable_src' => { 'name' => 'Disable rating of CDR records based on the "src" field in addition to "charged_party"',
59                        'type' => 'checkbox'
60                      },
61
62     'domestic_prefix' => { 'name'    => 'Destination prefix for domestic CDR records',
63                            'default' => '1',
64                          },
65
66 #    'domestic_prefix_required' => { 'name' => 'Require explicit destination prefix for domestic CDR records',
67 #                                    'type' => 'checkbox',
68 #                                  },
69
70     'international_prefix' => { 'name'    => 'Destination prefix for international CDR records',
71                                 'default' => '011',
72                               },
73
74     'use_amaflags' => { 'name' => 'Do not charge for CDRs where the amaflags field is not set to "2" ("BILL"/"BILLING").',
75                         'type' => 'checkbox',
76                       },
77
78     'use_disposition' => { 'name' => 'Do not charge for CDRs where the disposition flag is not set to "ANSWERED".',
79                            'type' => 'checkbox',
80                          },
81
82     #XXX also have option for an external db
83 #    'cdr_location' => { 'name' => 'CDR database location'
84 #                        'type' => 'select',
85 #                        'select_options' => \%cdr_location,
86 #                        'select_callback' => {
87 #                          'external' => {
88 #                            'enable' => [ 'datasrc', 'username', 'password' ],
89 #                          },
90 #                          'internal' => {
91 #                            'disable' => [ 'datasrc', 'username', 'password' ],
92 #                          }
93 #                        },
94 #                      },
95 #    'datasrc' => { 'name' => 'DBI data source for external CDR table',
96 #                   'disabled' => 'Y',
97 #                 },
98 #    'username' => { 'name' => 'External database username',
99 #                    'disabled' => 'Y',
100 #                  },
101 #    'password' => { 'name' => 'External database password',
102 #                    'disabled' => 'Y',
103 #                  },
104
105   },
106   'fieldorder' => [qw(
107                        setup_fee recur_fee unused_credit
108                        rating_method ratenum 
109                        default_prefix
110                        disable_src
111                        domestic_prefix international_prefix
112                        use_amaflags use_disposition
113                      )
114                   ],
115   'weight' => 40,
116 );
117
118 sub calc_setup {
119   my($self, $cust_pkg ) = @_;
120   $self->option('setup_fee');
121 }
122
123 #false laziness w/voip_sqlradacct... resolve it if that one ever gets used again
124 sub calc_recur {
125   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
126
127   my $last_bill = $cust_pkg->last_bill;
128
129   my $ratenum = $cust_pkg->part_pkg->option('ratenum');
130
131   my $spool_cdr = $cust_pkg->cust_main->spool_cdr;
132
133   my %included_min = ();
134
135   my $charges = 0;
136
137   my $downstream_cdr = '';
138
139   foreach my $cust_svc (
140     grep { $_->part_svc->svcdb eq 'svc_phone' } $cust_pkg->cust_svc
141   ) {
142
143     foreach my $cdr (
144       $cust_svc->get_cdrs_for_update()  # $last_bill, $$sdate )
145     ) {
146       if ( $DEBUG > 1 ) {
147         warn "rating CDR $cdr\n".
148              join('', map { "  $_ => ". $cdr->{$_}. "\n" } keys %$cdr );
149       }
150
151       my $rate_detail;
152       my( $rate_region, $regionnum );
153       my $pretty_destnum;
154       my $charge = '';
155       my @call_details = ();
156       if ( $self->option('rating_method') eq 'prefix'
157            || ! $self->option('rating_method')
158          )
159       {
160
161         if ( $self->option('use_amaflags') && $cdr->amaflags != 2 ) {
162
163           warn "not charging for CDR (amaflags != 2)\n" if $DEBUG;
164           $charge = 0;
165
166         } elsif ( $self->option('use_disposition')
167                   && $cdr->disposition ne 'ANSWERED' ) {
168
169           warn "not charging for CDR (disposition != ANSWERED)\n" if $DEBUG;
170           $charge = 0;
171
172         } else {
173
174           ###
175           # look up rate details based on called station id
176           # (or calling station id for toll free calls)
177           ###
178
179           my( $to_or_from, $number );
180           if ( $cdr->dst =~ /^(\+?1)?8([02-8])\1/ ) { #tollfree call
181             $to_or_from = 'from';
182             $number = $cdr->src;
183           } else { #regular call
184             $to_or_from = 'to';
185             $number = $cdr->dst;
186           }
187
188           #remove non-phone# stuff and whitespace
189           $number =~ s/\s//g;
190 #          my $proto = '';
191 #          $dest =~ s/^(\w+):// and $proto = $1; #sip:
192 #          my $siphost = '';
193 #          $dest =~ s/\@(.*)$// and $siphost = $1; # @10.54.32.1, @sip.example.com
194
195           my $intl = $self->option('international_prefix') || '011';
196
197           #determine the country code
198           my $countrycode;
199           if (    $number =~ /^$intl(((\d)(\d))(\d))(\d+)$/
200                || $number =~ /^\+(((\d)(\d))(\d))(\d+)$/
201              )
202           {
203
204             my( $three, $two, $one, $u1, $u2, $rest ) = ( $1,$2,$3,$4,$5,$6 );
205             #first look for 1 digit country code
206             if ( qsearch('rate_prefix', { 'countrycode' => $one } ) ) {
207               $countrycode = $one;
208               $number = $u1.$u2.$rest;
209             } elsif ( qsearch('rate_prefix', { 'countrycode' => $two } ) ) { #or 2
210               $countrycode = $two;
211               $number = $u2.$rest;
212             } else { #3 digit country code
213               $countrycode = $three;
214               $number = $rest;
215             }
216
217           } else {
218             $countrycode = $self->option('domestic_prefix') || '1';
219             $number =~ s/^$countrycode//;# if length($number) > 10;
220           }
221
222           warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
223           $pretty_destnum = "+$countrycode $number";
224
225           #find a rate prefix, first look at most specific (4 digits) then 3, etc.,
226           # finally trying the country code only
227           my $rate_prefix = '';
228           for my $len ( reverse(1..6) ) {
229             $rate_prefix = qsearchs('rate_prefix', {
230               'countrycode' => $countrycode,
231               #'npa'         => { op=> 'LIKE', value=> substr($number, 0, $len) }
232               'npa'         => substr($number, 0, $len),
233             } ) and last;
234           }
235           $rate_prefix ||= qsearchs('rate_prefix', {
236             'countrycode' => $countrycode,
237             'npa'         => '',
238           });
239
240           #
241           die "Can't find rate for call $to_or_from +$countrycode $number\n"
242             unless $rate_prefix;
243
244           $regionnum = $rate_prefix->regionnum;
245           $rate_detail = qsearchs('rate_detail', {
246             'ratenum'        => $ratenum,
247             'dest_regionnum' => $regionnum,
248           } );
249
250           $rate_region = $rate_prefix->rate_region;
251
252           warn "  found rate for regionnum $regionnum ".
253                "and rate detail $rate_detail\n"
254             if $DEBUG;
255
256         }
257
258       } elsif ( $self->option('rating_method') eq 'upstream' ) {
259
260         if ( $cdr->cdrtypenum == 1 ) { #rate based on upstream rateid
261
262           $rate_detail = $cdr->cdr_upstream_rate->rate_detail;
263
264           $regionnum = $rate_detail->dest_regionnum;
265           $rate_region = $rate_detail->dest_region;
266
267           $pretty_destnum = $cdr->dst;
268
269           warn "  found rate for regionnum $regionnum and ".
270                "rate detail $rate_detail\n"
271             if $DEBUG;
272
273         } else { #pass upstream price through
274
275           $charge = sprintf('%.2f', $cdr->upstream_price);
276           $charges += $charge;
277
278           @call_details = (
279             #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
280             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
281             'N/A', #minutes...
282             '$'.$charge,
283             #$pretty_destnum,
284             $cdr->description, #$rate_region->regionname,
285           );
286
287         }
288
289       } elsif ( $self->option('rating_method') eq 'upstream_simple' ) {
290
291         #XXX $charge = sprintf('%.2f', $cdr->upstream_price);
292         $charge = sprintf('%.3f', $cdr->upstream_price);
293         $charges += $charge;
294
295         @call_details = (
296           #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
297           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
298           sprintf('%.2f', $cdr->billsec / 60 ).'m',
299           '$'.$charge, #XXX $money_char
300           #$pretty_destnum,
301           $cdr->userfield, #$rate_region->regionname,
302           $cdr->dst,
303         );
304
305       } else {
306         die "don't know how to rate CDRs using method: ".
307             $self->option('rating_method'). "\n";
308       }
309
310       ###
311       # find the price and add detail to the invoice
312       ###
313
314       # if $rate_detail is not found, skip this CDR... i.e. 
315       # don't add it to invoice, don't set its status to NULL,
316       # don't call downstream_csv or something on it...
317       # but DO emit a warning...
318       #if ( ! $rate_detail && ! scalar(@call_details) ) {
319       if ( ! $rate_detail && $charge eq '' ) {
320
321         warn "no rate_detail found for CDR.acctid:  ". $cdr->acctid.
322              "; skipping\n"
323
324       } else { # there *is* a rate_detail (or call_details), proceed...
325
326         unless ( @call_details || ( $charge ne '' && $charge == 0 ) ) {
327
328           $included_min{$regionnum} = $rate_detail->min_included
329             unless exists $included_min{$regionnum};
330
331           my $granularity = $rate_detail->sec_granularity;
332           my $seconds = $cdr->billsec; # length($cdr->billsec) ? $cdr->billsec : $cdr->duration;
333           $seconds += $granularity - ( $seconds % $granularity )
334             if $seconds      # don't granular-ize 0 billsec calls (bills them)
335             && $granularity; # 0 is per call
336           my $minutes = sprintf("%.1f", $seconds / 60);
337           $minutes =~ s/\.0$// if $granularity == 60;
338
339           # per call rather than per minute
340           $minutes = 1 unless $granularity;
341
342           $included_min{$regionnum} -= $minutes;
343
344           if ( $included_min{$regionnum} < 0 ) {
345             my $charge_min = 0 - $included_min{$regionnum};
346             $included_min{$regionnum} = 0;
347             $charge = sprintf('%.2f', $rate_detail->min_charge * $charge_min );
348             $charges += $charge;
349           }
350
351           # this is why we need regionnum/rate_region....
352           warn "  (rate region $rate_region)\n" if $DEBUG;
353
354           @call_details = (
355             #time2str("%Y %b %d - %r", $cdr->calldate_unix ),
356             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
357             $granularity ? $minutes.'m' : $minutes.' call',
358             '$'.$charge,
359             $pretty_destnum,
360             $rate_region->regionname,
361           );
362
363         }
364
365         if ( $charge > 0 ) {
366           my $call_details = join(' - ', @call_details );
367           warn "  adding details on charge to invoice: $call_details"
368             if $DEBUG;
369           push @$details, $call_details; #\@call_details,
370         }
371
372         # if the customer flag is on, call "downstream_csv" or something
373         # like it to export the call downstream!
374         # XXX price plan option to pick format, or something...
375         $downstream_cdr .= $cdr->downstream_csv( 'format' => 'convergent' )
376           if $spool_cdr;
377
378         my $error = $cdr->set_status_and_rated_price('done', $charge);
379         die $error if $error;
380
381       }
382
383     } # $cdr
384
385   } # $cust_svc
386
387   if ( $spool_cdr && length($downstream_cdr) ) {
388
389     use FS::UID qw(datasrc);
390     my $dir = '/usr/local/etc/freeside/export.'. datasrc. '/cdr';
391     mkdir $dir, 0700 unless -d $dir;
392     $dir .= '/'. $cust_pkg->custnum.
393     mkdir $dir, 0700 unless -d $dir;
394     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
395
396     push @{ $param->{'precommit_hooks'} },
397          sub {
398                #lock the downstream spool file and append the records 
399                use Fcntl qw(:flock);
400                use IO::File;
401                my $spool = new IO::File ">>$filename"
402                  or die "can't open $filename: $!\n";
403                flock( $spool, LOCK_EX)
404                  or die "can't lock $filename: $!\n";
405                seek($spool, 0, 2)
406                  or die "can't seek to end of $filename: $!\n";
407                print $spool $downstream_cdr;
408                flock( $spool, LOCK_UN );
409                close $spool;
410              };
411
412   } #if ( $spool_cdr && length($downstream_cdr) )
413
414   $self->option('recur_fee') + $charges;
415
416 }
417
418 sub is_free {
419   0;
420 }
421
422 sub base_recur {
423   my($self, $cust_pkg) = @_;
424   $self->option('recur_fee');
425 }
426
427 1;
428