2465ab509b0b86ded09c2d8bb9363ed332097aa4
[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 sub calc_recur {
9   my $self = shift;
10   my($cust_pkg, $sdate, $details, $param ) = @_;
11
12   my $charges = 0;
13
14   $charges += $self->calc_usage(@_);
15   $charges += $self->calc_prorate(@_, 1);
16   #$charges -= $self->calc_discount(@_);
17
18   $charges;
19
20 }
21
22 #sub calc_cancel {  #somehow trigger an early report?
23
24 #have to look at getting the discounts to apply to the usage charges
25 sub can_discount { 0; }
26
27 sub calc_usage {
28   my $self = shift;
29   my($cust_pkg, $sdate, $details, $param ) = @_;
30
31   my @sdate = localtime($$sdate);
32   my $rep_date = ($sdate[5]+1900). '-'. ($sdate[4]+1). '-01';
33   my $rep_sql = "
34     SELECT id FROM reports WHERE rep_date = ?
35                              AND reportname = 'MonthlyUsage' and iscomplete = 1
36   ";
37   my $rep_id = $self->scalar_sql($rep_sql, $rep_date) or return 0;
38
39   #abort if ! iscomplete instead?
40
41   my $conf = new FS::Conf;
42   my $money_char = $conf->config('money_char') || '$';
43
44   my $sql = "
45     SELECT value FROM reportfields
46       WHERE rep_id = $rep_id
47         AND name = ?
48         AND servciceid = ?
49   ";
50  
51   my $total = 0;
52   foreach my $svc_port (
53     grep $_->table('svc_port'), map $_->svc_x, $cust_pkg->cust_svc
54   ) {
55
56     my $serviceid = $svc_port->serviceid;
57
58     my $in  = $self->scalar_sql($sql, $self->_torrus_name, $serviceid.'_IN');
59     my $out = $self->scalar_sql($sql, $self->_torrus_name, $serviceid.'_OUT');
60
61     my $max = max($in,$out);
62
63     my $inc = $self->option($self->_torrus_base);#aggregate instead of per-port?
64     $max -= $inc;
65     next if $max < 0;
66
67     my $amount = sprintf('%.2f', $self->option($self->_torrus_rate) * $max );
68     $total += $amount;
69
70     #add usage details to invoice
71     my $l = $self->_torrus_label;
72     my $d = "Last month's usage for $serviceid: $max$l";
73     $d .= " (". ($max+$inc). "$l - $inc$l included)" if $inc;
74     $d .= ": $money_char$amount";
75
76     push @$details, $d;
77
78   }
79
80   return sprintf('%.2f', $total );
81
82 }
83
84 1;