RT# 74877 flat pkg conf opt prorate_defer_change_bill
[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 use Time::Local 'timelocal';
19
20 #ask FS::UID to run this stuff for us later
21 FS::UID->install_callback( sub {
22   $conf = new FS::Conf;
23   $money_char = $conf->config('money_char') || '$';
24 });
25
26 tie my %temporalities, 'Tie::IxHash',
27   'upcoming'  => "Upcoming (future)",
28   'preceding' => "Preceding (past)",
29 ;
30
31 tie my %contract_years, 'Tie::IxHash', (
32   '' => '(none)',
33   map { $_*12 => $_ } (1..5),
34 );
35
36 %info = (
37   'name' => 'Flat rate (anniversary billing)',
38   'shortname' => 'Anniversary',
39   'inherit_fields' => [ 'prorate_Mixin', 'usage_Mixin', 'global_Mixin' ],
40   'fields' => {
41     #false laziness w/voip_cdr.pm
42     'recur_temporality' => { 'name' => 'Charge recurring fee for period',
43                              'type' => 'select',
44                              'select_options' => \%temporalities,
45                            },
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_defer_change_bill' => {
61                           'name' => 'When synchronizing, defer bill for '.
62                                     'package changes until the customer\'s '.
63                                     'next bill date',
64                           'type' => 'checkbox',
65                         },
66     'prorate_round_day' => {
67                           'name' => 'When synchronizing, round the prorated '.
68                                     'period',
69                           'type' => 'select',
70                           'select_options' => \%FS::part_pkg::prorate_Mixin::prorate_round_day_opts,
71                         },
72     'add_full_period' => { 'disabled' => 1 }, # doesn't make sense with sync?
73
74     'suspend_bill' => { 'name' => 'Continue recurring billing while suspended',
75                         'type' => 'checkbox',
76                       },
77     'unsuspend_adjust_bill' => 
78                         { 'name' => 'Adjust next bill date forward when '.
79                                     'unsuspending',
80                           'type' => 'checkbox',
81                         },
82     'bill_recur_on_cancel' => {
83                         'name' => 'Bill the last period on cancellation',
84                         'type' => 'checkbox',
85                         },
86     'bill_suspend_as_cancel' => {
87                         'name' => 'Bill immediately upon suspension', #desc?
88                         'type' => 'checkbox',
89                         },
90     'externalid' => { 'name'   => 'Optional External ID',
91                       'default' => '',
92                     },
93   },
94   'fieldorder' => [ qw( recur_temporality 
95                         start_1st
96                         sync_bill_date prorate_defer_bill
97                         prorate_defer_change_bill prorate_round_day
98                         suspend_bill unsuspend_adjust_bill
99                         bill_recur_on_cancel
100                         bill_suspend_as_cancel
101                         externalid ),
102                   ],
103   'weight' => 10,
104 );
105
106 sub price_info {
107   my $self = shift;
108   my %opt = @_;
109
110   my $setup = $opt{cust_pkg} ? $self->base_setup( $opt{cust_pkg} )
111                              : ($self->option('setup_fee') || 0);
112   my $recur = $opt{cust_pkg} ? $self->base_recur( $opt{cust_pkg} )
113                              : ($self->option('recur_fee', 1) || 0);
114   $recur += $self->usageprice_recur( $opt{cust_pkg} ) if $opt{cust_pkg};
115
116   my $str = '';
117   $str = $money_char . $setup . ($recur ? ' setup' : ' one-time') if $setup;
118   $str .= ', ' if ($setup && $recur);
119   $str .= $money_char. $recur. '/'. $self->freq_pretty if $recur;
120   $str;
121 }
122
123 sub calc_setup {
124   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
125
126   return 0 if $self->prorate_setup($cust_pkg, $sdate);
127
128   my $i = 0;
129   my $count = $self->option( 'additional_count', 'quiet' ) || 0;
130   while ($i < $count) {
131     push @$details, $self->option( 'additional_info' . $i++ );
132   }
133
134   my $charge = $self->base_setup($cust_pkg, $sdate, $details);
135
136   my $discount = 0;
137   if ( $charge > 0 ) {
138       $param->{'setup_charge'} = $charge;
139       $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
140       delete $param->{'setup_charge'};
141   }
142
143   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
144 }
145
146 sub base_setup {
147   my($self, $cust_pkg, $sdate, $details ) = @_;
148   $self->option('setup_fee', 1) || 0;
149 }
150
151 sub calc_recur {
152   my $self = shift;
153   my($cust_pkg, $sdate, $details, $param ) = @_;
154
155   #my $last_bill = $cust_pkg->last_bill;
156   my $last_bill = $cust_pkg->get('last_bill'); #->last_bill falls back to setup
157
158   return 0
159     if $self->recur_temporality eq 'preceding' && !$last_bill;
160
161   my $charge = $self->base_recur($cust_pkg, $sdate);
162   # always treat cutoff_day as a list
163   if ( my @cutoff_day = $self->cutoff_day($cust_pkg) ) {
164     $charge = $self->calc_prorate(@_, @cutoff_day);
165   }
166   elsif ( $param->{freq_override} ) {
167     # XXX not sure if this should be mutually exclusive with sync_bill_date.
168     # Given the very specific problem that freq_override is meant to 'solve',
169     # it probably should.
170     $charge *= $param->{freq_override} if $param->{freq_override};
171   }
172
173   $charge += $self->usageprice_recur($cust_pkg, $sdate);
174   $cust_pkg->apply_usageprice(); #$sdate for prorating?
175
176   my $discount = $self->calc_discount($cust_pkg, $sdate, $details, $param);
177
178   sprintf( '%.2f', ($cust_pkg->quantity || 1) * ($charge - $discount) );
179 }
180
181 sub cutoff_day {
182   my $self = shift;
183   my $cust_pkg = shift;
184   my $cust_main = $cust_pkg->cust_main;
185   # force it to act like a prorate package, is what this means
186   # because we made a distinction once between prorate and flat packages
187   if ( $cust_main->force_prorate_day  and $cust_main->prorate_day ) {
188      return ( $cust_main->prorate_day );
189   }
190   if ( $self->option('sync_bill_date',1) ) {
191     my $next_bill = $cust_pkg->cust_main->next_bill_date;
192     if ( $next_bill ) {
193       return (localtime($next_bill))[3];
194     } else {
195       # This is the customer's only active package and hasn't been billed
196       # yet, so set the cutoff day to either today or tomorrow, whichever
197       # would result in a full period after rounding.
198       my $setup = $cust_pkg->setup; # because it's "now"
199       my $rounding_mode = $self->option('prorate_round_day',1);
200       return () if !$setup or !$rounding_mode;
201       my ($sec, $min, $hour, $mday, $mon, $year) = localtime($setup);
202
203       if (   ( $rounding_mode == 1 and $hour >= 12 )
204           or ( $rounding_mode == 3 and ( $sec > 0 or $min > 0 or $hour > 0 ))
205       ) {
206         # then the prorate period will be rounded down to start from
207         # midnight tomorrow, so the cutoff day should be the current day +
208         # 1.
209         $setup = timelocal(59,59,23,$mday,$mon,$year) + 1;
210         $mday = (localtime($setup))[3];
211       }
212       # otherwise, it will be rounded up, so leave the cutoff day at today.
213       return $mday;
214     }
215   }
216   return ();
217 }
218
219 sub base_recur {
220   my($self, $cust_pkg, $sdate) = @_;
221   $self->option('recur_fee', 1) || 0;
222 }
223
224 sub base_recur_permonth {
225   my($self, $cust_pkg) = @_;
226
227   return 0 unless $self->freq =~ /^\d+$/ && $self->freq > 0;
228
229   sprintf('%.2f', $self->base_recur($cust_pkg) / $self->freq );
230 }
231
232 sub usageprice_recur {
233   my($self, $cust_pkg, $sdate) = @_;
234
235   my $recur = 0;
236   $recur += $_->price foreach $cust_pkg->cust_pkg_usageprice;
237
238   sprintf('%.2f', $recur);
239 }
240
241 sub calc_cancel {
242   my $self = shift;
243   if ( $self->recur_temporality eq 'preceding'
244        and $self->option('bill_recur_on_cancel', 1) ) {
245     # run another recurring cycle
246     return $self->calc_recur(@_);
247   } elsif ( $conf->exists('bill_usage_on_cancel') # should be a package option?
248           and $self->can('calc_usage') ) {
249     # bill for outstanding usage
250     return $self->calc_usage(@_);
251   } else {
252     return 'NOTHING'; # numerically zero, but has special meaning
253   }
254 }
255
256 # no longer used; see credit_remaining in FS::cust_pkg
257
258 sub calc_remain {
259   my ($self, $cust_pkg, %options) = @_;
260
261   my $time;
262   if ($options{'time'}) {
263     $time = $options{'time'};
264   } else {
265     $time = time;
266   }
267
268   my $next_bill = $cust_pkg->getfield('bill') || 0;
269
270   return 0 if    ! $self->base_recur($cust_pkg, \$time)
271               || ! $next_bill
272               || $next_bill < $time;
273
274   # Use actual charge for this period, not base_recur (for discounts).
275   # Use sdate < $time and edate >= $time because when billing on 
276   # cancellation, edate = $time.
277   my $credit = 0;
278   foreach my $cust_bill_pkg ( 
279     qsearch('cust_bill_pkg', { 
280       pkgnum => $cust_pkg->pkgnum,
281       edate => {op => '>=', value => $time},
282       recur => {op => '>' , value => 0},
283     })
284   ) {
285
286     # hack to deal with the weird behavior of edate on package cancellation
287     my $edate = $cust_bill_pkg->edate;
288     if ( $self->recur_temporality eq 'preceding' ) {
289       $edate = $self->add_freq($cust_bill_pkg->sdate);
290     }
291
292     # this will also get any package charges that are _entirely_ after the
293     # cancellation date (can happen with advance billing). in that case,
294     # use the entire recurring charge:
295     my $amount = $cust_bill_pkg->recur - $cust_bill_pkg->usage;
296
297     # but if the cancellation happens during the interval, prorate it:
298     # (XXX obey prorate_round_day here?)
299     if ( $cust_bill_pkg->sdate < $time ) {
300       $amount = $amount * ($edate - $time) / ($edate - $cust_bill_pkg->sdate);
301     }
302
303     $credit += $amount;
304
305     push @{ $options{'cust_credit_source_bill_pkg'} },
306       new FS::cust_credit_source_bill_pkg {
307         'billpkgnum' => $cust_bill_pkg->billpkgnum,
308         'amount'     => sprintf('%.2f', $amount),
309         'currency'   => $cust_bill_pkg->cust_bill->currency,
310       }
311         if $options{'cust_credit_source_bill_pkg'};
312
313   } 
314
315   sprintf('%.2f', $credit);
316
317 }
318
319 sub is_free_options {
320   qw( setup_fee recur_fee );
321 }
322
323 sub is_prepaid { 0; } #no, we're postpaid
324
325 sub can_start_date {
326   my $self = shift;
327   my %opt = @_;
328   return 0 if $self->start_on_hold;
329
330   ! $self->option('start_1st', 1) && (   ! $self->option('sync_bill_date',1)
331                                       || ! $self->option('prorate_defer_bill',1)
332                                       || ! $opt{'num_ncancelled_pkgs'}
333                                      ); 
334 }
335
336 sub can_discount { 1; }
337
338 sub can_usageprice { 1; }
339
340 sub recur_temporality {
341   my $self = shift;
342   $self->option('recur_temporality', 1);
343 }
344
345 sub usage_valuehash {
346   my $self = shift;
347   map { $_, $self->option($_) }
348     grep { $self->option($_, 'hush') } 
349     qw(seconds upbytes downbytes totalbytes);
350 }
351
352 sub reset_usage {
353   my($self, $cust_pkg, %opt) = @_;
354   warn "   resetting usage counters" if defined($opt{debug}) && $opt{debug} > 1;
355   my %values = $self->usage_valuehash;
356   if ($self->option('usage_rollover', 1)) {
357     $cust_pkg->recharge(\%values);
358   }else{
359     $cust_pkg->set_usage(\%values, %opt);
360   }
361 }
362
363 1;