torrus, RT#10574
[freeside.git] / FS / FS / part_pkg / torrus_Common.pm
1 package FS::part_pkg::torrus_Common;
2
3 use base qw( FS::part_pkg::prorate );
4 use List::Util qw(max);
5
6 our %info = ( 'disabled' => 1 ); #torrus_Common not a usable price plan directly
7
8 our $DEBUG = 1;
9
10 sub calc_recur {
11   my $self = shift;
12   my($cust_pkg, $sdate, $details, $param ) = @_;
13
14   my $charges = 0;
15
16   $charges += $self->calc_usage(@_);
17   $charges += $self->calc_prorate(@_, 1);
18   #$charges -= $self->calc_discount(@_);
19
20   $charges;
21
22 }
23
24 #sub calc_cancel {  #somehow trigger an early report?
25
26 #have to look at getting the discounts to apply to the usage charges
27 sub can_discount { 0; }
28
29 sub calc_usage {
30   my $self = shift;
31   my($cust_pkg, $sdate, $details, $param ) = @_;
32
33   my @sdate = localtime($$sdate);
34   #sdate is next bill date, but we want the report from last month
35   my($m, $y) = ($sdate[4], $sdate[5]+1900);
36   if ( $m == 0 ) { $m=12; $y--; }
37   $m = "0$m" if length($m) == 1;
38   my $rep_date = "$y-$m-01";
39   warn "searching for MonthlyUsage report for $rep_date\n" if $DEBUG;
40   my $rep_sql = "
41     SELECT id FROM reports WHERE rep_date = ?
42                              AND reportname = 'MonthlyUsage' and iscomplete = 1
43   ";
44   my $rep_id = $self->scalar_sql($rep_sql, $rep_date) or return 0;
45   warn "report id $rep_id found\n" if $DEBUG;
46
47   #abort if ! iscomplete instead?
48
49   my $conf = new FS::Conf;
50   my $money_char = $conf->config('money_char') || '$';
51
52   my $sql = "
53     SELECT value FROM reportfields
54       WHERE rep_id = $rep_id
55         AND name = ?
56         AND servciceid = ?
57   ";
58  
59   my $total = 0;
60   foreach my $svc_port (
61     grep $_->table('svc_port'), map $_->svc_x, $cust_pkg->cust_svc
62   ) {
63
64     my $serviceid = $svc_port->serviceid;
65
66     warn "searching for $serviceid usage\n" if $DEBUG;
67     my $in  = $self->scalar_sql($sql, $self->_torrus_name, $serviceid.'_IN');
68     my $out = $self->scalar_sql($sql, $self->_torrus_name, $serviceid.'_OUT');
69
70     my $max = max($in,$out);
71     warn "$serviceid usage is $max\n" if $DEBUG;
72
73     my $inc = $self->option($self->_torrus_base);#aggregate instead of per-port?
74     $max -= $inc;
75     next if $max < 0;
76
77     my $amount = sprintf('%.2f', $self->option($self->_torrus_rate) * $max );
78     $total += $amount;
79
80     #add usage details to invoice
81     my $l = $self->_torrus_label;
82     my $d = "Last month's usage for $serviceid: $max$l";
83     $d .= " (". ($max+$inc). "$l - $inc$l included)" if $inc;
84     $d .= ": $money_char$amount";
85
86     push @$details, $d;
87
88   }
89
90   return sprintf('%.2f', $total );
91
92 }
93
94 1;