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     'bill_recur_on_cancel' => {
75                         'name' => 'Bill the last period on cancellation',
76                         'type' => 'checkbox',
77                         },
78     'bill_suspend_as_cancel' => {
79                         'name' => 'Bill immediately upon suspension', #desc?
80                         'type' => 'checkbox',
81                         },
82     'externalid' => { 'name'   => 'Optional External ID',
83                       'default' => '',
84                     },
85   },
86   'fieldorder' => [ qw( recur_temporality 
87                         expire_months adjourn_months
88                         contract_end_months
89                         start_1st
90                         sync_bill_date prorate_defer_bill prorate_round_day
91                         suspend_bill unsuspend_adjust_bill
92                         bill_recur_on_cancel
93                         bill_suspend_as_cancel
94                         externalid ),
95                   ],
96   'weight' => 10,
97 );
98
99 sub price_info {
100     my $self = shift;
101     my %opt = @_;
102     my $conf = new FS::Conf;
103     my $money_char = $conf->config('money_char') || '$';
104     my $setup = $opt{cust_pkg} ? $self->base_setup( $opt{cust_pkg} )
105                                : ($self->option('setup_fee') || 0);
106     my $recur = $opt{cust_pkg} ? $self->base_recur( $opt{cust_pkg} )
107                                : ($self->option('recur_fee', 1) || 0);
108     $recur += $self->usageprice_recur( $opt{cust_pkg} ) if $opt{cust_pkg};
109     my $str = '';
110     $str = $money_char . $setup . ($recur ? ' setup' : ' one-time') if $setup;
111     $str .= ', ' if ($setup && $recur);
112     $str .= $money_char. $recur. '/'. $self->freq_pretty if $recur;
113     $str;
114 }
115
116 sub calc_setup {
117   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
118
119   return 0 if $self->prorate_setup($cust_pkg, $sdate);
120
121   my $i = 0;
122   my $count = $self->option( 'additional_count', 'quiet' ) || 0;
123   while ($i < $count) {
124     push @$details, $self->option( 'additional_info' . $i++ );
125   }
126
127   my $charge = $self->base_setup($cust_pkg, $sdate, $details);
128
129   my $discount = 0;
130   if ( $charge > 0 ) {
131       $param->{'setup_charge'} = $charge;
132       $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
133       delete $param->{'setup_charge'};
134   }
135
136   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
137 }
138
139 sub base_setup {
140   my($self, $cust_pkg, $sdate, $details ) = @_;
141
142   $self->option('setup_fee') || 0;
143 }
144
145 sub calc_recur {
146   my $self = shift;
147   my($cust_pkg, $sdate, $details, $param ) = @_;
148
149   #my $last_bill = $cust_pkg->last_bill;
150   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
151
152   return 0
153     if $self->recur_temporality eq 'preceding' && !$last_bill;
154
155   my $charge = $self->base_recur($cust_pkg, $sdate);
156   # always treat cutoff_day as a list
157   if ( my @cutoff_day = $self->cutoff_day($cust_pkg) ) {
158     $charge = $self->calc_prorate(@_, @cutoff_day);
159   }
160   elsif ( $param->{freq_override} ) {
161     # XXX not sure if this should be mutually exclusive with sync_bill_date.
162     # Given the very specific problem that freq_override is meant to 'solve',
163     # it probably should.
164     $charge *= $param->{freq_override} if $param->{freq_override};
165   }
166
167   $charge += $self->usageprice_recur($cust_pkg, $sdate);
168   $cust_pkg->apply_usageprice(); #$sdate for prorating?
169
170   my $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
171
172   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
173 }
174
175 sub cutoff_day {
176   my $self = shift;
177   my $cust_pkg = shift;
178   if ( $self->option('sync_bill_date',1) ) {
179     my $next_bill = $cust_pkg->cust_main->next_bill_date;
180     if ( defined($next_bill) ) {
181       return (localtime($next_bill))[3];
182     }
183   }
184   return ();
185 }
186
187 sub base_recur {
188   my($self, $cust_pkg, $sdate) = @_;
189   $self->option('recur_fee', 1) || 0;
190 }
191
192 sub base_recur_permonth {
193   my($self, $cust_pkg) = @_;
194
195   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
196
197   sprintf('%.2f', $self->base_recur($cust_pkg) / $self->freq );
198 }
199
200 sub usageprice_recur {
201   my($self, $cust_pkg, $sdate) = @_;
202
203   my $recur = 0;
204   $recur += $_->price foreach $cust_pkg->cust_pkg_usageprice;
205
206   sprintf('%.2f', $recur);
207 }
208
209 sub calc_cancel {
210   my $self = shift;
211   my $conf = new FS::Conf;
212   if ( $self->recur_temporality eq 'preceding'
213        and $self->option('bill_recur_on_cancel', 1) ) {
214     # run another recurring cycle
215     return $self->calc_recur(@_);
216   }
217   elsif ( $conf->exists('bill_usage_on_cancel') # should be a package option?
218           and $self->can('calc_usage') ) {
219     # bill for outstanding usage
220     return $self->calc_usage(@_);
221   }
222   0;
223 }
224
225 sub calc_remain {
226   my ($self, $cust_pkg, %options) = @_;
227
228   my $time;
229   if ($options{'time'}) {
230     $time = $options{'time'};
231   } else {
232     $time = time;
233   }
234
235   my $next_bill = $cust_pkg->getfield('bill') || 0;
236
237   return 0 if    ! $self->base_recur($cust_pkg, \$time)
238               || ! $next_bill
239               || $next_bill < $time;
240
241   # Use actual charge for this period, not base_recur (for discounts).
242   # Use sdate < $time and edate >= $time because when billing on 
243   # cancellation, edate = $time.
244   my $credit = 0;
245   foreach my $item ( 
246     qsearch('cust_bill_pkg', { 
247       pkgnum => $cust_pkg->pkgnum,
248       sdate => {op => '<' , value => $time},
249       edate => {op => '>=', value => $time},
250       recur => {op => '>' , value => 0},
251     })
252   ) {
253     # hack to deal with the weird behavior of edate on package cancellation
254     my $edate = $item->edate;
255     if ( $self->recur_temporality eq 'preceding' ) {
256       $edate = $self->add_freq($item->sdate);
257     }
258     $credit += ($item->recur - $item->usage) * 
259                ($edate - $time) / ($edate - $item->sdate);
260   } 
261   sprintf('%.2f', $credit);
262   #sprintf("%.2f", $self->base_recur($cust_pkg, \$time) * ( $next_bill - $time ) / $freq_sec );
263
264 }
265
266 sub is_free_options {
267   qw( setup_fee recur_fee );
268 }
269
270 sub is_prepaid { 0; } #no, we're postpaid
271
272 sub can_start_date {
273   my $self = shift;
274   my %opt = @_;
275
276   ! $self->option('start_1st', 1) && (   ! $self->option('sync_bill_date',1)
277                                       || ! $self->option('prorate_defer_bill',1)
278                                       || ! $opt{'num_ncancelled_pkgs'}
279                                      ); 
280 }
281
282 sub can_discount { 1; }
283
284 sub can_usageprice { 1; }
285
286 sub recur_temporality {
287   my $self = shift;
288   $self->option('recur_temporality', 1);
289 }
290
291 sub usage_valuehash {
292   my $self = shift;
293   map { $_, $self->option($_) }
294     grep { $self->option($_, 'hush') } 
295     qw(seconds upbytes downbytes totalbytes);
296 }
297
298 sub reset_usage {
299   my($self, $cust_pkg, %opt) = @_;
300   warn "   resetting usage counters" if defined($opt{debug}) && $opt{debug} > 1;
301   my %values = $self->usage_valuehash;
302   if ($self->option('usage_rollover', 1)) {
303     $cust_pkg->recharge(\%values);
304   }else{
305     $cust_pkg->set_usage(\%values, %opt);
306   }
307 }
308
309 1;