a89b54d2cd506470803dca1914337f13807e19af
[freeside.git] / FS / FS / part_pkg / prorate_Mixin.pm
1 package FS::part_pkg::prorate_Mixin;
2
3 use strict;
4 use vars qw( %info );
5 use Tie::IxHash;
6 use Time::Local qw( timelocal timelocal_nocheck );
7 use Date::Format qw( time2str );
8 use List::Util qw( min );
9
10 tie our %prorate_round_day_opts, 'Tie::IxHash',
11   0   => 'no',
12   1   => 'to the nearest day',
13   2   => 'up to a full day',
14   3   => 'down to a full day',
15 ;
16
17 %info = ( 
18   'disabled'  => 1,
19   # define all fields that are referenced in this code
20   'fields' => {
21     'add_full_period' => { 
22                 'name' => 'When prorating first month, also bill for one full '.
23                           'period after that',
24                 'type' => 'checkbox',
25     },
26     'prorate_round_day' => { 
27                 'name' => 'When prorating, round the prorated period',
28                 'type' => 'select',
29                 'select_options' => \%prorate_round_day_opts,
30     },
31     'prorate_defer_bill' => {
32                 'name' => 'When prorating, defer the first bill until the '.
33                           'billing day',
34                 'type' => 'checkbox',
35     },
36     'prorate_verbose' => {
37                 'name' => 'Show prorate details on the invoice',
38                 'type' => 'checkbox',
39     },
40   },
41   'fieldorder' => [ qw(prorate_defer_bill prorate_round_day 
42                        add_full_period prorate_verbose) ],
43 );
44
45 sub fieldorder {
46   @{ $info{'fieldorder'} }
47 }
48
49 =head1 NAME
50
51 FS::part_pkg::prorate_Mixin - Mixin class for part_pkg:: classes that 
52 need to prorate partial months
53
54 =head1 SYNOPSIS
55
56 package FS::part_pkg::...;
57 use base qw( FS::part_pkg::prorate_Mixin );
58
59 sub calc_recur {
60   ...
61   if( conditions that trigger prorate ) {
62     # sets $$sdate and $param->{'months'}, returns the prorated charge
63     $charges = $self->calc_prorate($cust_pkg, $sdate, $param, $cutoff_day);
64   } 
65   ...
66 }
67
68 =head METHODS
69
70 =item calc_prorate CUST_PKG SDATE DETAILS PARAM CUTOFF_DAY
71
72 Takes all the arguments of calc_recur.  Calculates a prorated charge from 
73 the $sdate to the cutoff day for this package definition, and sets the $sdate 
74 and $param->{months} accordingly.  base_recur() will be called to determine 
75 the base price per billing cycle.
76
77 Options:
78 - add_full_period: Bill for the time up to the prorate day plus one full
79   billing period after that.
80 - prorate_round_day: Round the current time to the nearest full day, 
81   instead of using the exact time.
82 - prorate_defer_bill: Don't bill the prorate interval until the prorate 
83   day arrives.
84 - prorate_verbose: Generate details to explain the prorate calculations.
85
86 =cut
87
88 sub calc_prorate {
89   my ($self, $cust_pkg, $sdate, $details, $param, @cutoff_days) = @_;
90   die "no cutoff_day" unless @cutoff_days;
91   die "can't prorate non-monthly package\n" if $self->freq =~ /\D/;
92
93   my $money_char = FS::Conf->new->config('money_char') || '$';
94
95   my $charge = $self->base_recur($cust_pkg, $sdate) || 0;
96
97   my $add_period = $self->option('add_full_period',1);
98
99   my $mnow = $$sdate;
100
101   # if this is the first bill but the bill date has been set
102   # (by prorate_defer_bill), calculate from the setup date,
103   # append the setup fee to @$details, and make sure to bill for 
104   # a full period after the bill date.
105   if ( $self->option('prorate_defer_bill',1)
106          && ! $cust_pkg->getfield('last_bill') 
107          && $cust_pkg->setup
108      )
109   {
110     #warn "[calc_prorate] #".$cust_pkg->pkgnum.": running deferred setup\n";
111     $param->{'setup_fee'} = $self->calc_setup($cust_pkg, $$sdate, $details);
112     $mnow = $cust_pkg->setup;
113     $add_period = 1;
114   }
115
116   # if the customer already has a billing day-of-month established,
117   # and it's a valid cutoff day, try to respect it
118   my $next_bill_day;
119   if ( my $next_bill = $cust_pkg->cust_main->next_bill_date ) {
120     $next_bill_day = (localtime($next_bill))[3];
121     if ( grep {$_ == $next_bill_day} @cutoff_days ) {
122       # by removing all other cutoff days from the list
123       @cutoff_days = ($next_bill_day);
124     }
125   }
126
127   my ($mend, $mstart);
128   ($mnow, $mend, $mstart) = $self->_endpoints($mnow, @cutoff_days);
129
130   # next bill date will be figured as $$sdate + one period
131   $$sdate = $mstart;
132
133   my $permonth = $charge / $self->freq;
134   my $months = ( ( $self->freq - 1 ) + ($mend-$mnow) / ($mend-$mstart) );
135   # after this, $self->freq - 1 < $months <= $self->freq
136
137   # add a full period if currently billing for a partial period
138   # or periods up to freq_override if billing for an override interval
139   if ( ($param->{'freq_override'} || 0) > 1 ) {
140     $months += $param->{'freq_override'} - 1;
141     # freq_override - 1 correct here?
142     # (probably only if freq == 1, yes?)
143   } elsif ( $add_period && $months < $self->freq ) {
144
145     # 'add_period' is a misnomer.
146     # we add enough to make the total at least a full period
147     $months++;
148     $$sdate = $self->add_freq($mstart, 1);
149     # now $self->freq <= $months <= $self->freq + 1
150     # (note that this only happens if $months < $self->freq to begin with)
151
152   }
153
154   if ( $self->option('prorate_verbose',1) and $months > 0 ) {
155     if ( $months < $self->freq ) {
156       # we are billing a fractional period only
157       #       # (though maybe not a fractional month)
158       my $period_end = $self->add_freq($mstart);
159       push @$details, 
160       'Prorated (' . time2str('%b %d', $mnow) .
161       ' - ' . time2str('%b %d', $period_end) . '): ' . $money_char .
162       sprintf('%.2f', $permonth * $months + 0.00000001 );
163
164     } elsif ( $months > $self->freq ) {
165       # we are billing MORE than a full period
166       push @$details,
167
168       'Prorated (' . time2str('%b %d', $mnow) .
169       ' - ' . time2str('%b %d', $mend) . '): ' . $money_char .
170       sprintf('%.2f', $permonth * ($months - $self->freq + 0.0000001)),
171
172       'First full period: ' . $money_char .
173       sprintf('%.2f', $permonth * $self->freq);
174     } # else $months == $self->freq, and no prorating has happened
175   }
176
177   $param->{'months'} = $months;
178                                                   #so 1.005 rounds to 1.01
179   $charge = sprintf('%.2f', $permonth * $months + 0.00000001 );
180
181   return sprintf('%.2f', $charge);
182 }
183
184 =item prorate_setup CUST_PKG SDATE
185
186 Set up the package.  This only has an effect if prorate_defer_bill is 
187 set, in which case it postpones the next bill to the cutoff day.
188
189 =cut
190
191 sub prorate_setup {
192   my $self = shift;
193   my ($cust_pkg, $sdate) = @_;
194   my @cutoff_days = $self->cutoff_day($cust_pkg);
195   if ( @cutoff_days and $self->option('prorate_defer_bill', 1) ) {
196     if ( $cust_pkg->setup ) {
197       # Setup date is already set. Then we're being called indirectly via calc_prorate
198       # to calculate the deferred setup fee. Allow that to happen normally.
199       return 0;
200     } else {
201       # We're going to set the setup date (so that the deferred billing knows when
202       # the package started) and suppress charging the setup fee.
203       if ( $cust_pkg->bill ) {
204         # For some reason (probably user override), the bill date has been set even
205         # though the package isn't billing yet. Start billing as though that was the
206         # start date.
207         $sdate = $cust_pkg->bill;
208         $cust_pkg->setup($cust_pkg->bill);
209       }
210       # Now figure the start and end of the period that contains the start date.
211       my ($mnow, $mend, $mstart) = $self->_endpoints($sdate, @cutoff_days);
212       # If today is the cutoff day, set the next bill and setup both to 
213       # midnight today, so that the customer will be billed normally for a 
214       # month starting today.
215       if ( $mnow - $mstart < 86400 ) {
216         $cust_pkg->setup($mstart);
217         $cust_pkg->bill($mstart);
218       }
219       else {
220         $cust_pkg->bill($mend);
221       }
222       return 1;
223     }
224   }
225   return 0;
226 }
227
228 =item _endpoints TIME CUTOFF_DAY
229
230 Given a current time and a day of the month to prorate to, return three 
231 times: the start of the prorate interval (usually the current time), the
232 end of the prorate interval (i.e. the cutoff date), and the time one month 
233 before the end of the prorate interval.
234
235 =cut
236
237 sub _endpoints {
238   my $self = shift;
239   my $mnow = shift;
240   my @cutoff_days = sort {$a <=> $b} @_;
241
242   # only works for freq >= 1 month; probably can't be fixed
243   my ($sec, $min, $hour, $mday, $mon, $year) = (localtime($mnow))[0..5];
244   my $rounding_mode = $self->option('prorate_round_day',1);
245   if ( $rounding_mode == 1 ) {
246     # If the time is 12:00-23:59, move to the next day by adding 18 
247     # hours to $mnow.  Because of DST this can end up from 05:00 to 18:59
248     # but it's always within the next day.
249     $mnow += 64800 if $hour >= 12;
250     # Get the new day, month, and year.
251     ($mday,$mon,$year) = (localtime($mnow))[3..5];
252     # Then set $mnow to midnight on that day.
253     $mnow = timelocal(0,0,0,$mday,$mon,$year);
254   } elsif ( $rounding_mode == 2 ) {
255     # Move the time back to midnight. This increases the length of the
256     # prorate interval.
257     $mnow = timelocal(0,0,0,$mday,$mon,$year);
258     ($mday,$mon,$year) = (localtime($mnow))[3..5];
259   } elsif ( $rounding_mode == 3 ) {
260     # If the time is after midnight, move it forward to the next midnight.
261     # This decreases the length of the prorate interval.
262     if ( $sec > 0 or $min > 0 or $hour > 0 ) {
263       # move to one second before midnight, then tick forward
264       $mnow = timelocal(59,59,23,$mday,$mon,$year) + 1;
265       ($mday,$mon,$year) = (localtime($mnow))[3..5];
266     }
267   }
268   my $mend;
269   my $mstart;
270   # select the first cutoff day that's on or after the current day
271   my $cutoff_day = min( grep { $_ >= $mday } @cutoff_days );
272   # if today is after the last cutoff, choose the first one
273   $cutoff_day ||= $cutoff_days[0];
274
275   # then, if today is on or after the selected day, set period to
276   # (cutoff day this month) - (cutoff day next month)
277   if ( $mday >= $cutoff_day ) {
278     $mend = 
279       timelocal_nocheck(0,0,0,$cutoff_day,$mon == 11 ? 0 : $mon + 1,$year+($mon==11));
280     $mstart =
281       timelocal_nocheck(0,0,0,$cutoff_day,$mon,$year);
282   }
283   # otherwise, set period to (cutoff day last month) - (cutoff day this month)
284   else {
285     $mend = 
286       timelocal_nocheck(0,0,0,$cutoff_day,$mon,$year);
287     $mstart = 
288       timelocal_nocheck(0,0,0,$cutoff_day,$mon == 0 ? 11 : $mon - 1,$year-($mon==0));
289   }
290   return ($mnow, $mend, $mstart);
291 }
292
293 1;