04d761b16ca5b348bc6c08610da64e7cd6276778
[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   ( exists( $self->{'Hash'}{'_opt_setup_fee'} )
140       ? $self->{'Hash'}{'_opt_setup_fee'}
141       : $self->option('setup_fee', 1) 
142   )
143     || 0;
144 }
145
146 sub calc_recur {
147   my $self = shift;
148   my($cust_pkg, $sdate, $details, $param ) = @_;
149
150   #my $last_bill = $cust_pkg->last_bill;
151   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
152
153   return 0
154     if $self->recur_temporality eq 'preceding' && !$last_bill;
155
156   my $charge = $self->base_recur($cust_pkg, $sdate);
157   # always treat cutoff_day as a list
158   if ( my @cutoff_day = $self->cutoff_day($cust_pkg) ) {
159     $charge = $self->calc_prorate(@_, @cutoff_day);
160   }
161   elsif ( $param->{freq_override} ) {
162     # XXX not sure if this should be mutually exclusive with sync_bill_date.
163     # Given the very specific problem that freq_override is meant to 'solve',
164     # it probably should.
165     $charge *= $param->{freq_override} if $param->{freq_override};
166   }
167
168   $charge += $self->usageprice_recur($cust_pkg, $sdate);
169   $cust_pkg->apply_usageprice(); #$sdate for prorating?
170
171   my $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
172
173   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
174 }
175
176 sub cutoff_day {
177   my $self = shift;
178   my $cust_pkg = shift;
179   if ( $self->option('sync_bill_date',1) ) {
180     my $next_bill = $cust_pkg->cust_main->next_bill_date;
181     if ( defined($next_bill) ) {
182       # careful here. if the prorate calculation is going to round to 
183       # the nearest day, this needs to always return the same result
184       if ( $self->option('prorate_round_day', 1) ) {
185         my $hour = (localtime($next_bill))[2];
186         $next_bill += 64800 if $hour >= 12;
187       }
188       return (localtime($next_bill))[3];
189     }
190   }
191   return ();
192 }
193
194 sub base_recur {
195   my($self, $cust_pkg, $sdate) = @_;
196   ( exists( $self->{'Hash'}{'_opt_recur_fee'} )
197       ? $self->{'Hash'}{'_opt_recur_fee'}
198       : $self->option('recur_fee', 1) 
199   )
200     || 0;
201 }
202
203 sub base_recur_permonth {
204   my($self, $cust_pkg) = @_;
205
206   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
207
208   sprintf('%.2f', $self->base_recur($cust_pkg) / $self->freq );
209 }
210
211 sub usageprice_recur {
212   my($self, $cust_pkg, $sdate) = @_;
213
214   my $recur = 0;
215   $recur += $_->price foreach $cust_pkg->cust_pkg_usageprice;
216
217   sprintf('%.2f', $recur);
218 }
219
220 sub calc_cancel {
221   my $self = shift;
222   if ( $self->recur_temporality eq 'preceding'
223        and $self->option('bill_recur_on_cancel', 1) ) {
224     # run another recurring cycle
225     return $self->calc_recur(@_);
226   } elsif ( $conf->exists('bill_usage_on_cancel') # should be a package option?
227           and $self->can('calc_usage') ) {
228     # bill for outstanding usage
229     return $self->calc_usage(@_);
230   } else {
231     return 'NOTHING'; # numerically zero, but has special meaning
232   }
233 }
234
235 sub calc_remain {
236   my ($self, $cust_pkg, %options) = @_;
237
238   my $time;
239   if ($options{'time'}) {
240     $time = $options{'time'};
241   } else {
242     $time = time;
243   }
244
245   my $next_bill = $cust_pkg->getfield('bill') || 0;
246
247   return 0 if    ! $self->base_recur($cust_pkg, \$time)
248               || ! $next_bill
249               || $next_bill < $time;
250
251   # Use actual charge for this period, not base_recur (for discounts).
252   # Use sdate < $time and edate >= $time because when billing on 
253   # cancellation, edate = $time.
254   my $credit = 0;
255   foreach my $cust_bill_pkg ( 
256     qsearch('cust_bill_pkg', { 
257       pkgnum => $cust_pkg->pkgnum,
258       edate => {op => '>=', value => $time},
259       recur => {op => '>' , value => 0},
260     })
261   ) {
262
263     # hack to deal with the weird behavior of edate on package cancellation
264     my $edate = $cust_bill_pkg->edate;
265     if ( $self->recur_temporality eq 'preceding' ) {
266       $edate = $self->add_freq($cust_bill_pkg->sdate);
267     }
268
269     # this will also get any package charges that are _entirely_ after the
270     # cancellation date (can happen with advance billing). in that case,
271     # use the entire recurring charge:
272     my $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
273
274     # but if the cancellation happens during the interval, prorate it:
275     # (XXX obey prorate_round_day here?)
276     if ( $cust_bill_pkg->sdate < $time ) {
277       $amount = $amount * ($edate - $time) / ($edate - $cust_bill_pkg->sdate);
278     }
279
280     $credit += $amount;
281
282     push @{ $options{'cust_credit_source_bill_pkg'} },
283       new FS::cust_credit_source_bill_pkg {
284         'billpkgnum' => $cust_bill_pkg->billpkgnum,
285         'amount'     => sprintf('%.2f', $amount),
286         'currency'   => $cust_bill_pkg->cust_bill->currency,
287       }
288         if $options{'cust_credit_source_bill_pkg'};
289
290   } 
291
292   sprintf('%.2f', $credit);
293
294 }
295
296 sub is_free_options {
297   qw( setup_fee recur_fee );
298 }
299
300 sub is_prepaid { 0; } #no, we're postpaid
301
302 sub can_start_date {
303   my $self = shift;
304   my %opt = @_;
305   return 0 if $self->start_on_hold;
306
307   ! $self->option('start_1st', 1) && (   ! $self->option('sync_bill_date',1)
308                                       || ! $self->option('prorate_defer_bill',1)
309                                       || ! $opt{'num_ncancelled_pkgs'}
310                                      ); 
311 }
312
313 sub can_discount { 1; }
314
315 sub can_usageprice { 1; }
316
317 sub recur_temporality {
318   my $self = shift;
319   $self->option('recur_temporality', 1);
320 }
321
322 sub usage_valuehash {
323   my $self = shift;
324   map { $_, $self->option($_) }
325     grep { $self->option($_, 'hush') } 
326     qw(seconds upbytes downbytes totalbytes);
327 }
328
329 sub reset_usage {
330   my($self, $cust_pkg, %opt) = @_;
331   warn "   resetting usage counters" if defined($opt{debug}) && $opt{debug} > 1;
332   my %values = $self->usage_valuehash;
333   if ($self->option('usage_rollover', 1)) {
334     $cust_pkg->recharge(\%values);
335   }else{
336     $cust_pkg->set_usage(\%values, %opt);
337   }
338 }
339
340 1;