Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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 FS::cust_credit_source_bill_pkg;
11 use Tie::IxHash;
12 use List::Util qw( min );
13 use FS::UI::bytecount;
14 use FS::Conf;
15
16 tie my %temporalities, 'Tie::IxHash',
17   'upcoming'  => "Upcoming (future)",
18   'preceding' => "Preceding (past)",
19 ;
20
21 tie my %contract_years, 'Tie::IxHash', (
22   '' => '(none)',
23   map { $_*12 => $_ } (1..5),
24 );
25
26 %info = (
27   'name' => 'Flat rate (anniversary billing)',
28   'shortname' => 'Anniversary',
29   'inherit_fields' => [ 'prorate_Mixin', 'usage_Mixin', 'global_Mixin' ],
30   'fields' => {
31     #false laziness w/voip_cdr.pm
32     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
33                              'type' => 'select',
34                              'select_options' => \%temporalities,
35                            },
36
37     #used in cust_pkg.pm so could add to any price plan
38     'expire_months' => { 'name' => 'Auto-add an expiration date this number of months out',
39                        },
40     'adjourn_months'=> { 'name' => 'Auto-add a suspension date this number of months out',
41                        },
42     'contract_end_months'=> { 
43                         'name' => 'Auto-add a contract end date this number of years out',
44                         'type' => 'select',
45                         'select_options' => \%contract_years,
46                       },
47     #used in cust_pkg.pm so could add to any price plan where it made sense
48     'start_1st'     => { 'name' => 'Auto-add a start date to the 1st, ignoring the current month.',
49                          'type' => 'checkbox',
50                        },
51     'sync_bill_date' => { 'name' => 'Prorate first month to synchronize '.
52                                     'with the customer\'s other packages',
53                           'type' => 'checkbox',
54                         },
55     'prorate_defer_bill' => { 
56                           'name' => 'When synchronizing, defer the bill until '.
57                                     'the customer\'s next bill date',
58                           'type' => 'checkbox',
59                         },
60     'prorate_round_day' => {
61                           'name' => 'When synchronizing, round the prorated '.
62                                     'period to the nearest full day',
63                           'type' => 'checkbox',
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                         expire_months adjourn_months
89                         contract_end_months
90                         start_1st
91                         sync_bill_date prorate_defer_bill prorate_round_day
92                         suspend_bill unsuspend_adjust_bill
93                         bill_recur_on_cancel
94                         bill_suspend_as_cancel
95                         externalid ),
96                   ],
97   'weight' => 10,
98 );
99
100 sub price_info {
101     my $self = shift;
102     my %opt = @_;
103     my $conf = new FS::Conf;
104     my $money_char = $conf->config('money_char') || '$';
105     my $setup = $opt{cust_pkg} ? $self->base_setup( $opt{cust_pkg} )
106                                : ($self->option('setup_fee') || 0);
107     my $recur = $opt{cust_pkg} ? $self->base_recur( $opt{cust_pkg} )
108                                : ($self->option('recur_fee', 1) || 0);
109     $recur += $self->usageprice_recur( $opt{cust_pkg} ) if $opt{cust_pkg};
110     my $str = '';
111     $str = $money_char . $setup . ($recur ? ' setup' : ' one-time') if $setup;
112     $str .= ', ' if ($setup && $recur);
113     $str .= $money_char. $recur. '/'. $self->freq_pretty if $recur;
114     $str;
115 }
116
117 sub calc_setup {
118   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
119
120   return 0 if $self->prorate_setup($cust_pkg, $sdate);
121
122   my $i = 0;
123   my $count = $self->option( 'additional_count', 'quiet' ) || 0;
124   while ($i < $count) {
125     push @$details, $self->option( 'additional_info' . $i++ );
126   }
127
128   my $charge = $self->base_setup($cust_pkg, $sdate, $details);
129
130   my $discount = 0;
131   if ( $charge > 0 ) {
132       $param->{'setup_charge'} = $charge;
133       $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
134       delete $param->{'setup_charge'};
135   }
136
137   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
138 }
139
140 sub base_setup {
141   my($self, $cust_pkg, $sdate, $details ) = @_;
142
143   $self->option('setup_fee') || 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   $self->option('recur_fee', 1) || 0;
197 }
198
199 sub base_recur_permonth {
200   my($self, $cust_pkg) = @_;
201
202   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
203
204   sprintf('%.2f', $self->base_recur($cust_pkg) / $self->freq );
205 }
206
207 sub usageprice_recur {
208   my($self, $cust_pkg, $sdate) = @_;
209
210   my $recur = 0;
211   $recur += $_->price foreach $cust_pkg->cust_pkg_usageprice;
212
213   sprintf('%.2f', $recur);
214 }
215
216 sub calc_cancel {
217   my $self = shift;
218   my $conf = new FS::Conf;
219   if ( $self->recur_temporality eq 'preceding'
220        and $self->option('bill_recur_on_cancel', 1) ) {
221     # run another recurring cycle
222     return $self->calc_recur(@_);
223   }
224   elsif ( $conf->exists('bill_usage_on_cancel') # should be a package option?
225           and $self->can('calc_usage') ) {
226     # bill for outstanding usage
227     return $self->calc_usage(@_);
228   }
229   0;
230 }
231
232 sub calc_remain {
233   my ($self, $cust_pkg, %options) = @_;
234
235   my $time;
236   if ($options{'time'}) {
237     $time = $options{'time'};
238   } else {
239     $time = time;
240   }
241
242   my $next_bill = $cust_pkg->getfield('bill') || 0;
243
244   return 0 if    ! $self->base_recur($cust_pkg, \$time)
245               || ! $next_bill
246               || $next_bill < $time;
247
248   # Use actual charge for this period, not base_recur (for discounts).
249   # Use sdate < $time and edate >= $time because when billing on 
250   # cancellation, edate = $time.
251   my $credit = 0;
252   foreach my $cust_bill_pkg ( 
253     qsearch('cust_bill_pkg', { 
254       pkgnum => $cust_pkg->pkgnum,
255       sdate => {op => '<' , value => $time},
256       edate => {op => '>=', value => $time},
257       recur => {op => '>' , value => 0},
258     })
259   ) {
260
261     # hack to deal with the weird behavior of edate on package cancellation
262     my $edate = $cust_bill_pkg->edate;
263     if ( $self->recur_temporality eq 'preceding' ) {
264       $edate = $self->add_freq($cust_bill_pkg->sdate);
265     }
266
267     my $amount = ($cust_bill_pkg->recur - $cust_bill_pkg->usage) * 
268                  ($edate - $time) / ($edate - $cust_bill_pkg->sdate);
269     $credit += $amount;
270
271     push @{ $options{'cust_credit_source_bill_pkg'} },
272       new FS::cust_credit_source_bill_pkg {
273         'billpkgnum' => $cust_bill_pkg->billpkgnum,
274         'amount'     => sprintf('%.2f', $amount),
275         'currency'   => $cust_bill_pkg->cust_bill->currency,
276       }
277         if $options{'cust_credit_source_bill_pkg'};
278
279   } 
280
281   sprintf('%.2f', $credit);
282
283 }
284
285 sub is_free_options {
286   qw( setup_fee recur_fee );
287 }
288
289 sub is_prepaid { 0; } #no, we're postpaid
290
291 sub can_start_date {
292   my $self = shift;
293   my %opt = @_;
294   return 0 if $self->start_on_hold;
295
296   ! $self->option('start_1st', 1) && (   ! $self->option('sync_bill_date',1)
297                                       || ! $self->option('prorate_defer_bill',1)
298                                       || ! $opt{'num_ncancelled_pkgs'}
299                                      ); 
300 }
301
302 sub can_discount { 1; }
303
304 sub can_usageprice { 1; }
305
306 sub recur_temporality {
307   my $self = shift;
308   $self->option('recur_temporality', 1);
309 }
310
311 sub usage_valuehash {
312   my $self = shift;
313   map { $_, $self->option($_) }
314     grep { $self->option($_, 'hush') } 
315     qw(seconds upbytes downbytes totalbytes);
316 }
317
318 sub reset_usage {
319   my($self, $cust_pkg, %opt) = @_;
320   warn "   resetting usage counters" if defined($opt{debug}) && $opt{debug} > 1;
321   my %values = $self->usage_valuehash;
322   if ($self->option('usage_rollover', 1)) {
323     $cust_pkg->recharge(\%values);
324   }else{
325     $cust_pkg->set_usage(\%values, %opt);
326   }
327 }
328
329 1;