per-package option to adjust bill date on unsuspend, RT#8434
[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 FS::part_pkg::prorate_Mixin);
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     'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
111                                    ' of service at cancellation',
112                          'type' => 'checkbox',
113                        },
114
115     #used in cust_pkg.pm so could add to any price plan
116     'expire_months' => { 'name' => 'Auto-add an expiration date this number of months out',
117                        },
118     #used in cust_pkg.pm so could add to any price plan where it made sense
119     'start_1st'     => { 'name' => 'Auto-add a start date to the 1st, ignoring the current month.',
120                          'type' => 'checkbox',
121                        },
122     'sync_bill_date' => { 'name' => 'Prorate first month to synchronize '.
123                                     'with the customer\'s other packages',
124                           'type' => 'checkbox',
125                         },
126     'unsuspend_adjust_bill' => 
127                         { 'name' => 'Adjust next bill date forward when '.
128                                     'unsuspending',
129                           'type' => 'checkbox',
130                         },
131
132     %usage_fields,
133     %usage_recharge_fields,
134
135     'externalid' => { 'name'   => 'Optional External ID',
136                       'default' => '',
137                     },
138   },
139   'fieldorder' => [ qw( setup_fee recur_fee
140                         recur_temporality unused_credit
141                         expire_months start_1st sync_bill_date
142                         unsuspend_adjust_bill
143                       ),
144                     @usage_fieldorder, @usage_recharge_fieldorder,
145                     qw( externalid ),
146                   ],
147   'weight' => 10,
148 );
149
150 sub calc_setup {
151   my($self, $cust_pkg, $sdate, $details ) = @_;
152
153   my $i = 0;
154   my $count = $self->option( 'additional_count', 'quiet' ) || 0;
155   while ($i < $count) {
156     push @$details, $self->option( 'additional_info' . $i++ );
157   }
158
159   my $quantity = $cust_pkg->quantity || 1;
160
161   sprintf("%.2f", $quantity * $self->unit_setup($cust_pkg, $sdate, $details) );
162 }
163
164 sub unit_setup {
165   my($self, $cust_pkg, $sdate, $details ) = @_;
166
167   $self->option('setup_fee') || 0;
168 }
169
170 sub calc_recur {
171   my $self = shift;
172   my($cust_pkg, $sdate, $details, $param ) = @_;
173
174   #my $last_bill = $cust_pkg->last_bill;
175   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
176
177   return 0
178     if $self->option('recur_temporality', 1) eq 'preceding' && $last_bill == 0;
179
180   if( $self->option('sync_bill_date',1) ) {
181     return $self->calc_prorate(@_);
182   }
183   else {
184     my $charge = $self->base_recur($cust_pkg);
185     my $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
186
187     return sprintf('%.2f', $charge - $discount);
188   }
189 }
190
191 sub calc_discount {
192   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
193
194   my $br = $self->base_recur($cust_pkg);
195
196   my $tot_discount = 0;
197   #UI enforces just 1 for now, will need ordering when they can be stacked
198   my @cust_pkg_discount = $cust_pkg->cust_pkg_discount_active;
199   foreach my $cust_pkg_discount ( @cust_pkg_discount ) {
200      my $discount = $cust_pkg_discount->discount;
201      #UI enforces one or the other (for now?  probably for good)
202      my $amount = 0;
203      $amount += $discount->amount
204        if $cust_pkg->pkgpart == $param->{real_pkgpart};
205      $amount += sprintf('%.2f', $discount->percent * $br / 100 );
206
207      my $chg_months = $param->{'months'} || $cust_pkg->part_pkg->freq;
208      
209      my $months = $discount->months
210                     ? min( $chg_months,
211                            $discount->months - $cust_pkg_discount->months_used )
212                     : $chg_months;
213
214      my $error = $cust_pkg_discount->increment_months_used($months);
215      die "error discounting: $error" if $error;
216
217      $amount *= $months;
218      $amount = sprintf('%.2f', $amount);
219
220      next unless $amount > 0;
221
222      #record details in cust_bill_pkg_discount
223      my $cust_bill_pkg_discount = new FS::cust_bill_pkg_discount {
224        'pkgdiscountnum' => $cust_pkg_discount->pkgdiscountnum,
225        'amount'         => $amount,
226        'months'         => $months,
227      };
228      push @{ $param->{'discounts'} }, $cust_bill_pkg_discount;
229
230      #add details on discount to invoice
231      my $conf = new FS::Conf;
232      my $money_char = $conf->config('money_char') || '$';  
233      $months = sprintf('%.2f', $months) if $months =~ /\./;
234
235      my $d = 'Includes ';
236      $d .= $discount->name. ' ' if $discount->name;
237      $d .= 'discount of '. $discount->description_short;
238      $d .= " for $months month". ( $months!=1 ? 's' : '' );
239      $d .= ": $money_char$amount" if $months != 1 || $discount->percent;
240      push @$details, $d;
241
242      $tot_discount += $amount;
243   }
244
245   sprintf('%.2f', $tot_discount);
246 }
247
248 sub base_recur {
249   my($self, $cust_pkg) = @_;
250   $self->option('recur_fee', 1) || 0;
251 }
252
253 sub base_recur_permonth {
254   my($self, $cust_pkg) = @_;
255
256   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
257
258   sprintf('%.2f', $self->base_recur($cust_pkg) / $self->freq );
259 }
260
261 sub calc_remain {
262   my ($self, $cust_pkg, %options) = @_;
263
264   my $time;
265   if ($options{'time'}) {
266     $time = $options{'time'};
267   } else {
268     $time = time;
269   }
270
271   my $next_bill = $cust_pkg->getfield('bill') || 0;
272
273   #my $last_bill = $cust_pkg->last_bill || 0;
274   my $last_bill = $cust_pkg->get('last_bill') || 0; #->last_bill falls back to setup
275
276   return 0 if    ! $self->base_recur($cust_pkg)
277               || ! $self->option('unused_credit', 1)
278               || ! $last_bill
279               || ! $next_bill
280               || $next_bill < $time;
281
282   my %sec = (
283     'h' =>    3600, # 60 * 60
284     'd' =>   86400, # 60 * 60 * 24
285     'w' =>  604800, # 60 * 60 * 24 * 7
286     'm' => 2629744, # 60 * 60 * 24 * 365.2422 / 12 
287   );
288
289   $self->freq =~ /^(\d+)([hdwm]?)$/
290     or die 'unparsable frequency: '. $self->freq;
291   my $freq_sec = $1 * $sec{$2||'m'};
292   return 0 unless $freq_sec;
293
294   sprintf("%.2f", $self->base_recur($cust_pkg) * ( $next_bill - $time ) / $freq_sec );
295
296 }
297
298 sub is_free_options {
299   qw( setup_fee recur_fee );
300 }
301
302 sub is_prepaid { 0; } #no, we're postpaid
303
304 #XXX discounts only on recurring fees for now (no setup/one-time or usage)
305 sub can_discount {
306   my $self = shift;
307   $self->freq =~ /^\d+$/ && $self->freq > 0;
308 }
309
310 sub usage_valuehash {
311   my $self = shift;
312   map { $_, $self->option($_) }
313     grep { $self->option($_, 'hush') } 
314     qw(seconds upbytes downbytes totalbytes);
315 }
316
317 sub reset_usage {
318   my($self, $cust_pkg, %opt) = @_;
319   warn "   resetting usage counters" if defined($opt{debug}) && $opt{debug} > 1;
320   my %values = $self->usage_valuehash;
321   if ($self->option('usage_rollover', 1)) {
322     $cust_pkg->recharge(\%values);
323   }else{
324     $cust_pkg->set_usage(\%values, %opt);
325   }
326 }
327
328 1;