fix sync_bill_date near the end of the month, RT#10503
[freeside.git] / FS / FS / part_pkg / flat.pm
1 package FS::part_pkg::flat;
2
3 use strict;
4 use vars qw( @ISA %info
5              %usage_fields %usage_recharge_fields
6              @usage_fieldorder @usage_recharge_fieldorder
7            );
8 use Tie::IxHash;
9 use List::Util qw(min); # max);
10 #use FS::Record qw(qsearch);
11 use FS::UI::bytecount;
12 use FS::Conf;
13 use FS::part_pkg;
14
15 @ISA = qw(FS::part_pkg 
16           FS::part_pkg::prorate_Mixin
17           FS::part_pkg::discount_Mixin);
18
19 tie my %temporalities, 'Tie::IxHash',
20   'upcoming'  => "Upcoming (future)",
21   'preceding' => "Preceding (past)",
22 ;
23
24 tie my %contract_years, 'Tie::IxHash', (
25   '' => '(none)',
26   map { $_*12 => $_ } (1..5),
27 );
28
29 %usage_fields = (
30
31     'seconds'       => { 'name' => 'Time limit for this package',
32                          'default' => '',
33                          'check' => sub { shift =~ /^\d*$/ },
34                        },
35     'upbytes'       => { 'name' => 'Upload limit for this package',
36                          'default' => '',
37                          'check' => sub { shift =~ /^\d*$/ },
38                          'format' => \&FS::UI::bytecount::display_bytecount,
39                          'parse' => \&FS::UI::bytecount::parse_bytecount,
40                        },
41     'downbytes'     => { 'name' => 'Download limit for this package',
42                          'default' => '',
43                          'check' => sub { shift =~ /^\d*$/ },
44                          'format' => \&FS::UI::bytecount::display_bytecount,
45                          'parse' => \&FS::UI::bytecount::parse_bytecount,
46                        },
47     'totalbytes'    => { 'name' => 'Transfer limit for this package',
48                          'default' => '',
49                          'check' => sub { shift =~ /^\d*$/ },
50                          'format' => \&FS::UI::bytecount::display_bytecount,
51                          'parse' => \&FS::UI::bytecount::parse_bytecount,
52                        },
53 );
54
55 %usage_recharge_fields = (
56
57     'recharge_amount'       => { 'name' => 'Cost of recharge for this package',
58                          'default' => '',
59                          'check' => sub { shift =~ /^\d*(\.\d{2})?$/ },
60                        },
61     'recharge_seconds'      => { 'name' => 'Recharge time for this package',
62                          'default' => '',
63                          'check' => sub { shift =~ /^\d*$/ },
64                        },
65     'recharge_upbytes'      => { 'name' => 'Recharge upload for this package',
66                          'default' => '',
67                          'check' => sub { shift =~ /^\d*$/ },
68                          'format' => \&FS::UI::bytecount::display_bytecount,
69                          'parse' => \&FS::UI::bytecount::parse_bytecount,
70                        },
71     'recharge_downbytes'    => { 'name' => 'Recharge download for this package',
72                          'default' => '',
73                          'check' => sub { shift =~ /^\d*$/ },
74                          'format' => \&FS::UI::bytecount::display_bytecount,
75                          'parse' => \&FS::UI::bytecount::parse_bytecount,
76                        },
77     'recharge_totalbytes'   => { 'name' => 'Recharge transfer for this package',
78                          'default' => '',
79                          'check' => sub { shift =~ /^\d*$/ },
80                          'format' => \&FS::UI::bytecount::display_bytecount,
81                          'parse' => \&FS::UI::bytecount::parse_bytecount,
82                        },
83     'usage_rollover' => { 'name' => 'Allow usage from previous period to roll '.
84                                     ' over into current period',
85                           'type' => 'checkbox',
86                         },
87     'recharge_reset' => { 'name' => 'Reset usage to these values on manual '.
88                                     'package recharge',
89                           'type' => 'checkbox',
90                         },
91 );
92
93 @usage_fieldorder = qw( seconds upbytes downbytes totalbytes );
94 @usage_recharge_fieldorder = qw(
95   recharge_amount recharge_seconds recharge_upbytes
96   recharge_downbytes recharge_totalbytes
97   usage_rollover recharge_reset
98 );
99
100 %info = (
101   'name' => 'Flat rate (anniversary billing)',
102   'shortname' => 'Anniversary',
103   'fields' => {
104     'setup_fee'     => { 'name' => 'Setup fee for this package',
105                          'default' => 0,
106                        },
107     'recur_fee'     => { 'name' => 'Recurring fee for this package',
108                          'default' => 0,
109                        },
110
111     #false laziness w/voip_cdr.pm
112     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
113                              'type' => 'select',
114                              'select_options' => \%temporalities,
115                            },
116     'unused_credit' => { 'name' => 'Credit the customer for the unused portion'.
117                                    ' of service at cancellation',
118                          'type' => 'checkbox',
119                        },
120
121     #used in cust_pkg.pm so could add to any price plan
122     'expire_months' => { 'name' => 'Auto-add an expiration date this number of months out',
123                        },
124     'adjourn_months'=> { 'name' => 'Auto-add a suspension date this number of months out',
125                        },
126     'contract_end_months'=> { 
127                         'name' => 'Auto-add a contract end date this number of years out',
128                         'type' => 'select',
129                         'select_options' => \%contract_years,
130                       },
131     #used in cust_pkg.pm so could add to any price plan where it made sense
132     'start_1st'     => { 'name' => 'Auto-add a start date to the 1st, ignoring the current month.',
133                          'type' => 'checkbox',
134                        },
135     'sync_bill_date' => { 'name' => 'Prorate first month to synchronize '.
136                                     'with the customer\'s other packages',
137                           'type' => 'checkbox',
138                         },
139     'suspend_bill' => { 'name' => 'Continue recurring billing while suspended',
140                         'type' => 'checkbox',
141                       },
142     'unsuspend_adjust_bill' => 
143                         { 'name' => 'Adjust next bill date forward when '.
144                                     'unsuspending',
145                           'type' => 'checkbox',
146                         },
147
148     %usage_fields,
149     %usage_recharge_fields,
150
151     'externalid' => { 'name'   => 'Optional External ID',
152                       'default' => '',
153                     },
154   },
155   'fieldorder' => [ qw( setup_fee recur_fee
156                         recur_temporality unused_credit
157                         expire_months adjourn_months
158                         contract_end_months
159                         start_1st sync_bill_date
160                         suspend_bill unsuspend_adjust_bill
161                       ),
162                     @usage_fieldorder, @usage_recharge_fieldorder,
163                     qw( externalid ),
164                   ],
165   'weight' => 10,
166 );
167
168 sub calc_setup {
169   my($self, $cust_pkg, $sdate, $details ) = @_;
170
171   my $i = 0;
172   my $count = $self->option( 'additional_count', 'quiet' ) || 0;
173   while ($i < $count) {
174     push @$details, $self->option( 'additional_info' . $i++ );
175   }
176
177   my $quantity = $cust_pkg->quantity || 1;
178
179   sprintf("%.2f", $quantity * $self->unit_setup($cust_pkg, $sdate, $details) );
180 }
181
182 sub unit_setup {
183   my($self, $cust_pkg, $sdate, $details ) = @_;
184
185   $self->option('setup_fee') || 0;
186 }
187
188 sub calc_recur {
189   my $self = shift;
190   my($cust_pkg, $sdate, $details, $param ) = @_;
191
192   #my $last_bill = $cust_pkg->last_bill;
193   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
194
195   return 0
196     if $self->option('recur_temporality', 1) eq 'preceding' && $last_bill == 0;
197
198   my $charge = $self->base_recur($cust_pkg);
199   if ( $self->option('sync_bill_date',1) ) {
200     my $next_bill = $cust_pkg->cust_main->next_bill_date;
201     if ( defined($next_bill) ) {
202       my $cutoff_day = (localtime($next_bill))[3];
203       $charge = $self->calc_prorate(@_, $cutoff_day);
204     }
205   }
206   elsif ( $param->{freq_override} ) {
207     # XXX not sure if this should be mutually exclusive with sync_bill_date.
208     # Given the very specific problem that freq_override is meant to 'solve',
209     # it probably should.
210     $charge *= $param->{freq_override} if $param->{freq_override};
211   }
212
213   my $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
214   return sprintf('%.2f', $charge - $discount);
215 }
216
217 sub base_recur {
218   my($self, $cust_pkg) = @_;
219   $self->option('recur_fee', 1) || 0;
220 }
221
222 sub base_recur_permonth {
223   my($self, $cust_pkg) = @_;
224
225   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
226
227   sprintf('%.2f', $self->base_recur($cust_pkg) / $self->freq );
228 }
229
230 sub calc_remain {
231   my ($self, $cust_pkg, %options) = @_;
232
233   my $time;
234   if ($options{'time'}) {
235     $time = $options{'time'};
236   } else {
237     $time = time;
238   }
239
240   my $next_bill = $cust_pkg->getfield('bill') || 0;
241
242   #my $last_bill = $cust_pkg->last_bill || 0;
243   my $last_bill = $cust_pkg->get('last_bill') || 0; #->last_bill falls back to setup
244
245   return 0 if    ! $self->base_recur($cust_pkg)
246               || ! $self->option('unused_credit', 1)
247               || ! $last_bill
248               || ! $next_bill
249               || $next_bill < $time;
250
251   my %sec = (
252     'h' =>    3600, # 60 * 60
253     'd' =>   86400, # 60 * 60 * 24
254     'w' =>  604800, # 60 * 60 * 24 * 7
255     'm' => 2629744, # 60 * 60 * 24 * 365.2422 / 12 
256   );
257
258   $self->freq =~ /^(\d+)([hdwm]?)$/
259     or die 'unparsable frequency: '. $self->freq;
260   my $freq_sec = $1 * $sec{$2||'m'};
261   return 0 unless $freq_sec;
262
263   sprintf("%.2f", $self->base_recur($cust_pkg) * ( $next_bill - $time ) / $freq_sec );
264
265 }
266
267 sub is_free_options {
268   qw( setup_fee recur_fee );
269 }
270
271 sub is_prepaid { 0; } #no, we're postpaid
272
273 #XXX discounts only on recurring fees for now (no setup/one-time or usage)
274 sub can_discount {
275   my $self = shift;
276   $self->freq =~ /^\d+$/ && $self->freq > 0;
277 }
278
279 sub usage_valuehash {
280   my $self = shift;
281   map { $_, $self->option($_) }
282     grep { $self->option($_, 'hush') } 
283     qw(seconds upbytes downbytes totalbytes);
284 }
285
286 sub reset_usage {
287   my($self, $cust_pkg, %opt) = @_;
288   warn "   resetting usage counters" if defined($opt{debug}) && $opt{debug} > 1;
289   my %values = $self->usage_valuehash;
290   if ($self->option('usage_rollover', 1)) {
291     $cust_pkg->recharge(\%values);
292   }else{
293     $cust_pkg->set_usage(\%values, %opt);
294   }
295 }
296
297 1;