-
Notifications
You must be signed in to change notification settings - Fork 0
/
cfdi.go
334 lines (277 loc) · 8.7 KB
/
cfdi.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
// Package cfdi implements the conversion from GOBL to CFDI XML
package cfdi
import (
"encoding/xml"
"errors"
"fmt"
"cloud.google.com/go/civil"
"github.com/invopop/gobl"
"github.com/invopop/gobl.cfdi/addendas"
"github.com/invopop/gobl.cfdi/internal"
"github.com/invopop/gobl.cfdi/internal/format"
"github.com/invopop/gobl/addons/mx/cfdi"
"github.com/invopop/gobl/bill"
"github.com/invopop/gobl/cal"
"github.com/invopop/gobl/currency"
"github.com/invopop/gobl/num"
"github.com/invopop/gobl/pay"
"github.com/invopop/gobl/schema"
"github.com/invopop/gobl/tax"
"github.com/invopop/validation"
)
// CFDI schema constants
const (
CFDINamespace = "http://www.sat.gob.mx/cfd/4"
CFDISchemaLocation = "http://www.sat.gob.mx/sitio_internet/cfd/4/cfdv40.xsd"
XSINamespace = "http://www.w3.org/2001/XMLSchema-instance"
CFDIVersion = "4.0"
)
// Hard-coded values for (yet) unsupported mappings
const (
FakeNoCertificado = "00000000000000000000"
ExportacionNoAplica = "01"
FormaPagoPorDefinir = "99"
ImpuestoIVA = "002"
)
// MetodoPago definitions
const (
MetodoPagoUnaExhibicion = "PUE"
MetodoPagoParcialidades = "PPD"
)
// Generic supplier constants
const (
NombreReceptorGenerico = "PÚBLICO EN GENERAL"
RegimenFiscalSinObligaciones = "616" // no tax obligations
UsoCFDISinEfectos = "S01" // no tax effects
)
// TipoFactor definitions.
const (
TipoFactorTasa = "Tasa"
TipoFactorCuota = "Cuota" // Not supported
TipoFactorExento = "Exento"
)
// Subject to tax constants
const (
ObjetoImpNo = "01" // not subject to tax
ObjetoImpSi = "02" // subject to tax
)
// ErrNotSupported is returned when the conversion of the invoice is not supported
var ErrNotSupported = errors.New("not supported")
// regime global
var regime = tax.RegimeDefFor("MX")
// Document is a pseudo-model for containing the XML document being created
type Document struct {
XMLName xml.Name `xml:"cfdi:Comprobante"`
CFDINamespace string `xml:"xmlns:cfdi,attr"`
XSINamespace string `xml:"xmlns:xsi,attr"`
ECCNamespace string `xml:"xmlns:ecc12,attr,omitempty"`
VDNamespace string `xml:"xmlns:valesdedespensa,attr,omitempty"`
SchemaLocation string `xml:"xsi:schemaLocation,attr"`
Version string `xml:"Version,attr"`
TipoDeComprobante string `xml:",attr"`
Serie string `xml:",attr,omitempty"`
Folio string `xml:",attr,omitempty"`
Fecha string `xml:",attr"`
LugarExpedicion string `xml:",attr"`
SubTotal string `xml:",attr"`
Descuento string `xml:",attr,omitempty"`
Total string `xml:",attr"`
Moneda string `xml:",attr"`
TipoCambio string `xml:",attr,omitempty"`
Exportacion string `xml:",attr"`
MetodoPago string `xml:",attr,omitempty"`
FormaPago string `xml:",attr,omitempty"`
CondicionesDePago string `xml:",attr,omitempty"`
Sello string `xml:",attr"`
NoCertificado string `xml:",attr"`
Certificado string `xml:",attr"`
CFDIRelacionados *CFDIRelacionados `xml:"cfdi:CfdiRelacionados,omitempty"`
Emisor *Emisor `xml:"cfdi:Emisor"`
Receptor *Receptor `xml:"cfdi:Receptor"`
Conceptos *Conceptos `xml:"cfdi:Conceptos"` //nolint:misspell
Impuestos *Impuestos `xml:"cfdi:Impuestos,omitempty"`
Complemento *internal.Nodes `xml:"cfdi:Complemento,omitempty"`
Addenda *internal.Nodes `xml:"cfdi:Addenda,omitempty"`
}
// NewDocument converts a GOBL envelope into a CFDI document
func NewDocument(env *gobl.Envelope) (*Document, error) {
inv, ok := env.Extract().(*bill.Invoice)
if !ok {
return nil, fmt.Errorf("invalid type %T", env.Document)
}
if err := validateSupport(inv); err != nil {
return nil, err
}
discount := internal.TotalInvoiceDiscount(inv)
subtotal := inv.Totals.Total.Add(discount)
issuePlace := issuePlace(inv)
document := &Document{
CFDINamespace: CFDINamespace,
XSINamespace: XSINamespace,
SchemaLocation: format.SchemaLocation(CFDINamespace, CFDISchemaLocation),
Version: CFDIVersion,
TipoDeComprobante: lookupTipoDeComprobante(inv),
Serie: inv.Series.String(),
Folio: inv.Code.String(),
Fecha: formatIssueDate(inv.IssueDate),
LugarExpedicion: issuePlace,
SubTotal: subtotal.String(),
Descuento: formatOptionalAmount(discount),
Total: inv.Totals.TotalWithTax.String(),
Moneda: string(inv.Currency),
TipoCambio: tipoCambio(inv),
Exportacion: ExportacionNoAplica,
MetodoPago: metodoPago(inv),
FormaPago: formaPago(inv),
CondicionesDePago: paymentTermsNotes(inv),
NoCertificado: FakeNoCertificado,
CFDIRelacionados: newCfdiRelacionados(inv),
Emisor: newEmisor(inv.Supplier),
Receptor: newReceptor(inv.Customer, issuePlace),
Conceptos: newConceptos(inv.Lines), // nolint:misspell
Impuestos: newImpuestos(inv.Totals, &inv.Currency),
}
if err := addComplementos(document, inv.Complements); err != nil {
return nil, err
}
if err := addAddendas(document, inv); err != nil {
return nil, err
}
return document, nil
}
func validateSupport(inv *bill.Invoice) error {
errs := validation.Errors{}
if len(inv.Charges) > 0 {
errs["charges"] = ErrNotSupported
}
for _, l := range inv.Lines {
if len(l.Charges) > 0 {
errs["line charges"] = ErrNotSupported
}
}
if len(inv.Outlays) > 0 {
errs["outlays"] = ErrNotSupported
}
// Deprecation pending...
if inv.HasTags(tax.TagSelfBilled) {
errs["self-billed"] = ErrNotSupported
}
if inv.HasTags(tax.TagCustomerRates) {
errs["customer-rates"] = ErrNotSupported
}
if len(errs) > 0 {
return errs
}
return nil
}
func issuePlace(inv *bill.Invoice) string {
if inv.Tax != nil && inv.Tax.Ext.Has(cfdi.ExtKeyIssuePlace) {
return inv.Tax.Ext[cfdi.ExtKeyIssuePlace].String()
}
// Fallback
return inv.Supplier.Ext[cfdi.ExtKeyIssuePlace].String()
}
// Bytes returns the XML representation of the document in bytes
func (d *Document) Bytes() ([]byte, error) {
bytes, err := xml.MarshalIndent(d, "", " ")
if err != nil {
return nil, err
}
return append([]byte(xml.Header), bytes...), nil
}
// AppendComplemento appends a complement to the document
func (d *Document) AppendComplemento(c interface{}) {
// We keep it nil unless an element is added so that no empty node is marshalled to XML
if d.Complemento == nil {
d.Complemento = &internal.Nodes{}
}
d.Complemento.Nodes = append(d.Complemento.Nodes, c)
}
// AppendAddenda appends an addenda to the document
func (d *Document) AppendAddenda(c interface{}) {
// We keep it nil unless an element is added so that no empty node is marshalled to XML
if d.Addenda == nil {
d.Addenda = &internal.Nodes{}
}
d.Addenda.Nodes = append(d.Addenda.Nodes, c)
}
func addComplementos(doc *Document, complements []*schema.Object) error {
for _, c := range complements {
switch o := c.Instance().(type) {
case *cfdi.FuelAccountBalance:
addEstadoCuentaCombustible(doc, o)
case *cfdi.FoodVouchers:
addValesDeDespensa(doc, o)
default:
return fmt.Errorf("unsupported complement %T", o)
}
}
return nil
}
func addAddendas(doc *Document, inv *bill.Invoice) error {
ads, err := addendas.For(inv)
if err != nil {
return err
}
for _, ad := range ads {
doc.AppendAddenda(ad)
}
return nil
}
func formatIssueDate(date cal.Date) string {
dateTime := civil.DateTime{Date: date.Date, Time: civil.Time{}}
return dateTime.String()
}
func lookupTipoDeComprobante(inv *bill.Invoice) string {
if inv.Tax == nil {
return ""
}
return inv.Tax.Ext[cfdi.ExtKeyDocType].String()
}
func tipoCambio(inv *bill.Invoice) string {
r := currency.MatchExchangeRate(inv.ExchangeRates, inv.Currency, currency.MXN)
if r == nil {
return ""
}
return r.Amount.String()
}
func metodoPago(inv *bill.Invoice) string {
if isPrepaid(inv) {
return MetodoPagoUnaExhibicion
}
return MetodoPagoParcialidades
}
func formaPago(inv *bill.Invoice) string {
adv := largestAdvance(inv)
if !isPrepaid(inv) || adv == nil {
return FormaPagoPorDefinir
}
return adv.Ext[cfdi.ExtKeyPaymentMeans].String()
}
func isPrepaid(inv *bill.Invoice) bool {
return inv.Totals.Due != nil && inv.Totals.Due.IsZero()
}
func largestAdvance(inv *bill.Invoice) *pay.Advance {
if inv.Payment == nil || len(inv.Payment.Advances) == 0 {
return nil
}
la := inv.Payment.Advances[0]
for _, a := range inv.Payment.Advances {
if a.Amount.Compare(la.Amount) == 1 {
la = a
}
}
return la
}
func paymentTermsNotes(inv *bill.Invoice) string {
if inv.Payment == nil || inv.Payment.Terms == nil {
return ""
}
return inv.Payment.Terms.Notes
}
func formatOptionalAmount(a num.Amount) string {
if a.IsZero() {
return ""
}
return a.String()
}