3e63242ae100557367d0bf5726848704e1872e2c
[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 FS::cust_credit_source_bill_pkg;
14 use Tie::IxHash;
15 use List::Util qw( min );
16 use FS::UI::bytecount;
17 use FS::Conf;
18
19 #ask FS::UID to run this stuff for us later
20 FS::UID->install_callback( sub {
21   $conf = new FS::Conf;
22   $money_char = $conf->config('money_char') || '$';
23 });
24
25 tie my %temporalities, 'Tie::IxHash',
26   'upcoming'  => "Upcoming (future)",
27   'preceding' => "Preceding (past)",
28 ;
29
30 tie my %contract_years, 'Tie::IxHash', (
31   '' => '(none)',
32   map { $_*12 => $_ } (1..5),
33 );
34
35 %info = (
36   'name' => 'Flat rate (anniversary billing)',
37   'shortname' => 'Anniversary',
38   'inherit_fields' => [ 'prorate_Mixin', 'usage_Mixin', 'global_Mixin' ],
39   'fields' => {
40     #false laziness w/voip_cdr.pm
41     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
42                              'type' => 'select',
43                              'select_options' => \%temporalities,
44                            },
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                         start_1st
88                         sync_bill_date prorate_defer_bill prorate_round_day
89                         suspend_bill unsuspend_adjust_bill
90                         bill_recur_on_cancel
91                         bill_suspend_as_cancel
92                         externalid ),
93                   ],
94   'weight' => 10,
95 );
96
97 sub price_info {
98   my $self = shift;
99   my %opt = @_;
100
101   my $setup = $opt{cust_pkg} ? $self->base_setup( $opt{cust_pkg} )
102                              : ($self->option('setup_fee') || 0);
103   my $recur = $opt{cust_pkg} ? $self->base_recur( $opt{cust_pkg} )
104                              : ($self->option('recur_fee', 1) || 0);
105   $recur += $self->usageprice_recur( $opt{cust_pkg} ) if $opt{cust_pkg};
106
107   my $str = '';
108   $str = $money_char . $setup . ($recur ? ' setup' : ' one-time') if $setup;
109   $str .= ', ' if ($setup && $recur);
110   $str .= $money_char. $recur. '/'. $self->freq_pretty if $recur;
111   $str;
112 }
113
114 sub calc_setup {
115   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
116
117   return 0 if $self->prorate_setup($cust_pkg, $sdate);
118
119   my $i = 0;
120   my $count = $self->option( 'additional_count', 'quiet' ) || 0;
121   while ($i < $count) {
122     push @$details, $self->option( 'additional_info' . $i++ );
123   }
124
125   my $charge = $self->base_setup($cust_pkg, $sdate, $details);
126
127   my $discount = 0;
128   if ( $charge > 0 ) {
129       $param->{'setup_charge'} = $charge;
130       $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
131       delete $param->{'setup_charge'};
132   }
133
134   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
135 }
136
137 sub base_setup {
138   my($self, $cust_pkg, $sdate, $details ) = @_;
139   $self->option('setup_fee', 1) || 0;
140 }
141
142 sub calc_recur {
143   my $self = shift;
144   my($cust_pkg, $sdate, $details, $param ) = @_;
145
146   #my $last_bill = $cust_pkg->last_bill;
147   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
148
149   return 0
150     if $self->recur_temporality eq 'preceding' && !$last_bill;
151
152   my $charge = $self->base_recur($cust_pkg, $sdate);
153   # always treat cutoff_day as a list
154   if ( my @cutoff_day = $self->cutoff_day($cust_pkg) ) {
155     $charge = $self->calc_prorate(@_, @cutoff_day);
156   }
157   elsif ( $param->{freq_override} ) {
158     # XXX not sure if this should be mutually exclusive with sync_bill_date.
159     # Given the very specific problem that freq_override is meant to 'solve',
160     # it probably should.
161     $charge *= $param->{freq_override} if $param->{freq_override};
162   }
163
164   $charge += $self->usageprice_recur($cust_pkg, $sdate);
165   $cust_pkg->apply_usageprice(); #$sdate for prorating?
166
167   my $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
168
169   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
170 }
171
172 sub cutoff_day {
173   my $self = shift;
174   my $cust_pkg = shift;
175   if ( $self->option('sync_bill_date',1) ) {
176     my $next_bill = $cust_pkg->cust_main->next_bill_date;
177     if ( $next_bill ) {
178       # careful here. if the prorate calculation is going to round to 
179       # the nearest day, this needs to always return the same result
180       if ( $self->option('prorate_round_day', 1) ) {
181         my $hour = (localtime($next_bill))[2];
182         $next_bill += 64800 if $hour >= 12;
183       }
184       return (localtime($next_bill))[3];
185     }
186   }
187   return ();
188 }
189
190 sub base_recur {
191   my($self, $cust_pkg, $sdate) = @_;
192   $self->option('recur_fee', 1) || 0;
193 }
194
195 sub base_recur_permonth {
196   my($self, $cust_pkg) = @_;
197
198   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
199
200   sprintf('%.2f', $self->base_recur($cust_pkg) / $self->freq );
201 }
202
203 sub usageprice_recur {
204   my($self, $cust_pkg, $sdate) = @_;
205
206   my $recur = 0;
207   $recur += $_->price foreach $cust_pkg->cust_pkg_usageprice;
208
209   sprintf('%.2f', $recur);
210 }
211
212 sub calc_cancel {
213   my $self = shift;
214   if ( $self->recur_temporality eq 'preceding'
215        and $self->option('bill_recur_on_cancel', 1) ) {
216     # run another recurring cycle
217     return $self->calc_recur(@_);
218   } elsif ( $conf->exists('bill_usage_on_cancel') # should be a package option?
219           and $self->can('calc_usage') ) {
220     # bill for outstanding usage
221     return $self->calc_usage(@_);
222   } else {
223     return 'NOTHING'; # numerically zero, but has special meaning
224   }
225 }
226
227 sub calc_remain {
228   my ($self, $cust_pkg, %options) = @_;
229
230   my $time;
231   if ($options{'time'}) {
232     $time = $options{'time'};
233   } else {
234     $time = time;
235   }
236
237   my $next_bill = $cust_pkg->getfield('bill') || 0;
238
239   return 0 if    ! $self->base_recur($cust_pkg, \$time)
240               || ! $next_bill
241               || $next_bill < $time;
242
243   # Use actual charge for this period, not base_recur (for discounts).
244   # Use sdate < $time and edate >= $time because when billing on 
245   # cancellation, edate = $time.
246   my $credit = 0;
247   foreach my $cust_bill_pkg ( 
248     qsearch('cust_bill_pkg', { 
249       pkgnum => $cust_pkg->pkgnum,
250       edate => {op => '>=', value => $time},
251       recur => {op => '>' , value => 0},
252     })
253   ) {
254
255     # hack to deal with the weird behavior of edate on package cancellation
256     my $edate = $cust_bill_pkg->edate;
257     if ( $self->recur_temporality eq 'preceding' ) {
258       $edate = $self->add_freq($cust_bill_pkg->sdate);
259     }
260
261     # this will also get any package charges that are _entirely_ after the
262     # cancellation date (can happen with advance billing). in that case,
263     # use the entire recurring charge:
264     my $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
265
266     # but if the cancellation happens during the interval, prorate it:
267     # (XXX obey prorate_round_day here?)
268     if ( $cust_bill_pkg->sdate < $time ) {
269       $amount = $amount * ($edate - $time) / ($edate - $cust_bill_pkg->sdate);
270     }
271
272     $credit += $amount;
273
274     push @{ $options{'cust_credit_source_bill_pkg'} },
275       new FS::cust_credit_source_bill_pkg {
276         'billpkgnum' => $cust_bill_pkg->billpkgnum,
277         'amount'     => sprintf('%.2f', $amount),
278         'currency'   => $cust_bill_pkg->cust_bill->currency,
279       }
280         if $options{'cust_credit_source_bill_pkg'};
281
282   } 
283
284   sprintf('%.2f', $credit);
285
286 }
287
288 sub is_free_options {
289   qw( setup_fee recur_fee );
290 }
291
292 sub is_prepaid { 0; } #no, we're postpaid
293
294 sub can_start_date {
295   my $self = shift;
296   my %opt = @_;
297   return 0 if $self->start_on_hold;
298
299   ! $self->option('start_1st', 1) && (   ! $self->option('sync_bill_date',1)
300                                       || ! $self->option('prorate_defer_bill',1)
301                                       || ! $opt{'num_ncancelled_pkgs'}
302                                      ); 
303 }
304
305 sub can_discount { 1; }
306
307 sub can_usageprice { 1; }
308
309 sub recur_temporality {
310   my $self = shift;
311   $self->option('recur_temporality', 1);
312 }
313
314 sub usage_valuehash {
315   my $self = shift;
316   map { $_, $self->option($_) }
317     grep { $self->option($_, 'hush') } 
318     qw(seconds upbytes downbytes totalbytes);
319 }
320
321 sub reset_usage {
322   my($self, $cust_pkg, %opt) = @_;
323   warn "   resetting usage counters" if defined($opt{debug}) && $opt{debug} > 1;
324   my %values = $self->usage_valuehash;
325   if ($self->option('usage_rollover', 1)) {
326     $cust_pkg->recharge(\%values);
327   }else{
328     $cust_pkg->set_usage(\%values, %opt);
329   }
330 }
331
332 1;