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