discount reporting, RT#6679
[freeside.git] / FS / FS / part_pkg / flat.pm
1 package FS::part_pkg::flat;
2
3 use strict;
4 use vars qw( @ISA %info
5              %usage_fields %usage_recharge_fields
6              @usage_fieldorder @usage_recharge_fieldorder
7            );
8 use Tie::IxHash;
9 use List::Util qw(min); # max);
10 #use FS::Record qw(qsearch);
11 use FS::UI::bytecount;
12 use FS::Conf;
13 use FS::part_pkg;
14 use FS::cust_bill_pkg_discount;
15
16 @ISA = qw(FS::part_pkg);
17
18 tie my %temporalities, 'Tie::IxHash',
19   'upcoming'  => "Upcoming (future)",
20   'preceding' => "Preceding (past)",
21 ;
22
23 %usage_fields = (
24
25     'seconds'       => { 'name' => 'Time limit for this package',
26                          'default' => '',
27                          'check' => sub { shift =~ /^\d*$/ },
28                        },
29     'upbytes'       => { 'name' => 'Upload limit for this package',
30                          'default' => '',
31                          'check' => sub { shift =~ /^\d*$/ },
32                          'format' => \&FS::UI::bytecount::display_bytecount,
33                          'parse' => \&FS::UI::bytecount::parse_bytecount,
34                        },
35     'downbytes'     => { 'name' => 'Download limit for this package',
36                          'default' => '',
37                          'check' => sub { shift =~ /^\d*$/ },
38                          'format' => \&FS::UI::bytecount::display_bytecount,
39                          'parse' => \&FS::UI::bytecount::parse_bytecount,
40                        },
41     'totalbytes'    => { 'name' => 'Transfer limit for this package',
42                          'default' => '',
43                          'check' => sub { shift =~ /^\d*$/ },
44                          'format' => \&FS::UI::bytecount::display_bytecount,
45                          'parse' => \&FS::UI::bytecount::parse_bytecount,
46                        },
47 );
48
49 %usage_recharge_fields = (
50
51     'recharge_amount'       => { 'name' => 'Cost of recharge for this package',
52                          'default' => '',
53                          'check' => sub { shift =~ /^\d*(\.\d{2})?$/ },
54                        },
55     'recharge_seconds'      => { 'name' => 'Recharge time for this package',
56                          'default' => '',
57                          'check' => sub { shift =~ /^\d*$/ },
58                        },
59     'recharge_upbytes'      => { 'name' => 'Recharge upload for this package',
60                          'default' => '',
61                          'check' => sub { shift =~ /^\d*$/ },
62                          'format' => \&FS::UI::bytecount::display_bytecount,
63                          'parse' => \&FS::UI::bytecount::parse_bytecount,
64                        },
65     'recharge_downbytes'    => { 'name' => 'Recharge download for this package',
66                          'default' => '',
67                          'check' => sub { shift =~ /^\d*$/ },
68                          'format' => \&FS::UI::bytecount::display_bytecount,
69                          'parse' => \&FS::UI::bytecount::parse_bytecount,
70                        },
71     'recharge_totalbytes'   => { 'name' => 'Recharge transfer for this package',
72                          'default' => '',
73                          'check' => sub { shift =~ /^\d*$/ },
74                          'format' => \&FS::UI::bytecount::display_bytecount,
75                          'parse' => \&FS::UI::bytecount::parse_bytecount,
76                        },
77     'usage_rollover' => { 'name' => 'Allow usage from previous period to roll '.
78                                     ' over into current period',
79                           'type' => 'checkbox',
80                         },
81     'recharge_reset' => { 'name' => 'Reset usage to these values on manual '.
82                                     'package recharge',
83                           'type' => 'checkbox',
84                         },
85 );
86
87 @usage_fieldorder = qw( seconds upbytes downbytes totalbytes );
88 @usage_recharge_fieldorder = qw(
89   recharge_amount recharge_seconds recharge_upbytes
90   recharge_downbytes recharge_totalbytes
91   usage_rollover recharge_reset
92 );
93
94 %info = (
95   'name' => 'Flat rate (anniversary billing)',
96   'shortname' => 'Anniversary',
97   'fields' => {
98     'setup_fee'     => { 'name' => 'Setup fee for this package',
99                          'default' => 0,
100                        },
101     'recur_fee'     => { 'name' => 'Recurring fee for this package',
102                          'default' => 0,
103                        },
104
105     #false laziness w/voip_cdr.pm
106     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
107                              'type' => 'select',
108                              'select_options' => \%temporalities,
109                            },
110
111     %usage_fields,
112     %usage_recharge_fields,
113
114     'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
115                                    ' of service at cancellation',
116                          'type' => 'checkbox',
117                        },
118     'externalid' => { 'name'   => 'Optional External ID',
119                       'default' => '',
120                     },
121   },
122   'fieldorder' => [ qw( setup_fee recur_fee recur_temporality unused_credit ),
123                     @usage_fieldorder, @usage_recharge_fieldorder,
124                     qw( externalid ),
125                   ],
126   'weight' => 10,
127 );
128
129 sub calc_setup {
130   my($self, $cust_pkg, $sdate, $details ) = @_;
131
132   my $i = 0;
133   my $count = $self->option( 'additional_count', 'quiet' ) || 0;
134   while ($i < $count) {
135     push @$details, $self->option( 'additional_info' . $i++ );
136   }
137
138   my $quantity = $cust_pkg->quantity || 1;
139
140   sprintf("%.2f", $quantity * $self->unit_setup($cust_pkg, $sdate, $details) );
141 }
142
143 sub unit_setup {
144   my($self, $cust_pkg, $sdate, $details ) = @_;
145
146   $self->option('setup_fee');
147 }
148
149 sub calc_recur {
150   my $self = shift;
151   my($cust_pkg) = @_;
152
153   #my $last_bill = $cust_pkg->last_bill;
154   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
155
156   return 0
157     if $self->option('recur_temporality', 1) eq 'preceding' && $last_bill == 0;
158
159   my $br = $self->base_recur(@_);
160
161   my $discount = $self->calc_discount(@_);
162
163   sprintf('%.2f', $br - $discount);
164 }
165
166 sub calc_discount {
167   my $self = shift;
168   my($cust_pkg, $sdate, $details, $param ) = @_;
169
170   my $br = $self->base_recur(@_);
171
172   my $tot_discount = 0;
173   #UI enforces just 1 for now, will need ordering when they can be stacked
174   foreach my $cust_pkg_discount ( $cust_pkg->cust_pkg_discount_active ) {
175      my $discount = $cust_pkg_discount->discount;
176      #UI enforces one or the other (for now?  probably for good)
177      my $amount = 0;
178      $amount += $discount->amount;
179      $amount += sprintf('%.2f', $discount->percent * $br / 100 );
180
181      my $chg_months = $param->{'months'} || $cust_pkg->part_pkg->freq;
182      
183      my $months = $discount->months
184                     ? min( $chg_months,
185                            $discount->months - $cust_pkg->months_used )
186                     : $chg_months;
187
188      my $error = $cust_pkg_discount->increment_months_used($months);
189      die "error discounting: $error" if $error;
190
191      $amount *= $months;
192      $amount = sprintf('%.2f', $amount);
193
194      next unless $amount > 0;
195
196      #record details in cust_bill_pkg_discount
197      my $cust_bill_pkg_discount = new FS::cust_bill_pkg_discount {
198        'pkgdiscountnum' => $cust_pkg_discount->pkgdiscountnum,
199        'amount'         => $amount,
200        'months'         => $months,
201      };
202      push @{ $param->{'discounts'} }, $cust_bill_pkg_discount;
203
204      #add details on discount to invoice
205      my $conf = new FS::Conf;
206      my $money_char = $conf->config('money_char') || '$';  
207      $months = sprintf('%.2f', $months) if $months =~ /\./;
208
209      my $d = 'Includes ';
210      $d .= $discount->name. ' ' if $discount->name;
211      $d .= 'discount of '. $discount->description_short;
212      $d .= " for $months month". ( $months!=1 ? 's' : '' );
213      $d .= ": $money_char$amount" if $months != 1 || $discount->percent;
214      push @$details, $d;
215
216      $tot_discount += $amount;
217   }
218
219   sprintf('%.2f', $tot_discount);
220 }
221
222 sub base_recur {
223   my($self, $cust_pkg) = @_;
224   $self->option('recur_fee', 1) || 0;
225 }
226
227 sub base_recur_permonth {
228   my($self, $cust_pkg) = @_;
229
230   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
231
232   sprintf('%.2f', $self->base_recur($cust_pkg) / $self->freq );
233 }
234
235 sub calc_remain {
236   my ($self, $cust_pkg, %options) = @_;
237
238   my $time;
239   if ($options{'time'}) {
240     $time = $options{'time'};
241   } else {
242     $time = time;
243   }
244
245   my $next_bill = $cust_pkg->getfield('bill') || 0;
246
247   #my $last_bill = $cust_pkg->last_bill || 0;
248   my $last_bill = $cust_pkg->get('last_bill') || 0; #->last_bill falls back to setup
249
250   return 0 if    ! $self->base_recur($cust_pkg)
251               || ! $self->option('unused_credit', 1)
252               || ! $last_bill
253               || ! $next_bill
254               || $next_bill < $time;
255
256   my %sec = (
257     'h' =>    3600, # 60 * 60
258     'd' =>   86400, # 60 * 60 * 24
259     'w' =>  604800, # 60 * 60 * 24 * 7
260     'm' => 2629744, # 60 * 60 * 24 * 365.2422 / 12 
261   );
262
263   $self->freq =~ /^(\d+)([hdwm]?)$/
264     or die 'unparsable frequency: '. $self->freq;
265   my $freq_sec = $1 * $sec{$2||'m'};
266   return 0 unless $freq_sec;
267
268   sprintf("%.2f", $self->base_recur($cust_pkg) * ( $next_bill - $time ) / $freq_sec );
269
270 }
271
272 sub is_free_options {
273   qw( setup_fee recur_fee );
274 }
275
276 sub is_prepaid { 0; } #no, we're postpaid
277
278 #XXX discounts only on recurring fees for now (no setup/one-time or usage)
279 sub can_discount {
280   my $self = shift;
281   $self->freq =~ /^\d+$/ && $self->freq > 0;
282 }
283
284 sub usage_valuehash {
285   my $self = shift;
286   map { $_, $self->option($_) }
287     grep { $self->option($_, 'hush') } 
288     qw(seconds upbytes downbytes totalbytes);
289 }
290
291 sub reset_usage {
292   my($self, $cust_pkg, %opt) = @_;
293   warn "   resetting usage counters" if defined($opt{debug}) && $opt{debug} > 1;
294   my %values = $self->usage_valuehash;
295   if ($self->option('usage_rollover', 1)) {
296     $cust_pkg->recharge(\%values);
297   }else{
298     $cust_pkg->set_usage(\%values, %opt);
299   }
300 }
301
302 1;