add customer fields option with agent, display_custnum, status and name, RT#73721
[freeside.git] / FS / FS / TaxEngine.pm
1 package FS::TaxEngine;
2
3 use strict;
4 use vars qw( $DEBUG );
5 use FS::Conf;
6 use FS::Record qw(qsearch qsearchs);
7
8 $DEBUG = 0;
9
10 =head1 NAME
11
12 FS::TaxEngine - Base class for tax calculation engines.
13
14 =head1 USAGE
15
16 1. At the start of creating an invoice, create an FS::TaxEngine object.
17 2. Each time a sale item is added to the invoice, call L</add_sale> on the 
18    TaxEngine.
19 3. Set the "pending" flag on the invoice.
20 4. Insert the invoice and its line items.
21
22 - If the TaxEngine is "batch" style (Billsoft):
23 5. After creating all invoices for the day, call 
24    FS::TaxEngine::process_tax_batch.  This will create the tax items for
25    all of the pending invoices, clear the "pending" flag, and call 
26    L<FS::cust_main::Billing/collect> on each of the billed customers.
27
28 - If not (the internal tax system, CCH):
29 5. After adding all sale items, call L</calculate_taxes> on the TaxEngine to
30    produce a list of tax line items.
31 6. Append the tax line items to the invoice.
32 7. Update the invoice with the new charged amount and clear the pending flag.
33
34 =head1 CLASS METHODS
35
36 =over 4
37
38 =item class
39
40 Returns the class name for tax engines, according to the 'tax_data_vendor'
41 configuration setting.
42
43 =cut
44
45 sub class {
46   my $conf = FS::Conf->new;
47   my $subclass = $conf->config('tax_data_vendor') || 'internal';
48   my $class = "FS::TaxEngine::$subclass";
49   local $@;
50   eval "use $class";
51   die "couldn't load $class: $@\n" if $@;
52
53   $class;
54 }
55
56 =item new 'cust_main' => CUST_MAIN, 'invoice_time' => TIME, OPTIONS...
57
58 Creates an L<FS::TaxEngine> object.  The subclass will be chosen by the 
59 'tax_data_vendor' configuration setting.
60
61 CUST_MAIN and TIME are required.  OPTIONS can include:
62
63 "cancel" => 1 to indicate that the package is being billed on cancellation.
64
65 "estimate" => 1 to indicate that this calculation is for tax estimation,
66 and isn't an actual sale invoice, in case that matters.
67
68 =cut
69
70 sub new {
71   my $class = shift;
72   my %opt = @_;
73   my $conf = FS::Conf->new;
74   if ($class eq 'FS::TaxEngine') {
75     $class = $class->class;
76   }
77   my $self = { items => [], taxes => {}, conf => $conf, %opt };
78   bless $self, $class;
79 }
80
81 =item info
82
83 Returns a hashref of metadata about this tax method, including:
84 - batch: whether this is a batch-style engine (requires different usage)
85 - override: whether this engine uses tax overrides
86 - manual_tax_location: whether this engine requires the user to select a "tax
87   location" separate from the address/city/state/zip fields
88 - rate_table: the table that stores the tax rates
89   (the 'taxline' method of that class will be used to calculate line-item
90    taxes)
91 - link_table: the table that links L<FS::cust_bill_pkg> records for taxes
92   to the C<rate_table> entry that generated them, and to the item they 
93   represent tax on.
94
95 =back
96
97 =head1 METHODS
98
99 =over 4
100
101 =item add_sale CUST_BILL_PKG
102
103 Adds the CUST_BILL_PKG object as a taxable sale on this invoice.
104
105 =item calculate_taxes INVOICE
106
107 Calculates the taxes on the taxable sales and returns a list of 
108 L<FS::cust_bill_pkg> objects to add to the invoice.  The base implementation
109 is to call L</make_taxlines> to produce a list of "raw" tax line items, 
110 then L</consolidate_taxlines> to combine those with the same itemdesc.
111
112 If this fails, it will throw an exception. (Accordingly it should not trap
113 exceptions from internal methods that it calls, except to translate error 
114 messages into a more meaningful form.) If it succeeds, it MUST return an
115 arrayref (even if the arrayref is empty).
116
117 =cut
118
119 sub calculate_taxes {
120   my $self = shift;
121   my $cust_bill = shift;
122
123   my @raw_taxlines = $self->make_taxlines($cust_bill);
124   if ( !@raw_taxlines ) {
125     return;
126   } elsif ( !ref $raw_taxlines[0] ) { # error message
127     return $raw_taxlines[0];
128   }
129
130   my @real_taxlines = $self->consolidate_taxlines(@raw_taxlines);
131
132   if ( $cust_bill and $cust_bill->get('invnum') ) {
133     $_->set('invnum', $cust_bill->get('invnum')) foreach @real_taxlines;
134   }
135   return \@real_taxlines;
136 }
137
138 sub make_taxlines {
139   # only used by FS::TaxEngine::internal; should just move there
140   my $self = shift;
141   my $conf = $self->{conf};
142
143   my $cust_bill = shift;
144
145   my @raw_taxlines;
146
147   # For each distinct tax rate definition, calculate the tax and exemptions.
148   foreach my $taxnum ( keys %{ $self->{taxes} } ) {
149
150     my $taxables = $self->{taxes}{$taxnum};
151     my $tax_object = shift @$taxables;
152     # $tax_object is a cust_main_county or tax_rate 
153     # (with billpkgnum, pkgnum, locationnum set)
154     # the rest of @{ $taxlisthash->{$tax} } is cust_bill_pkg component objects
155     # (setup, recurring, usage classes)
156
157     my @taxlines = $self->taxline('tax' => $tax_object, 'sales' => $taxables);
158     # taxline methods are now required to return the link records alone.
159     # Consolidation will take care of the rest.
160     next if !@taxlines;
161     die $taxlines[0] unless ref($taxlines[0]);
162
163     push @raw_taxlines, @taxlines;
164
165   } #foreach $taxnum
166
167   return @raw_taxlines;
168 }
169
170 sub consolidate_taxlines {
171
172   my $self = shift;
173   my $conf = $self->{conf};
174
175   my @raw_taxlines = @_;
176   return if !@raw_taxlines; # shouldn't even be here
177
178   my @tax_line_items;
179
180   # keys are tax names (as printed on invoices / itemdesc )
181   # values are arrayrefs of tax links ("raw taxlines")
182   my %taxname;
183   # collate these by itemdesc
184   foreach my $taxline (@raw_taxlines) {
185     my $taxname = $taxline->taxname;
186     $taxname{$taxname} ||= [];
187     push @{ $taxname{$taxname} }, $taxline;
188   }
189
190   # keys are taxnums
191   # values are (cumulative) amounts
192   my %tax_amount;
193
194   my $link_table = $raw_taxlines[0]->table;
195
196   # Preconstruct cust_bill_pkg objects that will become the "final"
197   # taxlines for each name, so that we can reference them.
198   # (keys are taxnames)
199   my %real_taxline_named = map {
200     $_ => FS::cust_bill_pkg->new({
201         'pkgnum'    => 0,
202         'recur'     => 0,
203         'sdate'     => '',
204         'edate'     => '',
205         'itemdesc'  => $_
206     })
207   } keys %taxname;
208
209   # For each distinct tax name (the values set as $taxline->itemdesc),
210   # create a consolidated tax item with the total amount and all the links
211   # of all tax items that share that name.
212   foreach my $taxname ( keys %taxname ) {
213     my $tax_links = $taxname{$taxname};
214     my $tax_cust_bill_pkg = $real_taxline_named{$taxname};
215     $tax_cust_bill_pkg->set( $link_table => $tax_links );
216
217     my $tax_total = 0;
218     warn "adding $taxname\n" if $DEBUG > 1;
219
220     foreach my $link ( @$tax_links ) {
221       # then we need to transfer the amount and the links from the
222       # line item to the new one we're creating.
223       $tax_total += $link->amount;
224       $link->set('tax_cust_bill_pkg', $tax_cust_bill_pkg);
225
226       # if the link represents tax on tax, also fix its taxable pointer
227       # to point to the "final" taxline
228       my $taxable_cust_bill_pkg = $link->get('taxable_cust_bill_pkg');
229       if ( $taxable_cust_bill_pkg and
230            my $other_taxname = $taxable_cust_bill_pkg->itemdesc) {
231         $link->set('taxable_cust_bill_pkg',
232           $real_taxline_named{$other_taxname}
233         );
234       }
235
236     } # foreach $link
237     next unless $tax_total;
238
239     # we should really neverround this up...I guess it's okay if taxline 
240     # already returns amounts with 2 decimal places
241     $tax_total = sprintf('%.2f', $tax_total );
242     $tax_cust_bill_pkg->set('setup', $tax_total);
243
244     my $pkg_category = qsearchs( 'pkg_category', { 'categoryname' => $taxname,
245                                                    'disabled'     => '',
246                                                  },
247                                );
248
249     my @display = ();
250     if ( $pkg_category and
251          $conf->config('invoice_latexsummary') ||
252          $conf->config('invoice_htmlsummary')
253        )
254     {
255       my %hash = (  'section' => $pkg_category->categoryname );
256       push @display, new FS::cust_bill_pkg_display { type => 'S', %hash };
257     }
258     $tax_cust_bill_pkg->set('display', \@display);
259
260     push @tax_line_items, $tax_cust_bill_pkg;
261   }
262
263   @tax_line_items;
264 }
265
266 =head1 CLASS METHODS
267
268 =item cust_tax_locations LOCATION
269
270 Given an L<FS::cust_location> object (or a hash of location fields), 
271 returns a list of all tax jurisdiction locations that could possibly 
272 match it.  This is meant for interactive use: the location editing UI
273 displays the candidate locations to the user so they can choose the 
274 best match.
275
276 =cut
277
278 sub cust_tax_locations {
279   ();
280 } # shouldn't even get called unless info->{manual_tax_location} is true
281
282 =item add_taxproduct DESCRIPTION
283
284 If the module allows manually adding tax products (categories of taxable
285 items/services), this method will be called to do it. (If not, the UI in
286 browse/part_pkg_taxproduct/* should prevent adding an unlisted tax product.
287 That is the default behavior, so by default this method simply fails.)
288
289 DESCRIPTION is the contents of the taxproduct_description form input, which
290 will normally be filled in by browse/part_pkg_taxproduct/*.
291
292 Must return the newly inserted part_pkg_taxproduct object on success, or
293 a string on failure.
294
295 =cut
296
297 sub add_taxproduct {
298   my $class = shift;
299   "$class does not allow manually adding taxproducts";
300 }
301
302 =item transfer_batch (batch-style only)
303
304 Submits the pending transaction batch for processing, receives the 
305 results, and appends the calculated taxes to all invoices that were 
306 included in the batch.  Then clears their pending flags, and queues
307 a job to run C<FS::cust_main::Billing::collect> on each affected
308 customer.
309
310 =back
311
312 =cut
313
314 1;