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