enable CardFortress in test database, #71513
[freeside.git] / FS / FS / cdr.pm
index 775c791..c4e9c47 100644 (file)
@@ -3,6 +3,7 @@ package FS::cdr;
 use strict;
 use vars qw( @ISA @EXPORT_OK $DEBUG $me
              $conf $cdr_prerate %cdr_prerate_cdrtypenums
+             $use_lrn $support_key
            );
 use Exporter;
 use List::Util qw(first min);
@@ -24,8 +25,14 @@ use FS::rate;
 use FS::rate_prefix;
 use FS::rate_detail;
 
+# LRN lookup
+use LWP::UserAgent;
+use HTTP::Request::Common qw(POST);
+use IO::Socket::SSL;
+use Cpanel::JSON::XS qw(decode_json);
+
 @ISA = qw(FS::Record);
-@EXPORT_OK = qw( _cdr_date_parser_maker _cdr_min_parser_maker );
+@EXPORT_OK = qw( _cdr_date_parser_maker _cdr_min_parser_maker _cdr_date_parse );
 
 $DEBUG = 0;
 $me = '[FS::cdr]';
@@ -39,6 +46,10 @@ FS::UID->install_callback( sub {
   @cdr_prerate_cdrtypenums = $conf->config('cdr-prerate-cdrtypenums')
     if $cdr_prerate;
   %cdr_prerate_cdrtypenums = map { $_=>1 } @cdr_prerate_cdrtypenums;
+
+  $support_key = $conf->config('support-key');
+  $use_lrn = $conf->exists('cdr-lrn_lookup');
+
 });
 
 =head1 NAME
@@ -215,7 +226,10 @@ sub table_info {
         'upstream_price'        => 'Upstream price',
         #'upstream_rateplanid'   => '',
         #'ratedetailnum'         => '',
+        'src_lrn'               => 'Source LRN',
+        'dst_lrn'               => 'Dest. LRN',
         'rated_price'           => 'Rated price',
+        'rated_cost'            => 'Rated cost',
         #'distance'              => '',
         #'islocal'               => '',
         #'calltypenum'           => '',
@@ -468,7 +482,9 @@ Sets the status and rated price.
 
 Available options are: inbound, rated_pretty_dst, rated_regionname,
 rated_seconds, rated_minutes, rated_granularity, rated_ratedetailnum,
-rated_classnum, rated_ratename.
+rated_classnum, rated_ratename.  If rated_ratedetailnum is provided,
+will also set a recalculated L</rate_cost> in the rated_cost field 
+after the other fields are set (does not work with inbound.)
 
 If there is an error, returns the error, otherwise returns false.
 
@@ -492,8 +508,9 @@ sub set_status_and_rated_price {
         rated_price => $rated_price,
         status      => $status,
     });
-    $term->rated_seconds($opt{rated_seconds}) if exists($opt{rated_seconds});
-    $term->rated_minutes($opt{rated_minutes}) if exists($opt{rated_minutes});
+    foreach (qw(rated_seconds rated_minutes rated_granularity)) {
+      $term->set($_, $opt{$_}) if exists($opt{$_});
+    }
     $term->svcnum($svcnum) if $svcnum;
     return $term->insert;
 
@@ -506,6 +523,8 @@ sub set_status_and_rated_price {
         qw( pretty_dst regionname seconds minutes granularity
             ratedetailnum classnum ratename );
     $self->svcnum($svcnum) if $svcnum;
+    $self->rated_cost($self->rate_cost) if $opt{'rated_ratedetailnum'};
+
     return $self->replace();
 
   }
@@ -541,6 +560,9 @@ sub parse_number {
 
   my $field = $options{column} || 'dst';
   my $intl = $options{international_prefix} || '011';
+  # Still, don't break anyone's CDR rating if they have an empty string in
+  # there. Require an explicit statement that there's no prefix.
+  $intl = '' if lc($intl) eq 'none';
   my $countrycode = '';
   my $number = $self->$field();
 
@@ -678,9 +700,6 @@ sub rate_prefix {
     }
   }
 
-    
-
-
   ###
   # look up rate details based on called station id
   # (or calling station id for toll free calls)
@@ -714,13 +733,32 @@ sub rate_prefix {
     domestic_prefix => $part_pkg->option_cacheable('domestic_prefix'),
   );
 
