Merge branch 'master' of git.freeside.biz:/home/git/freeside
[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   if ( $param->{freq_override} ) {
54     # When a customer pays for more than one month at a time to receive a 
55     # term discount, freq_override is set to the number of months.
56     my $real_part_pkg = new FS::part_pkg { $self->hash };
57     $real_part_pkg->pkgpart($param->{real_pkgpart} || $self->pkgpart);
58     # Find a discount with that duration...
59     my @discount = grep { $_->months == $param->{freq_override} }
60                     map { $_->discount } $real_part_pkg->part_pkg_discount;
61     my $discount = shift @discount;
62     # and default to bill that many months at once.
63     $param->{months} = $param->{freq_override} unless $param->{months};
64     my $error;
65     if ($discount) {
66       # Then set the cust_pkg discount.
67       if ($discount->months == $param->{months}) {
68         $cust_pkg->discountnum($discount->discountnum);
69         $error = $cust_pkg->insert_discount;
70       } else {
71         $cust_pkg->discountnum(-1);
72         foreach ( qw( amount percent months ) ) {
73           my $method = "discountnum_$_";
74           $cust_pkg->$method($discount->$_);
75         }
76         $error = $cust_pkg->insert_discount;
77       }
78       die "error discounting using part_pkg_discount: $error" if $error;
79     }
80   }
81
82   my @cust_pkg_discount = $cust_pkg->cust_pkg_discount_active;
83   foreach my $cust_pkg_discount ( @cust_pkg_discount ) {
84     my $discount_left;
85     my $discount = $cust_pkg_discount->discount;
86     #UI enforces one or the other (for now?  probably for good)
87     # $chg_months: the number of months we are charging recur for
88     # $months: $chg_months or the months left on the discount, whchever is less
89
90     my $chg_months = $cust_pkg->part_pkg->freq || 1;
91     if ( defined($param->{'months'}) ) { # then override
92       $chg_months = $param->{'months'};
93     }
94
95     my $months = $chg_months;
96     if ( $discount->months ) {
97       $months = min( $chg_months,
98                      $discount->months - $cust_pkg_discount->months_used );
99     }
100
101     # $amount is now the (estimated) discount amount on the recurring charge.
102     # if it's a percent discount, that's base recur * percentage.
103
104     my $amount = 0;
105
106     if (defined $param->{'setup_charge'}) {
107
108         # we are calculating the setup discount.
109         # if this discount doesn't apply to setup fees, skip it.
110         # if it's a percent discount, set $amount = percent * setup_charge.
111         # if it's a flat amount discount for one month:
112         # - if the discount amount > setup_charge, then set it to setup_charge,
113         #   and set 'discount_left_recur' to the difference.
114         # - otherwise set it to just the discount amount.
115         # if it's a flat amount discount for other than one month:
116         # - skip the discount. unsure, leaving it alone for now.
117
118         next unless $discount->setup;
119
120         $months = 0; # never count a setup discount as a month of discount
121                      # (the recur discount in the same month should do it)
122
123         if ( $discount->percent > 0 ) {
124             $amount = $discount->percent * $param->{'setup_charge'} / 100;
125         } elsif ( $discount->amount > 0 && ($discount->months || 0) == 1) {
126             # apply the discount amount, up to a maximum of the setup charge
127             $amount = min($discount->amount, $param->{'setup_charge'});
128             $discount_left = sprintf('%.2f', $discount->amount - $amount);
129             # transfer remainder of discount, if any, to recur
130             $param->{'discount_left_recur'}{$discount->discountnum} = $discount_left;
131         } else {
132           # I guess we don't allow multiple-month flat amount discounts to
133           # apply to setup?
134             next; 
135         }
136
137     } else {
138       
139       # we are calculating a recurring fee discount. estimate the recurring
140       # fee:
141       # XXX it would be more accurate for calc_recur to just _tell us_ what
142       # it's going to charge
143
144       my $recur_charge = $br * ($cust_pkg->quantity || 1) * $chg_months / $self->freq;
145       # round this, because the real recur charge is rounded
146       $recur_charge = sprintf('%.2f', $recur_charge);
147
148       # if it's a percentage discount, calculate it based on that estimate.
149       # otherwise use the flat amount.
150       
151       if ( $discount->percent > 0 ) {
152         $amount = $recur_charge * $discount->percent / 100;
153       } elsif ( $discount->amount > 0
154                 and $cust_pkg->pkgpart == $param->{'real_pkgpart'} ) {
155         $amount = $discount->amount * $months;
156       }
157
158       if ( exists $param->{'discount_left_recur'}{$discount->discountnum} ) {
159         # there is a discount_left_recur entry for this discountnum, so this
160         # is the second (recur) pass on the discount.  use up transferred
161         # remainder of discount from setup.
162         #
163         # note that discount_left_recur can now be zero.
164         $amount = $param->{'discount_left_recur'}{$discount->discountnum};
165         $param->{'discount_left_recur'}{$discount->discountnum} = 0;
166         $months = 1; # XXX really? not $chg_months?
167       }
168       #elsif (    $discount->setup
169       #          && ($discount->months || 0) == 1
170       #          && $discount->amount > 0
171       #        ) {
172       #    next;
173       #
174       #    RT #11512: bugfix to prevent applying flat discount to both setup
175       #    and recur. The original implementation ignored discount_left_recur
176       #    if it was zero, so if the setup fee used up the entire flat 
177       #    discount, the recurring charge would get to use the entire flat
178       #    discount also. This bugfix was a kludge. Instead, we now allow
179       #    discount_left_recur to be zero in that case, and then the available
180       #    recur discount is zero. 
181       #}
182
183       # transfer remainder of discount, if any, to setup
184       # this is used when the recur phase wants to add a setup fee
185       # (prorate_defer_bill): the "discount_left_setup" amount will
186       # be subtracted in _make_lines.
187       if ( $discount->setup && $discount->amount > 0
188           && ($discount->months || 0) != 1
189          )
190       {
191         # $amount is no longer permonth at this point! correct. very good.
192         $discount_left = $amount - $recur_charge; # backward, as above
193         if ( $discount_left > 0 ) {
194           $amount = $recur_charge;
195           $param->{'discount_left_setup'}{$discount->discountnum} = 
196             0 - $discount_left;
197         }
198       }
199
200       # cap the discount amount at the recur charge
201       $amount = min($amount, $recur_charge);
202
203       # if this is the base pkgpart, schedule increment_months_used to run at
204       # the end of billing. (addon packages haven't been calculated yet, so
205       # don't let the discount expire during the billing process. RT#17045.)
206       if ( $cust_pkg->pkgpart == $param->{'real_pkgpart'} ) {
207         push @{ $param->{precommit_hooks} }, sub {
208           my $error = $cust_pkg_discount->increment_months_used($months);
209           die "error discounting: $error" if $error;
210         };
211       }
212
213     }
214
215     $amount = sprintf('%.2f', $amount + 0.00000001 ); #so 1.005 rounds to 1.01
216
217     next unless $amount > 0;
218
219     #record details in cust_bill_pkg_discount
220     my $cust_bill_pkg_discount = new FS::cust_bill_pkg_discount {
221       'pkgdiscountnum' => $cust_pkg_discount->pkgdiscountnum,
222       'amount'         => $amount,
223       'months'         => $months,
224       # XXX should have a 'setuprecur'
225     };
226     push @{ $param->{'discounts'} }, $cust_bill_pkg_discount;
227     $tot_discount += $amount;
228
229   }
230
231   sprintf('%.2f', $tot_discount);
232 }
233
234 1;