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