agent commission schedules for consecutive invoices, #71217
[freeside.git] / FS / FS / part_event / Action / bill_agent_credit_schedule.pm
1 package FS::part_event::Action::bill_agent_credit_schedule;
2
3 use base qw( FS::part_event::Action );
4 use FS::Conf;
5 use FS::cust_credit;
6 use FS::commission_schedule;
7 use Date::Format qw(time2str);
8
9 use strict;
10
11 sub description { 'Credit the agent based on a commission schedule' }
12
13 sub option_fields {
14   'schedulenum' => { 'label'        => 'Schedule',
15                      'type'         => 'select-table',
16                      'table'        => 'commission_schedule',
17                      'name_col'     => 'schedulename',
18                      'disable_empty'=> 1,
19                    },
20 }
21
22 sub eventtable_hashref {
23   { 'cust_bill' => 1 };
24 }
25
26 our $date_format;
27
28 sub do_action {
29   my( $self, $cust_bill, $cust_event ) = @_;
30
31   $date_format ||= FS::Conf->new->config('date_format') || '%x';
32
33   my $cust_main = $self->cust_main($cust_bill);
34   my $agent = $cust_main->agent;
35   return "No customer record for agent ". $agent->agent
36     unless $agent->agent_custnum;
37
38   my $agent_cust_main = $agent->agent_cust_main;
39
40   my $schedulenum = $self->option('schedulenum')
41     or return "no commission schedule selected";
42   my $schedule = FS::commission_schedule->by_key($schedulenum)
43     or return "commission schedule #$schedulenum not found";
44     # commission_schedule::delete tries to prevent this, but just in case
45
46   my $amount = $schedule->calc_credit($cust_bill)
47     or return;
48
49   my $reasonnum = $schedule->reasonnum;
50
51   #XXX shouldn't do this here, it's a localization problem.
52   # credits with commission_invnum should know how to display it as part
53   # of invoice rendering.
54   my $desc = 'from invoice #'. $cust_bill->display_invnum .
55              ' ('. time2str($date_format, $cust_bill->_date) . ')';
56              # could also show custnum and pkgnums here?
57   my $cust_credit = FS::cust_credit->new({
58     'custnum'             => $agent_cust_main->custnum,
59     'reasonnum'           => $reasonnum,
60     'amount'              => $amount,
61     'eventnum'            => $cust_event->eventnum,
62     'addlinfo'            => $desc,
63     'commission_agentnum' => $cust_main->agentnum,
64     'commission_invnum'   => $cust_bill->invnum,
65   });
66   my $error = $cust_credit->insert;
67   die "Error crediting customer ". $agent_cust_main->custnum.
68       " for agent commission: $error"
69     if $error;
70
71   #return $warning; # currently don't get warnings here
72   return;
73
74 }
75
76 1;