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