Merge remote-tracking branch 'upstream/master'
[freeside.git] / FS / FS / sales.pm
1 package FS::sales;
2 use base qw( FS::Agent_Mixin FS::Record );
3
4 use strict;
5 use FS::Record qw( qsearch qsearchs );
6 use FS::agent;
7 use FS::cust_main;
8 use FS::cust_bill_pkg;
9 use FS::cust_credit;
10
11 =head1 NAME
12
13 FS::sales - Object methods for sales records
14
15 =head1 SYNOPSIS
16
17   use FS::sales;
18
19   $record = new FS::sales \%hash;
20   $record = new FS::sales { 'column' => 'value' };
21
22   $error = $record->insert;
23
24   $error = $new_record->replace($old_record);
25
26   $error = $record->delete;
27
28   $error = $record->check;
29
30 =head1 DESCRIPTION
31
32 An FS::sales object represents a sales person.  FS::sales inherits from
33 FS::Record.  The following fields are currently supported:
34
35 =over 4
36
37 =item salesnum
38
39 primary key
40
41 =item agentnum
42
43 agentnum
44
45 =item disabled
46
47 disabled
48
49
50 =back
51
52 =head1 METHODS
53
54 =over 4
55
56 =item new HASHREF
57
58 Creates a new sales person.  To add the sales person to the database, see
59 L<"insert">.
60
61 Note that this stores the hash reference, not a distinct copy of the hash it
62 points to.  You can ask the object for a copy with the I<hash> method.
63
64 =cut
65
66 # the new method can be inherited from FS::Record, if a table method is defined
67
68 sub table { 'sales'; }
69
70 =item insert
71
72 Adds this record to the database.  If there is an error, returns the error,
73 otherwise returns false.
74
75 =cut
76
77 # the insert method can be inherited from FS::Record
78
79 =item delete
80
81 Delete this record from the database.
82
83 =cut
84
85 # the delete method can be inherited from FS::Record
86
87 =item replace OLD_RECORD
88
89 Replaces the OLD_RECORD with this one in the database.  If there is an error,
90 returns the error, otherwise returns false.
91
92 =cut
93
94 # the replace method can be inherited from FS::Record
95
96 =item check
97
98 Checks all fields to make sure this is a valid sales person.  If there is
99 an error, returns the error, otherwise returns false.  Called by the insert
100 and replace methods.
101
102 =cut
103
104 # the check method should currently be supplied - FS::Record contains some
105 # data checking routines
106
107 sub check {
108   my $self = shift;
109
110   my $error = 
111     $self->ut_numbern('salesnum')
112     || $self->ut_text('salesperson')
113     || $self->ut_foreign_key('agentnum', 'agent', 'agentnum')
114     || $self->ut_foreign_keyn('sales_custnum', 'cust_main', 'custnum')
115     || $self->ut_enum('disabled', [ '', 'Y' ])
116   ;
117   return $error if $error;
118
119   $self->SUPER::check;
120 }
121
122 =item sales_cust_main
123
124 Returns the FS::cust_main object (see L<FS::cust_main>), if any, for this
125 sales person.
126
127 =cut
128
129 sub sales_cust_main {
130   my $self = shift;
131   qsearchs( 'cust_main', { 'custnum' => $self->sales_custnum } );
132 }
133
134 =item cust_bill_pkg START END OPTIONS
135
136 Returns the package line items (see L<FS::cust_bill_pkg>) for which this 
137 sales person could receive commission.
138
139 START and END are an optional date range to limit the results.
140
141 OPTIONS may contain:
142 - I<cust_main_sales>: if this is a true value, sales of packages that have no
143 package sales person will be included if this is their customer sales person.
144 - I<classnum>: limit to this package classnum.
145 - I<paid>: limit to sales that have no unpaid balance.
146
147 =cut
148
149 sub cust_bill_pkg_search {
150   my( $self, $sdate, $edate, %search ) = @_;
151
152   my $cmp_salesnum = delete $search{'cust_main_sales'}
153                        ? ' COALESCE( cust_pkg.salesnum, cust_main.salesnum )'
154                        : ' cust_pkg.salesnum ';
155
156   my $salesnum = $self->salesnum;
157   die "bad salesnum" unless $salesnum =~ /^(\d+)$/;
158   my @where = ( "$cmp_salesnum    = $salesnum",
159                 "sales_pkg_class.salesnum = $salesnum"
160               );
161   push @where, "cust_bill._date >= $sdate" if $sdate;
162   push @where, "cust_bill._date  < $edate" if $edate;
163
164   my $classnum_sql = '';
165   if ( exists( $search{'classnum'}  ) ) {
166     my $classnum = $search{'classnum'} || '';
167     die "bad classnum" unless $classnum =~ /^(\d*)$/;
168
169     push @where,
170       "part_pkg.classnum ". ( $classnum ? " = $classnum " : ' IS NULL ' );
171   }
172
173   # sales_pkg_class number-of-months limit, grr
174   # (we should be able to just check for the cust_event record from the 
175   # commission credit, but the report is supposed to act as a check on that)
176   #
177   # Pg-specific, of course
178   my $setup_date = 'TO_TIMESTAMP( cust_pkg.setup )';
179   my $interval = "(sales_pkg_class.commission_duration || ' months')::interval";
180   my $charge_date = 'TO_TIMESTAMP( cust_bill._date )';
181   push @where, "CASE WHEN sales_pkg_class.commission_duration IS NOT NULL ".
182                "THEN $charge_date < $setup_date + $interval ".
183                "ELSE TRUE END";
184
185   if ( $search{'paid'} ) {
186     push @where, FS::cust_bill_pkg->owed_sql . ' <= 0.005';
187   }
188
189   my $extra_sql = "WHERE ".join(' AND ', map {"( $_ )"} @where);
190
191   { 'table'     => 'cust_bill_pkg',
192     'select'    => 'cust_bill_pkg.*',
193     'addl_from' => ' LEFT JOIN cust_bill USING ( invnum ) '.
194                    ' LEFT JOIN cust_pkg  USING ( pkgnum ) '.
195                    ' LEFT JOIN part_pkg  USING ( pkgpart ) '.
196                    ' LEFT JOIN cust_main ON ( cust_pkg.custnum = cust_main.custnum )'.
197                    ' JOIN sales_pkg_class ON ( '.
198                    ' COALESCE( sales_pkg_class.classnum, 0) = COALESCE( part_pkg.classnum, 0) )',
199     'extra_sql' => $extra_sql,
200  };
201 }
202
203 sub cust_bill_pkg {
204   my $self = shift;
205   qsearch( $self->cust_bill_pkg_search(@_) )
206 }
207
208 sub cust_credit {
209   my( $self, $sdate, $edate, %search ) = @_;
210
211   $search{'hashref'}->{'commission_salesnum'} = $self->salesnum;
212
213   my $classnum_sql = '';
214   if ( exists($search{'commission_classnum'}) ) {
215     my $classnum = delete($search{'commission_classnum'});
216     $classnum_sql = " AND part_pkg.classnum ". ( $classnum ? " = $classnum"
217                                                            : " IS NULL "    );
218
219     $search{'addl_from'} .=
220       ' LEFT JOIN cust_pkg ON ( commission_pkgnum = cust_pkg.pkgnum ) '.
221       ' LEFT JOIN part_pkg USING ( pkgpart ) ';
222   }
223
224   qsearch({ 'table'     => 'cust_credit',
225             'extra_sql' => " AND cust_credit._date >= $sdate ".
226                            " AND cust_credit._date  < $edate ".
227                            $classnum_sql,
228             %search,
229          });
230 }
231
232 =back
233
234 =head1 BUGS
235
236 =head1 SEE ALSO
237
238 L<FS::Record>, schema.html from the base documentation.
239
240 =cut
241
242 1;
243