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