-
Notifications
You must be signed in to change notification settings - Fork 4
/
invoice.go
603 lines (535 loc) · 17 KB
/
invoice.go
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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
package bill
import (
"context"
"errors"
"fmt"
"regexp"
"github.com/invopop/gobl/cal"
"github.com/invopop/gobl/cbc"
"github.com/invopop/gobl/currency"
"github.com/invopop/gobl/internal"
"github.com/invopop/gobl/org"
"github.com/invopop/gobl/schema"
"github.com/invopop/gobl/tax"
"github.com/invopop/gobl/uuid"
"github.com/invopop/jsonschema"
"github.com/invopop/validation"
)
// Constants used to help identify invoices
const (
ShortSchemaInvoice = "bill/invoice"
)
const (
defaultTaxRemovalAccuracy uint32 = 2
)
const (
// InvoiceCodePattern defines what we expect from codes
// and series in an invoice.
InvoiceCodePattern = `^([A-Za-z0-9][A-Za-z0-9 /\._-]?)*[A-Za-z0-9]$`
)
var (
// InvoiceCodeRegexp is used to validate invoice codes and series
// to something that is compatible with most tax regimes.
InvoiceCodeRegexp = regexp.MustCompile(InvoiceCodePattern)
)
// Invoice represents a payment claim for goods or services supplied under
// conditions agreed between the supplier and the customer. In most cases
// the resulting document describes the actual financial commitment of goods
// or services ordered from the supplier.
type Invoice struct {
uuid.Identify
// Type of invoice document subject to the requirements of the local tax regime.
Type cbc.Key `json:"type" jsonschema:"title=Type" jsonschema_extras:"calculated=true"`
// Used as a prefix to group codes.
Series string `json:"series,omitempty" jsonschema:"title=Series"`
// Sequential code used to identify this invoice in tax declarations.
Code string `json:"code" jsonschema:"title=Code"`
// When the invoice was created.
IssueDate cal.Date `json:"issue_date" jsonschema:"title=Issue Date" jsonschema_extras:"calculated=true"`
// Date when the operation defined by the invoice became effective.
OperationDate *cal.Date `json:"op_date,omitempty" jsonschema:"title=Operation Date"`
// When the taxes of this invoice become accountable, if none set, the issue date is used.
ValueDate *cal.Date `json:"value_date,omitempty" jsonschema:"title=Value Date"`
// Currency for all invoice totals.
Currency currency.Code `json:"currency" jsonschema:"title=Currency" jsonschema_extras:"calculated=true"`
// Exchange rates to be used when converting the invoices monetary values into other currencies.
ExchangeRates []*currency.ExchangeRate `json:"exchange_rates,omitempty" jsonschema:"title=Exchange Rates"`
// Key information regarding previous invoices and potentially details as to why they
// were corrected.
Preceding []*Preceding `json:"preceding,omitempty" jsonschema:"title=Preceding Details"`
// Special tax configuration for billing.
Tax *Tax `json:"tax,omitempty" jsonschema:"title=Tax"`
// The taxable entity supplying the goods or services.
Supplier *org.Party `json:"supplier" jsonschema:"title=Supplier"`
// Legal entity receiving the goods or services, may be empty in certain circumstances such as simplified invoices.
Customer *org.Party `json:"customer,omitempty" jsonschema:"title=Customer"`
// List of invoice lines representing each of the items sold to the customer.
Lines []*Line `json:"lines,omitempty" jsonschema:"title=Lines"`
// Discounts or allowances applied to the complete invoice
Discounts []*Discount `json:"discounts,omitempty" jsonschema:"title=Discounts"`
// Charges or surcharges applied to the complete invoice
Charges []*Charge `json:"charges,omitempty" jsonschema:"title=Charges"`
// Expenses paid for by the supplier but invoiced directly to the customer.
Outlays []*Outlay `json:"outlays,omitempty" jsonschema:"title=Outlays"`
// Ordering details including document references and buyer or seller parties.
Ordering *Ordering `json:"ordering,omitempty" jsonschema:"title=Ordering Details"`
// Information on when, how, and to whom the invoice should be paid.
Payment *Payment `json:"payment,omitempty" jsonschema:"title=Payment Details"`
// Specific details on delivery of the goods referenced in the invoice.
Delivery *Delivery `json:"delivery,omitempty" jsonschema:"title=Delivery Details"`
// Summary of all the invoice totals, including taxes (calculated).
Totals *Totals `json:"totals" jsonschema:"title=Totals" jsonschema_extras:"calculated=true"`
// The EN 16931-1:2017 standard recognises a need to be able to attach additional
// documents to an invoice. We don't support this yet, but this is where
// it could go.
//Attachments Attachments `json:"attachments,omitempty" jsonschema:"title=Attachments"`
// Unstructured information that is relevant to the invoice, such as correction or additional
// legal details.
Notes []*cbc.Note `json:"notes,omitempty" jsonschema:"title=Notes"`
// Additional complementary objects that add relevant information to the invoice.
Complements []*schema.Object `json:"complements,omitempty" jsonschema:"title=Complements"`
// Additional semi-structured data that doesn't fit into the body of the invoice.
Meta cbc.Meta `json:"meta,omitempty" jsonschema:"title=Meta"`
}
// Validate checks to ensure the invoice is valid and contains all the information we need.
func (inv *Invoice) Validate() error {
return inv.ValidateWithContext(context.Background())
}
// ValidateWithContext checks to ensure the invoice is valid and contains all the
// information we need.
func (inv *Invoice) ValidateWithContext(ctx context.Context) error {
r := inv.TaxRegime()
if r == nil {
return errors.New("supplier: invalid or unknown tax regime")
}
ctx = r.WithContext(ctx)
err := validation.ValidateStructWithContext(ctx, inv,
validation.Field(&inv.UUID),
validation.Field(&inv.Type,
validation.Required,
isValidInvoiceType,
),
validation.Field(&inv.Series,
validation.Match(InvoiceCodeRegexp),
),
validation.Field(&inv.Code,
validation.Match(InvoiceCodeRegexp),
validation.When(
!internal.IsDraft(ctx),
validation.Required,
),
),
validation.Field(&inv.IssueDate,
cal.DateNotZero(),
),
validation.Field(&inv.OperationDate),
validation.Field(&inv.ValueDate),
validation.Field(&inv.Currency,
validation.Required,
currency.CanConvertInto(inv.ExchangeRates, r.Currency),
),
validation.Field(&inv.ExchangeRates),
validation.Field(&inv.Preceding),
validation.Field(&inv.Tax),
validation.Field(&inv.Supplier,
validation.Required,
),
validation.Field(&inv.Customer,
// Customer is not required for simplified invoices.
validation.When(
!inv.Tax.ContainsTag(tax.TagSimplified),
validation.Required,
),
),
validation.Field(&inv.Lines,
validation.Required,
),
validation.Field(&inv.Discounts),
validation.Field(&inv.Charges),
validation.Field(&inv.Outlays),
validation.Field(&inv.Ordering),
validation.Field(&inv.Payment),
validation.Field(&inv.Delivery),
validation.Field(&inv.Totals,
validation.Required,
),
validation.Field(&inv.Notes),
validation.Field(&inv.Complements),
validation.Field(&inv.Meta),
)
if err == nil {
err = r.ValidateObject(inv)
}
return err
}
// Invert effectively reverses the invoice by inverting the sign of all quantity
// or amount values. Caution should be taken when using this method as
// advances will also be inverted, while payment terms will remain the same,
// which could be confusing if no further modifications are made.
// After inverting the invoice is recalculated and any differences will raise
// an error.
func (inv *Invoice) Invert() error {
payable := inv.Totals.Payable.Invert()
for _, row := range inv.Lines {
row.Quantity = row.Quantity.Invert()
for _, d := range row.Discounts {
d.Amount = d.Amount.Invert()
}
for _, c := range row.Charges {
c.Amount = c.Amount.Invert()
}
}
for _, row := range inv.Charges {
row.Amount = row.Amount.Invert()
}
for _, row := range inv.Discounts {
row.Amount = row.Amount.Invert()
}
for _, row := range inv.Outlays {
row.Amount = row.Amount.Invert()
}
if inv.Payment != nil {
for _, row := range inv.Payment.Advances {
row.Amount = row.Amount.Invert()
}
}
inv.Totals = nil
if err := inv.Calculate(); err != nil {
return err
}
// The following check tries to ensure that any future fields do not cause
// unexpected results.
if !payable.Equals(inv.Totals.Payable) {
return fmt.Errorf("inverted invoice totals do not match %s != %s", payable.String(), inv.Totals.Payable.String())
}
return nil
}
// Empty is a convenience method that will empty all the lines and
// related rows.
func (inv *Invoice) Empty() {
inv.Lines = make([]*Line, 0)
inv.Charges = make([]*Charge, 0)
inv.Discounts = make([]*Discount, 0)
inv.Outlays = make([]*Outlay, 0)
inv.Totals = nil
inv.Payment.ResetAdvances()
}
// Calculate performs all the calculations and normalizations required for the invoice
// totals and taxes. If the original invoice only includes partial calculations, this
// will figure out what's missing.
func (inv *Invoice) Calculate() error {
if inv.Type == cbc.KeyEmpty {
inv.Type = InvoiceTypeStandard
}
if inv.Supplier == nil {
return errors.New("missing supplier")
}
if err := inv.Supplier.Calculate(); err != nil {
return fmt.Errorf("supplier: %w", err)
}
if inv.Customer != nil {
if err := inv.Customer.Calculate(); err != nil {
return fmt.Errorf("customer: %w", err)
}
}
// Preceding entries
if inv.Preceding != nil {
for _, p := range inv.Preceding {
if err := p.Calculate(); err != nil {
return err
}
}
}
if err := inv.prepareTagsAndScenarios(); err != nil {
return err
}
// Should we use the customer's identity for calculations?
tID, err := inv.determineTaxIdentity()
if err != nil {
return err
}
r := tax.RegimeFor(tID.Country)
if r == nil {
return fmt.Errorf("no tax regime for %v", tID.Country)
}
// Run Regime pre-calculations first
if err := r.CalculateObject(inv); err != nil {
return err
}
return inv.calculateWithRegime(r)
}
// RemoveIncludedTaxes is a special function that will go through all prices which may include
// the tax included in the invoice, and remove them.
//
// This method will call "Calculate" on the invoice automatically both before and after
// to ensure that the data matches.
//
// If after removing taxes the totals don't match, a rounding error will be added to the
// invoice totals. In most scenarios this shouldn't be more than a cent or two.
//
// A new invoice object is returned, leaving the original instance untouched.
func (inv *Invoice) RemoveIncludedTaxes() (*Invoice, error) {
if inv.Tax == nil || inv.Tax.PricesInclude.IsEmpty() {
return inv, nil // nothing to do!
}
if err := inv.Calculate(); err != nil {
return nil, err
}
i2 := *inv
i2.Totals = new(Totals)
i2.Lines = make([]*Line, len(inv.Lines))
for i, l := range inv.Lines {
i2.Lines[i] = l.removeIncludedTaxes(inv.Tax.PricesInclude)
}
if len(inv.Discounts) > 0 {
i2.Discounts = make([]*Discount, len(inv.Discounts))
for i, l := range inv.Discounts {
i2.Discounts[i] = l.removeIncludedTaxes(inv.Tax.PricesInclude)
}
}
if len(i2.Charges) > 0 {
i2.Charges = make([]*Charge, len(inv.Charges))
for i, l := range inv.Charges {
i2.Charges[i] = l.removeIncludedTaxes(inv.Tax.PricesInclude)
}
}
tx := *i2.Tax
tx.PricesInclude = ""
i2.Tax = &tx
if err := i2.Calculate(); err != nil {
return nil, err
}
// Account for any rounding errors that we just can't handle
if !inv.Totals.TotalWithTax.Equals(i2.Totals.TotalWithTax) {
rnd := inv.Totals.TotalWithTax.Subtract(i2.Totals.TotalWithTax)
i2.Totals.Rounding = &rnd
if err := i2.Calculate(); err != nil {
return nil, err
}
}
return &i2, nil
}
// TaxRegime determines the tax regime for the invoice based on the supplier tax
// identity.
func (inv *Invoice) TaxRegime() *tax.Regime {
return taxRegimeFor(inv.Supplier)
}
// ScenarioSummary determines a summary of the tax scenario for the invoice based on
// the document type and tax tags.
func (inv *Invoice) ScenarioSummary() *tax.ScenarioSummary {
r := inv.TaxRegime()
if r == nil {
return nil
}
return inv.scenarioSummary(r)
}
func (inv *Invoice) scenarioSummary(r *tax.Regime) *tax.ScenarioSummary {
ss := r.ScenarioSet(ShortSchemaInvoice)
if ss == nil {
return nil
}
tags := []cbc.Key{}
if inv.Tax != nil {
tags = inv.Tax.Tags
}
return ss.SummaryFor(inv.Type, tags)
}
func (inv *Invoice) prepareTagsAndScenarios() error {
r := inv.TaxRegime()
if r == nil {
return nil
}
if inv.Tax == nil {
return nil
}
// First check the tags are all valid
for _, k := range inv.Tax.Tags {
if t := r.Tag(k); t == nil {
return fmt.Errorf("invalid document tag: %v", k)
}
}
// Use the scenario summary to add any notes to the invoice
ss := inv.scenarioSummary(r)
if ss == nil {
return nil
}
for _, n := range ss.Notes {
// make sure we don't already have the same note in the invoice
var en *cbc.Note
for _, n2 := range inv.Notes {
if n.Src == n2.Src {
en = n
break
}
}
if en == nil {
inv.Notes = append(inv.Notes, n)
}
}
return nil
}
func (inv *Invoice) calculateWithRegime(r *tax.Regime) error {
// Normalize data
if inv.IssueDate.IsZero() {
inv.IssueDate = cal.TodayIn(r.TimeLocation())
}
date := inv.ValueDate
if date == nil {
date = &inv.IssueDate
}
if inv.Currency == currency.CodeEmpty {
inv.Currency = r.Currency
}
// Prepare the totals we'll need with amounts based on currency
if inv.Totals == nil {
inv.Totals = new(Totals)
}
t := inv.Totals
zero := inv.Currency.Def().Zero()
t.reset(zero)
// Lines
if err := calculateLines(r, inv.Lines, inv.Currency, inv.ExchangeRates); err != nil {
return validation.Errors{"lines": err}
}
t.Sum = calculateLineSum(inv.Lines, inv.Currency)
t.Total = t.Sum
// Discount Lines
calculateDiscounts(inv.Discounts, t.Sum, zero)
if discounts := calculateDiscountSum(inv.Discounts, zero); discounts != nil {
t.Discount = discounts
t.Total = t.Total.Subtract(*discounts)
}
// Charge Lines
calculateCharges(inv.Charges, t.Sum, zero)
if charges := calculateChargeSum(inv.Charges, zero); charges != nil {
t.Charge = charges
t.Total = t.Total.Add(*charges)
}
// Build list of taxable lines
tls := make([]tax.TaxableLine, 0)
for _, l := range inv.Lines {
tls = append(tls, l)
}
for _, l := range inv.Discounts {
tls = append(tls, l)
}
for _, l := range inv.Charges {
tls = append(tls, l)
}
// Now figure out the tax totals
var pit cbc.Code
if inv.Tax != nil && inv.Tax.PricesInclude != "" {
pit = inv.Tax.PricesInclude
}
t.Taxes = new(tax.Total)
var tags []cbc.Key
if inv.Tax != nil {
tags = inv.Tax.Tags
}
tc := &tax.TotalCalculator{
Zero: zero,
Regime: r,
Tags: tags,
Date: *date,
Lines: tls,
Includes: pit,
}
if err := tc.Calculate(t.Taxes); err != nil {
return err
}
// Remove any included taxes from the total.
ct := t.Taxes.Category(pit)
if ct != nil {
ti := ct.PreciseAmount()
t.TaxIncluded = &ti
t.Total = t.Total.Subtract(ti)
}
// Finally calculate the total with *all* the taxes.
t.Tax = t.Taxes.PreciseSum()
t.TotalWithTax = t.Total.Add(t.Tax)
t.Payable = t.TotalWithTax
if t.Rounding != nil {
// BT-144 in EN16931
t.Payable = t.Payable.Add(*t.Rounding)
}
// Outlays
t.Outlays = calculateOutlays(zero, inv.Outlays)
if t.Outlays != nil {
t.Payable = t.Payable.Add(*t.Outlays)
}
if inv.Payment != nil {
inv.Payment.calculateAdvances(zero, t.TotalWithTax)
// Deal with advances, if any
if t.Advances = inv.Payment.totalAdvance(zero); t.Advances != nil {
v := t.Payable.Subtract(*t.Advances)
t.Due = &v
}
// Calculate any due date amounts
inv.Payment.Terms.CalculateDues(zero, t.Payable)
}
t.round(zero)
// Complements
if err := calculateComplements(inv.Complements); err != nil {
return validation.Errors{"complements": err}
}
return nil
}
func calculateComplements(comps []*schema.Object) error {
for _, c := range comps {
if err := c.Calculate(); err != nil {
return err
}
}
return nil
}
func (inv *Invoice) determineTaxIdentity() (*tax.Identity, error) {
if inv.Tax != nil {
if inv.Tax.ContainsTag(tax.TagCustomerRates) {
if inv.Customer == nil {
return nil, fmt.Errorf("missing customer for %s", tax.TagCustomerRates.String())
}
if inv.Customer.TaxID == nil {
return nil, fmt.Errorf("missing customer tax ID for %s", tax.TagCustomerRates.String())
}
return inv.Customer.TaxID, nil
}
}
if inv.Supplier == nil {
return nil, errors.New("missing supplier")
}
if inv.Supplier.TaxID == nil {
return nil, errors.New("missing supplier tax ID")
}
return inv.Supplier.TaxID, nil
}
func taxRegimeFor(party *org.Party) *tax.Regime {
if party == nil {
return nil
}
tID := party.TaxID
if tID == nil {
return nil
}
return tax.RegimeFor(tID.Country)
}
// JSONSchemaExtend extends the schema with additional property details
func (Invoice) JSONSchemaExtend(schema *jsonschema.Schema) {
props := schema.Properties
if prop, ok := props.Get("series"); ok {
prop.Pattern = InvoiceCodePattern
}
if prop, ok := props.Get("code"); ok {
prop.Pattern = InvoiceCodePattern
}
// Extend type list
if its, ok := props.Get("type"); ok {
its.OneOf = make([]*jsonschema.Schema, len(InvoiceTypes))
for i, kd := range InvoiceTypes {
its.OneOf[i] = &jsonschema.Schema{
Const: kd.Key.String(),
Title: kd.Name.String(),
Description: kd.Desc.String(),
}
}
}
}