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