5b3f100940e2ad19f0da143444b3f29859aa0c72
[freeside.git] / FS / FS / part_pkg / discount_Mixin.pm
1 package FS::part_pkg::discount_Mixin;
2
3 use strict;
4 use vars qw( %info );
5 use Time::Local qw( timelocal );
6 use List::Util  qw( min );
7 use FS::Record qw( qsearchs );
8 use FS::cust_pkg;
9 use FS::cust_bill_pkg_discount;
10
11 %info = ( 'disabled' => 1 );
12
13 =head1 NAME
14
15 FS::part_pkg::discount_Mixin - Mixin class for part_pkg:: classes that 
16 can be discounted.
17
18 =head1 SYNOPSIS
19
20 package FS::part_pkg::...;
21 use base qw( FS::part_pkg::discount_Mixin );
22
23 sub calc_recur {
24   ...
25   my $discount = $self->calc_discount($cust_pkg, $$sdate, $details, $param);
26   $charge -= $discount;
27   ...
28 }
29
30 =head METHODS
31
32 =item calc_discount CUST_PKG, SDATE, DETAILS_ARRAYREF, PARAM_HASHREF
33
34 Takes all the arguments of calc_recur.  Calculates and returns the amount 
35 by which to reduce the charge; also increments months used on the discount.
36
37 If there is a setup fee, this will be called once with 'setup_charge' => the
38 setup fee amount (and should return the discount to be applied to the setup
39 charge, if any), and again without it (for the recurring fee discount). 
40 PARAM_HASHREF carries over between the two invocations.
41
42 =cut
43
44 sub calc_discount {
45   my($self, $cust_pkg, $sdate, $details, $param ) = @_;
46   my $conf = new FS::Conf;
47
48   my $br = $self->base_recur($cust_pkg, $sdate);
49   $br += $param->{'override_charges'} * ($cust_pkg->part_pkg->freq || 0) if $param->{'override_charges'};
50
51   my $tot_discount = 0;
52   #UI enforces just 1 for now, will need ordering when they can be stacked
53
54   if ( $param->{freq_override} ) {
55     # When a customer pays for more than one month at a time to receive a 
56     # term discount, freq_override is set to the number of months.
57     my $real_part_pkg = new FS::part_pkg { $self->hash };
58     $real_part_pkg->pkgpart($param->{real_pkgpart} || $self->pkgpart);
59     # Find a discount with that duration...
60     my @discount = grep { $_->months == $param->{freq_override} }
61                     map { $_->discount } $real_part_pkg->part_pkg_discount;
62     my $discount = shift @discount;
63     # and default to bill that many months at once.
64     $param->{months} = $param->{freq_override} unless $param->{months};
65     my $error;
66     if ($discount) {
67       # Then set the cust_pkg discount.
68       if ($discount->months == $param->{months}) {
69         $cust_pkg->discountnum($discount->discountnum);
70         $error = $cust_pkg->insert_discount;
71       } else {
72         $cust_pkg->discountnum(-1);
73         foreach ( qw( amount percent months ) ) {
74           my $method = "discountnum_$_";
75           $cust_pkg->$method($discount->$_);
76         }
77         $error = $cust_pkg->insert_discount;
78       }
79       die "error discounting using part_pkg_discount: $error" if $error;
80     }
81   }
82
83   my @cust_pkg_discount = $cust_pkg->cust_pkg_discount_active;
84   foreach my $cust_pkg_discount ( @cust_pkg_discount ) {
85     my $discount_left;
86     my $discount = $cust_pkg_discount->discount;
87     #UI enforces one or the other (for now?  probably for good)
88     # $chg_months: the number of months we are charging recur for
89     # $months: $chg_months or the months left on the discount, whchever is less
90
91     my $chg_months = $cust_pkg->part_pkg->freq || 1;
92     if ( defined($param->{'months'}) ) { # then override
93       $chg_months = $param->{'months'};
94     }
95
96     my $months = $chg_months;
97     if ( $discount->months ) {
98       $months = min( $chg_months,
99                      $discount->months - $cust_pkg_discount->months_used );
100     }
101
102     # $amount is now the (estimated) discount amount on the recurring charge.
103     # if it's a percent discount, that's base recur * percentage.
104
105     my $amount = 0;
106
107     if (defined $param->{'setup_charge'}) {
108
109         # we are calculating the setup discount.
110         # if this discount doesn't apply to setup fees, skip it.
111         # if it's a percent discount, set $amount = percent * setup_charge.
112         # if it's a flat amount discount for one month:
113         # - if the discount amount > setup_charge, then set it to setup_charge,
114         #   and set 'discount_left_recur' to the difference.
115         # - otherwise set it to just the discount amount.
116         # if it's a flat amount discount for other than one month:
117         # - skip the discount. unsure, leaving it alone for now.
118
119         next unless $discount->setup;
120
121         $months = 0; # never count a setup discount as a month of discount
122                      # (the recur discount in the same month should do it)
123
124         if ( $discount->percent > 0 ) {
125             $amount = $discount->percent * $param->{'setup_charge'} / 100;
126         } elsif ( $discount->amount > 0 ) {
127             # apply the discount amount, up to a maximum of the setup charge
128             $amount = min($discount->amount, $param->{'setup_charge'});
129             $discount_left = sprintf('%.2f', $discount->amount - $amount);
130             # transfer remainder of discount, if any, to recur
131             $param->{'discount_left_recur'}{$discount->discountnum} = $discount_left;
132         } 
133
134     } else {
135       
136       # we are calculating a recurring fee discount. estimate the recurring
137       # fee. Note we use $months here rather than $chg_months so that if the
138       # remaining discount amount is for less time than the package period,
139       # the "estimated recurring fee" is only for as long as the discount
140       # lasts.
141
142       my $recur_charge = $br * $months / $self->freq;
143       # round this, because the real recur charge is rounded
144       $recur_charge = sprintf('%.2f', $recur_charge);
145
146       # if it's a percentage discount, calculate it based on that estimate.
147       # otherwise use the flat amount.
148       
149       if ( $discount->percent > 0 ) {
150         $amount = $recur_charge * $discount->percent / 100;
151       } elsif ( $discount->amount > 0
152                 and $cust_pkg->pkgpart == $param->{'real_pkgpart'} ) {
153         $amount = $discount->amount * $months;
154       }
155
156       if ( exists $param->{'discount_left_recur'}{$discount->discountnum} ) {
157         # there is a discount_left_recur entry for this discountnum, so this
158         # is the second (recur) pass on the discount.  use up transferred
159         # remainder of discount from setup.
160         #
161         # note that discount_left_recur can now be zero.
162         $amount = $param->{'discount_left_recur'}{$discount->discountnum};
163         $param->{'discount_left_recur'}{$discount->discountnum} = 0;
164         $months = 1; # XXX really? not $chg_months?
165       }
166       #elsif (    $discount->setup
167       #          && ($discount->months || 0) == 1
168       #          && $discount->amount > 0
169       #        ) {
170       #    next;
171       #
172       #    RT #11512: bugfix to prevent applying flat discount to both setup
173       #    and recur. The original implementation ignored discount_left_recur
174       #    if it was zero, so if the setup fee used up the entire flat 
175       #    discount, the recurring charge would get to use the entire flat
176       #    discount also. This bugfix was a kludge. Instead, we now allow
177       #    discount_left_recur to be zero in that case, and then the available
178       #    recur discount is zero. 
179       #}
180
181       # transfer remainder of discount, if any, to setup
182       # this is used when the recur phase wants to add a setup fee
183       # (prorate_defer_bill): the "discount_left_setup" amount will
184       # be subtracted in _make_lines.
185       if ( $discount->setup && $discount->amount > 0
186           && ($discount->months || 0) != 1
187          )
188       {
189         # $amount is no longer permonth at this point! correct. very good.
190         $discount_left = $amount - $recur_charge; # backward, as above
191         if ( $discount_left > 0 ) {
192           $amount = $recur_charge;
193           $param->{'discount_left_setup'}{$discount->discountnum} = 
194             0 - $discount_left;
195         }
196       }
197
198       # cap the discount amount at the recur charge
199       $amount = min($amount, $recur_charge);
200
201       # if this is the base pkgpart, schedule increment_months_used to run at
202       # the end of billing. (addon packages haven't been calculated yet, so
203       # don't let the discount expire during the billing process. RT#17045.)
204       if ( $cust_pkg->pkgpart == $param->{'real_pkgpart'} ) {
205         push @{ $param->{precommit_hooks} }, sub {
206           my $error = $cust_pkg_discount->increment_months_used($months);
207           die "error discounting: $error" if $error;
208         };
209       }
210
211     }
212
213     $amount = sprintf('%.2f', $amount + 0.00000001 ); #so 1.005 rounds to 1.01
214
215     next unless $amount > 0;
216
217     #record details in cust_bill_pkg_discount
218     my $cust_bill_pkg_discount = new FS::cust_bill_pkg_discount {
219       'pkgdiscountnum' => $cust_pkg_discount->pkgdiscountnum,
220       'amount'         => $amount,
221       'months'         => $months,
222       # XXX should have a 'setuprecur' (and on 4.x, it does)
223     };
224     push @{ $param->{'discounts'} }, $cust_bill_pkg_discount;
225     $tot_discount += $amount;
226
227   }
228
229   sprintf('%.2f', $tot_discount);
230 }
231
232 1;