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