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