+  my $ratename = '';
+  my $intrastate_ratenum = $part_pkg->option_cacheable('intrastate_ratenum');
+
+  if ( $use_lrn and $countrycode eq '1' ) {
+
+    # then ask about the number
+    foreach my $field ('src', 'dst') {
+
+      $self->get_lrn($field);
+      if ( $field eq $column ) {
+        # then we are rating on this number
+        $number = $self->get($field.'_lrn');
+        $number =~ s/^1//;
+        # is this ever meaningful? can the LRN be outside NANP space?
+      }
+
+    } # foreach $field
+
+  }
+
   warn "rating call $to_or_from +$countrycode $number\n" if $DEBUG;
   my $pretty_dst = "+$countrycode $number";
   #asterisks here causes inserting the detail to barf, so:
   $pretty_dst =~ s/\*//g;
 
-  my $ratename = '';
-  my $intrastate_ratenum = $part_pkg->option_cacheable('intrastate_ratenum');
+  # should check $countrycode eq '1' here?
   if ( $intrastate_ratenum && !$self->is_tollfree ) {
     $ratename = 'Interstate'; #until proven otherwise
     # this is relatively easy only because:
@@ -729,8 +767,10 @@ sub rate_prefix {
     # -disregard private or unknown numbers
     # -there is exactly one record in rate_prefix for a given NPANXX
     # -default to interstate if we can't find one or both of the prefixes
+    my $dst_col = $use_lrn ? 'dst_lrn' : 'dst';
+    my $src_col = $use_lrn ? 'src_lrn' : 'src';
     my (undef, $dstprefix) = $self->parse_number(
-      column => 'dst',
+      column => $dst_col,
       international_prefix => $part_pkg->option_cacheable('international_prefix'),
       domestic_prefix => $part_pkg->option_cacheable('domestic_prefix'),
     );
@@ -739,7 +779,7 @@ sub rate_prefix {
                                                 'npa' => $1, 
                                          }) || '';
     my (undef, $srcprefix) = $self->parse_number(
-      column => 'src',
+      column => $src_col,
       international_prefix => $part_pkg->option_cacheable('international_prefix'),
       domestic_prefix => $part_pkg->option_cacheable('domestic_prefix'),
     );
@@ -919,8 +959,10 @@ sub rate_prefix {
 
       # by default, set the included minutes for this region/time to
       # what's in the rate_detail
-      $included_min->{$regionnum}{$ratetimenum} = $rate_detail->min_included
-        unless exists $included_min->{$regionnum}{$ratetimenum};
+      if (!exists( $included_min->{$regionnum}{$ratetimenum} )) {
+        $included_min->{$regionnum}{$ratetimenum} =
+          ($rate_detail->min_included * $cust_pkg->quantity || 1);
+      }
 
       if ( $included_min->{$regionnum}{$ratetimenum} >= $minutes ) {
         $charge_sec = 0;
@@ -1254,6 +1296,10 @@ my %export_names = (
     'name'           => 'Number of calls, one line per service',
     'invoice_header' => 'Caller,Rate,Messages,Price',
   },
+  'sum_duration' => {
+    'name'           => 'Summary, one line per service',
+    'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
+  },
   'sum_duration_prefix' => {
     'name'           => 'Summary, one line per destination prefix',
     'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
@@ -1262,6 +1308,10 @@ my %export_names = (
     'name'           => 'Summary, one line per usage class',
     'invoice_header' => 'Caller,Class,Calls,Price',
   },
+  'sum_duration_accountcode' => {
+    'name'           => 'Summary, one line per accountcode',
+    'invoice_header' => 'Caller,Rate,Calls,Minutes,Price',
+  },
 );
 
 my %export_formats = ();
@@ -1445,6 +1495,44 @@ sub downstream_csv {
 
 }
 
+sub get_lrn {
+  my $self = shift;
+  my $field = shift;
+
+  my $ua = LWP::UserAgent->new(
+             'ssl_opts' => {
+               verify_hostname => 0,
+               SSL_verify_mode => IO::Socket::SSL::SSL_VERIFY_NONE,
+             },
+           );
+
+  my $url = 'https://ws.freeside.biz/get_lrn';
+
+  my %content = ( 'support-key' => $support_key,
+                  'tn' => $self->get($field),
+                );
+  my $response = $ua->request( POST $url, \%content );
+
+  die "LRN service error: ". $response->message. "\n"
+    unless $response->is_success;
+
+  local $@;
+  my $data = eval { decode_json($response->content) };
+  die "LRN service JSON error : $@\n" if $@;
+
+  if ($data->{error}) {
+    die "acctid ".$self->acctid." $field LRN lookup failed:\n$data->{error}";
+    # for testing; later we should respect ignore_unrateable
+  } elsif ($data->{lrn}) {
+    # normal case
+    $self->set($field.'_lrn', $data->{lrn});
+  } else {
+    die "acctid ".$self->acctid." $field LRN lookup returned no number.\n";
+  }
+
+  return $data; # in case it's interesting somehow
+}
 =back
 
 =head1 CLASS METHODS