summaryrefslogtreecommitdiff
path: root/FS/FS/commission_schedule.pm
blob: 375386c33b9b0ac14e83524c2ebb3ec9dd57572d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
package FS::commission_schedule;
use base qw( FS::o2m_Common FS::Record );

use strict;
use FS::Record qw( qsearch qsearchs );
use FS::commission_rate;
use Tie::IxHash;

tie our %basis_options, 'Tie::IxHash', (
  setuprecur    => 'Total sales',
  setup         => 'One-time and setup charges',
  recur         => 'Recurring charges',
  setup_cost    => 'Setup costs',
  recur_cost    => 'Recurring costs',
  setup_margin  => 'Setup charges minus costs',
  recur_margin_permonth => 'Monthly recurring charges minus costs',
);

=head1 NAME

FS::commission_schedule - Object methods for commission_schedule records

=head1 SYNOPSIS

  use FS::commission_schedule;

  $record = new FS::commission_schedule \%hash;
  $record = new FS::commission_schedule { 'column' => 'value' };

  $error = $record->insert;

  $error = $new_record->replace($old_record);

  $error = $record->delete;

  $error = $record->check;

=head1 DESCRIPTION

An FS::commission_schedule object represents a bundle of one or more
commission rates for invoices. FS::commission_schedule inherits from
FS::Record.  The following fields are currently supported:

=over 4

=item schedulenum - primary key

=item schedulename - descriptive name

=item reasonnum - the credit reason (L<FS::reason>) that will be assigned
to these commission credits

=item basis - for percentage credits, which component of the invoice charges
the percentage will be calculated on:
- setuprecur (total charges)
- setup
- recur
- setup_cost
- recur_cost
- setup_margin (setup - setup_cost)
- recur_margin_permonth ((recur - recur_cost) / freq)

=back

=head1 METHODS

=over 4

=item new HASHREF

Creates a new commission schedule.  To add the object to the database, see
L<"insert">.

=cut

sub table { 'commission_schedule'; }

=item insert

Adds this record to the database.  If there is an error, returns the error,
otherwise returns false.

=item delete

Delete this record from the database.

=cut

sub delete {
  my $self = shift;
  # don't allow the schedule to be removed if it's still linked to events
  if ($self->part_event) {
    return 'This schedule is still in use.'; # UI should be smarter
  }
  $self->process_o2m(
    'table'   => 'commission_rate',
    'params'  => [],
  ) || $self->delete;
}

=item replace OLD_RECORD

Replaces the OLD_RECORD with this one in the database.  If there is an error,
returns the error, otherwise returns false.

=item check

Checks all fields to make sure this is a valid record.  If there is
an error, returns the error, otherwise returns false.  Called by the insert
and replace methods.

=cut

sub check {
  my $self = shift;

  my $error = 
    $self->ut_numbern('schedulenum')
    || $self->ut_text('schedulename')
    || $self->ut_number('reasonnum')
    || $self->ut_enum('basis', [ keys %basis_options ])
  ;
  return $error if $error;

  $self->SUPER::check;
}

=item part_event

Returns a list of billing events (L<FS::part_event> objects) that pay
commission on this schedule.

=cut

sub part_event {
  my $self = shift;
  map { $_->part_event }
    qsearch('part_event_option', {
      optionname  => 'schedulenum',
      optionvalue => $self->schedulenum,
    }
  );
}

=item calc_credit INVOICE

Takes an L<FS::cust_bill> object and calculates credit on this schedule.
Returns the amount to credit. If there's no rate defined for this invoice,
returns nothing.

=cut

# Some false laziness w/ FS::part_event::Action::Mixin::credit_bill.
# this is a little different in that we calculate the credit on the whole
# invoice.

sub calc_credit {
  my $self = shift;
  my $cust_bill = shift;
  die "cust_bill record required" if !$cust_bill or !$cust_bill->custnum;
  # count invoices before or including this one
  my $cycle = FS::cust_bill->count('custnum = ? AND _date <= ?',
    $cust_bill->custnum,
    $cust_bill->_date
  );
  my $rate = qsearchs('commission_rate', {
    schedulenum => $self->schedulenum,
    cycle       => $cycle,
  });
  # we might do something with a rate that applies "after the end of the
  # schedule" (cycle = 0 or something) so that this can do commissions with
  # no end date. add that here if there's a need.
  return unless $rate;

  my $amount;
  if ( $rate->percent ) {
    my $what = $self->basis;
    my $cost = ($what =~ /_cost/ ? 1 : 0);
    my $margin = ($what =~ /_margin/ ? 1 : 0);
    my %part_pkg_cache;
    foreach my $cust_bill_pkg ( $cust_bill->cust_bill_pkg ) {

      my $charge = 0;
      next if !$cust_bill_pkg->pkgnum; # exclude taxes and fees

      my $cust_pkg = $cust_bill_pkg->cust_pkg;
      if ( $margin or $cost ) {
        # look up package costs only if we need them
        my $pkgpart = $cust_bill_pkg->pkgpart_override || $cust_pkg->pkgpart;
        my $part_pkg   = $part_pkg_cache{$pkgpart}
                     ||= FS::part_pkg->by_key($pkgpart);

        if ( $cost ) {
          $charge = $part_pkg->get($what);
        } else { # $margin
          $charge = $part_pkg->$what($cust_pkg);
        }

        $charge = ($charge || 0) * ($cust_pkg->quantity || 1);

      } else {

        if ( $what eq 'setup' ) {
          $charge = $cust_bill_pkg->get('setup');
        } elsif ( $what eq 'recur' ) {
          $charge = $cust_bill_pkg->get('recur');
        } elsif ( $what eq 'setuprecur' ) {
          $charge = $cust_bill_pkg->get('setup') +
                    $cust_bill_pkg->get('recur');
        }
      }

      $amount += ($charge * $rate->percent / 100);

    }
  } # if $rate->percent

  if ( $rate->amount ) {
    $amount += $rate->amount;
  }

  $amount = sprintf('%.2f', $amount + 0.005);
  return $amount;
}

=back

=head1 SEE ALSO

L<FS::Record>, L<FS::part_event>, L<FS::commission_rate>

=cut

1;