fix intro rates packages vs discounts, RT#83503
[freeside.git] / FS / FS / part_pkg / flat.pm
1 package FS::part_pkg::flat;
2 use base qw( FS::part_pkg::prorate_Mixin
3              FS::part_pkg::discount_Mixin
4              FS::part_pkg
5            );
6
7 use strict;
8 use vars qw( $conf $money_char %info
9              %usage_recharge_fields @usage_recharge_fieldorder
10            );
11 use FS::UID;
12 use FS::Record qw( qsearch );
13 use Tie::IxHash;
14 use List::Util qw( min );
15 use FS::UI::bytecount;
16 use FS::Conf;
17 use Time::Local 'timelocal';
18
19 #ask FS::UID to run this stuff for us later
20 FS::UID->install_callback( sub {
21   $conf = new FS::Conf;
22   $money_char = $conf->config('money_char') || '$';
23 });
24
25 tie my %temporalities, 'Tie::IxHash',
26   'upcoming'  => "Upcoming (future)",
27   'preceding' => "Preceding (past)",
28 ;
29
30 tie my %contract_years, 'Tie::IxHash', (
31   '' => '(none)',
32   map { $_*12 => $_ } (1..5),
33 );
34
35 %info = (
36   'name' => 'Flat rate (anniversary billing)',
37   'shortname' => 'Anniversary',
38   'inherit_fields' => [ 'prorate_Mixin', 'usage_Mixin', 'global_Mixin' ],
39   'fields' => {
40     #false laziness w/voip_cdr.pm
41     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
42                              'type' => 'select',
43                              'select_options' => \%temporalities,
44                            },
45
46     #used in cust_pkg.pm so could add to any price plan
47     'expire_months' => { 'name' => 'Auto-add an expiration date this number of months out',
48                        },
49     'adjourn_months'=> { 'name' => 'Auto-add a suspension date this number of months out',
50                        },
51     'contract_end_months'=> { 
52                         'name' => 'Auto-add a contract end date this number of years out',
53                         'type' => 'select',
54                         'select_options' => \%contract_years,
55                       },
56     #used in cust_pkg.pm so could add to any price plan where it made sense
57     'start_1st'     => { 'name' => 'Auto-add a start date to the 1st, ignoring the current month.',
58                          'type' => 'checkbox',
59                        },
60     'sync_bill_date' => { 'name' => 'Prorate first month to synchronize '.
61                                     'with the customer\'s other packages',
62                           'type' => 'checkbox',
63                         },
64     'prorate_defer_bill' => { 
65                           'name' => 'When synchronizing, defer the bill until '.
66                                     'the customer\'s next bill date',
67                           'type' => 'checkbox',
68                         },
69     'prorate_round_day' => {
70                           'name' => 'When synchronizing, round the prorated '.
71                                     'period',
72                           'type' => 'select',
73                           'select_options' => \%FS::part_pkg::prorate_Mixin::prorate_round_day_opts,
74                         },
75     'add_full_period' => { 'disabled' => 1 }, # doesn't make sense with sync?
76
77     'suspend_bill' => { 'name' => 'Continue recurring billing while suspended',
78                         'type' => 'checkbox',
79                       },
80     'unsuspend_adjust_bill' => 
81                         { 'name' => 'Adjust next bill date forward when '.
82                                     'unsuspending',
83                           'type' => 'checkbox',
84                         },
85     'bill_recur_on_cancel' => {
86                         'name' => 'Bill the last period on cancellation',
87                         'type' => 'checkbox',
88                         },
89     'bill_suspend_as_cancel' => {
90                         'name' => 'Bill immediately upon suspension', #desc?
91                         'type' => 'checkbox',
92                         },
93     'externalid' => { 'name'   => 'Optional External ID',
94                       'default' => '',
95                     },
96   },
97   'fieldorder' => [ qw( recur_temporality 
98                         expire_months adjourn_months
99                         contract_end_months
100                         start_1st
101                         sync_bill_date prorate_defer_bill prorate_round_day
102                         suspend_bill unsuspend_adjust_bill
103                         bill_recur_on_cancel
104                         bill_suspend_as_cancel
105                         externalid ),
106                   ],
107   'weight' => 10,
108 );
109
110 sub price_info {
111   my $self = shift;
112
113   my $setup = $self->option('setup_fee') || 0;
114   my $recur = $self->option('recur_fee', 1) || 0;
115
116   my $str = '';
117   $str = $money_char . $setup . ($recur ? ' setup ' : ' one-time') if $setup;
118   $str .= ', ' if ($setup && $recur);
119   $str .= $money_char. $recur. '/'. $self->freq_pretty if $recur;
120   $str;
121 }
122
123 sub calc_setup {
124   my($self, $cust_pkg, $time, $details, $param ) = @_;
125
126   return 0 if $self->prorate_setup($cust_pkg, $time);
127
128   my $i = 0;
129   my $count = $self->option( 'additional_count', 'quiet' ) || 0;
130   while ($i < $count) {
131     push @$details, $self->option( 'additional_info' . $i++ );
132   }
133
134   my $charge = $self->unit_setup($cust_pkg, $time, $details);
135
136   my $discount = 0;
137   if ( $charge > 0 ) {
138       $param->{'setup_charge'} = $charge;
139       $discount = $self->calc_discount($cust_pkg, \$time, $details, $param);
140       delete $param->{'setup_charge'};
141   }
142
143   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
144 }
145
146 sub unit_setup {
147   my($self, $cust_pkg, $time, $details ) = @_;
148   $self->option('setup_fee', 1) || 0;
149 }
150
151 sub calc_recur {
152   my $self = shift;
153   my($cust_pkg, $sdate, $details, $param ) = @_;
154
155   #my $last_bill = $cust_pkg->last_bill;
156   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
157
158   return 0
159     if $self->recur_temporality eq 'preceding' && !$last_bill;
160
161   my $charge = $self->base_recur($cust_pkg, $sdate);
162   # always treat cutoff_day as a list
163   if ( my @cutoff_day = $self->cutoff_day($cust_pkg) ) {
164     $charge = $self->calc_prorate(@_, @cutoff_day);
165   }
166   elsif ( $param->{freq_override} ) {
167     # XXX not sure if this should be mutually exclusive with sync_bill_date.
168     # Given the very specific problem that freq_override is meant to 'solve',
169     # it probably should.
170     $charge *= $param->{freq_override} if $param->{freq_override};
171   }
172
173   my $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
174
175   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
176 }
177
178 sub cutoff_day {
179   my $self = shift;
180   my $cust_pkg = shift;
181   my $cust_main = $cust_pkg->cust_main;
182   # force it to act like a prorate package, is what this means
183   # because we made a distinction once between prorate and flat packages
184   if ( $cust_main->force_prorate_day  and $cust_main->prorate_day ) {
185      return ( $cust_main->prorate_day );
186   }
187   if ( $self->option('sync_bill_date',1) ) {
188     my $next_bill = $cust_pkg->cust_main->next_bill_date;
189     if ( $next_bill ) {
190       return (localtime($next_bill))[3];
191     } else {
192       # This is the customer's only active package and hasn't been billed
193       # yet, so set the cutoff day to either today or tomorrow, whichever
194       # would result in a full period after rounding.
195       my $setup = $cust_pkg->setup; # because it's "now"
196       my $rounding_mode = $self->option('prorate_round_day',1);
197       return () if !$setup or !$rounding_mode;
198       my ($sec, $min, $hour, $mday, $mon, $year) = localtime($setup);
199
200       if (   ( $rounding_mode == 1 and $hour >= 12 )
201           or ( $rounding_mode == 3 and ( $sec > 0 or $min > 0 or $hour > 0 ))
202       ) {
203         # then the prorate period will be rounded down to start from
204         # midnight tomorrow, so the cutoff day should be the current day +
205         # 1.
206         $setup = timelocal(59,59,23,$mday,$mon,$year) + 1;
207         $mday = (localtime($setup))[3];
208       }
209       # otherwise, it will be rounded up, so leave the cutoff day at today.
210       return $mday;
211     }
212   }
213   return ();
214 }
215
216 sub base_recur {
217   my($self, $cust_pkg, $sdate) = @_;
218   $self->option('recur_fee', 1) || 0;
219 }
220
221 sub base_recur_permonth {
222   my($self, $cust_pkg) = @_;
223
224   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
225
226   sprintf('%.2f', $self->base_recur($cust_pkg) / $self->freq );
227 }
228
229 sub calc_cancel {
230   my $self = shift;
231   if ( $self->recur_temporality eq 'preceding'
232        and $self->option('bill_recur_on_cancel', 1) ) {
233     # run another recurring cycle
234     return $self->calc_recur(@_);
235   } elsif ( $conf->exists('bill_usage_on_cancel') # should be a package option?
236           and $self->can('calc_usage') ) {
237     # bill for outstanding usage
238     return $self->calc_usage(@_);
239   } else {
240     return 'NOTHING'; # numerically zero, but has special meaning
241   }
242 }
243
244 sub calc_remain {
245   my ($self, $cust_pkg, %options) = @_;
246
247   my $time;
248   if ($options{'time'}) {
249     $time = $options{'time'};
250   } else {
251     $time = time;
252   }
253
254   my $next_bill = $cust_pkg->getfield('bill') || 0;
255
256   return 0 if    ! $self->base_recur($cust_pkg, \$time)
257               || ! $next_bill
258               || $next_bill < $time;
259
260   # Use actual charge for this period, not base_recur (for discounts).
261   # Use sdate < $time and edate >= $time because when billing on 
262   # cancellation, edate = $time.
263   my $credit = 0;
264   foreach my $cust_bill_pkg ( 
265     qsearch('cust_bill_pkg', { 
266       pkgnum => $cust_pkg->pkgnum,
267       edate => {op => '>=', value => $time},
268       recur => {op => '>' , value => 0},
269     })
270   ) {
271     # hack to deal with the weird behavior of edate on package cancellation
272     my $edate = $cust_bill_pkg->edate;
273     if ( $self->recur_temporality eq 'preceding' ) {
274       $edate = $self->add_freq($cust_bill_pkg->sdate);
275     }
276
277     # this will also get any package charges that are _entirely_ after the
278     # cancellation date (can happen with advance billing). in that case,
279     # use the entire recurring charge:
280     my $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
281
282     # but if the cancellation happens during the interval, prorate it:
283     # (XXX obey prorate_round_day here?)
284     if ( $cust_bill_pkg->sdate < $time ) {
285       $amount = $amount * ($edate - $time) / ($edate - $cust_bill_pkg->sdate);
286     }
287
288     $credit += $amount;
289   } 
290   sprintf('%.2f', $credit);
291
292 }
293
294 sub is_free_options {
295   qw( setup_fee recur_fee );
296 }
297
298 sub is_prepaid { 0; } #no, we're postpaid
299
300 sub can_start_date {
301   my $self = shift;
302   my %opt = @_;
303   return 0 if $self->start_on_hold;
304
305   ! $self->option('start_1st', 1) && (   ! $self->option('sync_bill_date',1)
306                                       || ! $self->option('prorate_defer_bill',1)
307                                       || ! $opt{'num_ncancelled_pkgs'}
308                                      ); 
309 }
310
311 sub can_discount { 1; }
312
313 sub recur_temporality {
314   my $self = shift;
315   $self->option('recur_temporality', 1);
316 }
317
318 sub usage_valuehash {
319   my $self = shift;
320   map { $_, $self->option($_) }
321     grep { $self->option($_, 'hush') } 
322     qw(seconds upbytes downbytes totalbytes);
323 }
324
325 sub reset_usage {
326   my($self, $cust_pkg, %opt) = @_;
327   warn "   resetting usage counters" if defined($opt{debug}) && $opt{debug} > 1;
328   my %values = $self->usage_valuehash;
329   if ($self->option('usage_rollover', 1)) {
330     $cust_pkg->recharge(\%values);
331   }else{
332     $cust_pkg->set_usage(\%values, %opt);
333   }
334 }
335
336 1;