discount_Mixin
[freeside.git] / FS / FS / part_pkg / prorate_Mixin.pm
1 package FS::part_pkg::prorate_Mixin;
2
3 use strict;
4 use vars qw(@ISA %info);
5 use Time::Local qw(timelocal);
6
7 @ISA = qw(FS::part_pkg);
8 %info = ( 
9   'disabled'  => 1,
10 );
11
12 =head1 NAME
13
14 FS::part_pkg::prorate_Mixin - Mixin class for part_pkg:: classes that 
15 need to prorate partial months
16
17 =head1 SYNOPSIS
18
19 package FS::part_pkg::...;
20 use base qw( FS::part_pkg::prorate_Mixin );
21
22 sub calc_recur {
23   ...
24   if( conditions that trigger prorate ) {
25     # sets $$sdate and $param->{'months'}, returns the prorated charge
26     $charges = $self->calc_prorate($cust_pkg, $sdate, $param, $cutoff_day);
27   } 
28   ...
29 }
30
31 =head METHODS
32
33 =item calc_prorate CUST_PKG
34
35 Takes all the arguments of calc_recur, followed by a day of the month 
36 to prorate to.  Calculates a prorated charge from the $sdate to that day, 
37 and sets the $sdate and $param->{months} accordingly.
38
39 Options:
40 - recur_fee: The charge to use for a complete billing period.
41 - add_full_period: Bill for the time up to the prorate day plus one full
42 billing period after that.
43 - prorate_round_day: Round the current time to the nearest full day, 
44 instead of using the exact time.
45
46 =cut
47
48 sub calc_prorate {
49   my $self  = shift;
50   my ($cust_pkg, $sdate, $details, $param, $cutoff_day) = @_;
51  
52   my $charge = $self->option('recur_fee',1) || 0;
53   if($cutoff_day) {
54     # only works for freq >= 1 month; probably can't be fixed
55     my $mnow = $$sdate;
56     my ($sec, $min, $hour, $mday, $mon, $year) = (localtime($mnow))[0..5];
57     if( $self->option('prorate_round_day',1) ) {
58       $mday++ if $hour >= 12;
59       $mnow = timelocal(0,0,0,$mday,$mon,$year);
60     }
61     my $mend;
62     my $mstart;
63     if ( $mday >= $cutoff_day ) {
64       $mend = 
65         timelocal(0,0,0,$cutoff_day,$mon == 11 ? 0 : $mon + 1,$year+($mon==11));
66       $mstart =
67         timelocal(0,0,0,$cutoff_day,$mon,$year);
68     }
69     else {
70       $mend = 
71         timelocal(0,0,0,$cutoff_day,$mon,$year);
72       $mstart = 
73         timelocal(0,0,0,$cutoff_day,$mon == 0 ? 11 : $mon - 1,$year-($mon==11));
74     }
75    
76     # next bill date will be figured as $$sdate + one period
77     $$sdate = $mstart;
78
79     my $permonth = $charge / $self->freq;
80     my $months = ( ( $self->freq - 1 ) + ($mend-$mnow) / ($mend-$mstart) );
81
82     if ( $self->option('add_full_period',1) ) {
83       # charge a full period in addition to the partial month
84       $months += $self->freq;
85       $$sdate = $self->add_freq($mstart);
86     }
87
88     $param->{'months'} = $months;
89     $charge = sprintf('%.2f', $permonth * $months);
90   }
91   return $charge;
92 }
93
94 1;