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