localize header / merge github#56
[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',
62                           'type' => 'select',
63                           'select_options' => \%FS::part_pkg::prorate_Mixin::prorate_round_day_opts,
64                         },
65     'add_full_period' => { 'disabled' => 1 }, # doesn't make sense with sync?
66
67     'suspend_bill' => { 'name' => 'Continue recurring billing while suspended',
68                         'type' => 'checkbox',
69                       },
70     'unsuspend_adjust_bill' => 
71                         { 'name' => 'Adjust next bill date forward when '.
72                                     'unsuspending',
73                           'type' => 'checkbox',
74                         },
75     'bill_recur_on_cancel' => {
76                         'name' => 'Bill the last period on cancellation',
77                         'type' => 'checkbox',
78                         },
79     'bill_suspend_as_cancel' => {
80                         'name' => 'Bill immediately upon suspension', #desc?
81                         'type' => 'checkbox',
82                         },
83     'externalid' => { 'name'   => 'Optional External ID',
84                       'default' => '',
85                     },
86   },
87   'fieldorder' => [ qw( recur_temporality 
88                         start_1st
89                         sync_bill_date prorate_defer_bill prorate_round_day
90                         suspend_bill unsuspend_adjust_bill
91                         bill_recur_on_cancel
92                         bill_suspend_as_cancel
93                         externalid ),
94                   ],
95   'weight' => 10,
96 );
97
98 sub price_info {
99   my $self = shift;
100   my %opt = @_;
101
102   my $setup = $opt{cust_pkg} ? $self->base_setup( $opt{cust_pkg} )
103                              : ($self->option('setup_fee') || 0);
104   my $recur = $opt{cust_pkg} ? $self->base_recur( $opt{cust_pkg} )
105                              : ($self->option('recur_fee', 1) || 0);
106   $recur += $self->usageprice_recur( $opt{cust_pkg} ) if $opt{cust_pkg};
107
108   my $str = '';
109   $str = $money_char . $setup . ($recur ? ' setup' : ' one-time') if $setup;
110   $str .= ', ' if ($setup && $recur);
111   $str .= $money_char. $recur. '/'. $self->freq_pretty if $recur;
112   $str;
113 }
114
115 sub calc_setup {
116   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
117
118   return 0 if $self->prorate_setup($cust_pkg, $sdate);
119
120   my $i = 0;
121   my $count = $self->option( 'additional_count', 'quiet' ) || 0;
122   while ($i < $count) {
123     push @$details, $self->option( 'additional_info' . $i++ );
124   }
125
126   my $charge = $self->base_setup($cust_pkg, $sdate, $details);
127
128   my $discount = 0;
129   if ( $charge > 0 ) {
130       $param->{'setup_charge'} = $charge;
131       $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
132       delete $param->{'setup_charge'};
133   }
134
135   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
136 }
137
138 sub base_setup {
139   my($self, $cust_pkg, $sdate, $details ) = @_;
140   $self->option('setup_fee', 1) || 0;
141 }
142
143 sub calc_recur {
144   my $self = shift;
145   my($cust_pkg, $sdate, $details, $param ) = @_;
146
147   #my $last_bill = $cust_pkg->last_bill;
148   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
149
150   return 0
151     if $self->recur_temporality eq 'preceding' && !$last_bill;
152
153   my $charge = $self->base_recur($cust_pkg, $sdate);
154   # always treat cutoff_day as a list
155   if ( my @cutoff_day = $self->cutoff_day($cust_pkg) ) {
156     $charge = $self->calc_prorate(@_, @cutoff_day);
157   }
158   elsif ( $param->{freq_override} ) {
159     # XXX not sure if this should be mutually exclusive with sync_bill_date.
160     # Given the very specific problem that freq_override is meant to 'solve',
161     # it probably should.
162     $charge *= $param->{freq_override} if $param->{freq_override};
163   }
164
165   $charge += $self->usageprice_recur($cust_pkg, $sdate);
166   $cust_pkg->apply_usageprice(); #$sdate for prorating?
167
168   my $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
169
170   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
171 }
172
173 sub cutoff_day {
174   my $self = shift;
175   my $cust_pkg = shift;
176   if ( $self->option('sync_bill_date',1) ) {
177     my $next_bill = $cust_pkg->cust_main->next_bill_date;
178     if ( $next_bill ) {
179       # careful here. if the prorate calculation is going to round to 
180       # the nearest day, this needs to always return the same result
181       if ( $self->option('prorate_round_day', 1) ) {
182         my $hour = (localtime($next_bill))[2];
183         $next_bill += 64800 if $hour >= 12;
184       }
185       return (localtime($next_bill))[3];
186     }
187   }
188   return ();
189 }
190
191 sub base_recur {
192   my($self, $cust_pkg, $sdate) = @_;
193   $self->option('recur_fee', 1) || 0;
194 }
195
196 sub base_recur_permonth {
197   my($self, $cust_pkg) = @_;
198
199   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
200
201   sprintf('%.2f', $self->base_recur($cust_pkg) / $self->freq );
202 }
203
204 sub usageprice_recur {
205   my($self, $cust_pkg, $sdate) = @_;
206
207   my $recur = 0;
208   $recur += $_->price foreach $cust_pkg->cust_pkg_usageprice;
209
210   sprintf('%.2f', $recur);
211 }
212
213 sub calc_cancel {
214   my $self = shift;
215   if ( $self->recur_temporality eq 'preceding'
216        and $self->option('bill_recur_on_cancel', 1) ) {
217     # run another recurring cycle
218     return $self->calc_recur(@_);
219   } elsif ( $conf->exists('bill_usage_on_cancel') # should be a package option?
220           and $self->can('calc_usage') ) {
221     # bill for outstanding usage
222     return $self->calc_usage(@_);
223   } else {
224     return 'NOTHING'; # numerically zero, but has special meaning
225   }
226 }
227
228 sub calc_remain {
229   my ($self, $cust_pkg, %options) = @_;
230
231   my $time;
232   if ($options{'time'}) {
233     $time = $options{'time'};
234   } else {
235     $time = time;
236   }
237
238   my $next_bill = $cust_pkg->getfield('bill') || 0;
239
240   return 0 if    ! $self->base_recur($cust_pkg, \$time)
241               || ! $next_bill
242               || $next_bill < $time;
243
244   # Use actual charge for this period, not base_recur (for discounts).
245   # Use sdate < $time and edate >= $time because when billing on 
246   # cancellation, edate = $time.
247   my $credit = 0;
248   foreach my $cust_bill_pkg ( 
249     qsearch('cust_bill_pkg', { 
250       pkgnum => $cust_pkg->pkgnum,
251       edate => {op => '>=', value => $time},
252       recur => {op => '>' , value => 0},
253     })
254   ) {
255
256     # hack to deal with the weird behavior of edate on package cancellation
257     my $edate = $cust_bill_pkg->edate;
258     if ( $self->recur_temporality eq 'preceding' ) {
259       $edate = $self->add_freq($cust_bill_pkg->sdate);
260     }
261
262     # this will also get any package charges that are _entirely_ after the
263     # cancellation date (can happen with advance billing). in that case,
264     # use the entire recurring charge:
265     my $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
266
267     # but if the cancellation happens during the interval, prorate it:
268     # (XXX obey prorate_round_day here?)
269     if ( $cust_bill_pkg->sdate < $time ) {
270       $amount = $amount * ($edate - $time) / ($edate - $cust_bill_pkg->sdate);
271     }
272
273     $credit += $amount;
274
275     push @{ $options{'cust_credit_source_bill_pkg'} },
276       new FS::cust_credit_source_bill_pkg {
277         'billpkgnum' => $cust_bill_pkg->billpkgnum,
278         'amount'     => sprintf('%.2f', $amount),
279         'currency'   => $cust_bill_pkg->cust_bill->currency,
280       }
281         if $options{'cust_credit_source_bill_pkg'};
282
283   } 
284
285   sprintf('%.2f', $credit);
286
287 }
288
289 sub is_free_options {
290   qw( setup_fee recur_fee );
291 }
292
293 sub is_prepaid { 0; } #no, we're postpaid
294
295 sub can_start_date {
296   my $self = shift;
297   my %opt = @_;
298   return 0 if $self->start_on_hold;
299
300   ! $self->option('start_1st', 1) && (   ! $self->option('sync_bill_date',1)
301                                       || ! $self->option('prorate_defer_bill',1)
302                                       || ! $opt{'num_ncancelled_pkgs'}
303                                      ); 
304 }
305
306 sub can_discount { 1; }
307
308 sub can_usageprice { 1; }
309
310 sub recur_temporality {
311   my $self = shift;
312   $self->option('recur_temporality', 1);
313 }
314
315 sub usage_valuehash {
316   my $self = shift;
317   map { $_, $self->option($_) }
318     grep { $self->option($_, 'hush') } 
319     qw(seconds upbytes downbytes totalbytes);
320 }
321
322 sub reset_usage {
323   my($self, $cust_pkg, %opt) = @_;
324   warn "   resetting usage counters" if defined($opt{debug}) && $opt{debug} > 1;
325   my %values = $self->usage_valuehash;
326   if ($self->option('usage_rollover', 1)) {
327     $cust_pkg->recharge(\%values);
328   }else{
329     $cust_pkg->set_usage(\%values, %opt);
330   }
331 }
332
333 1;