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