-
Notifications
You must be signed in to change notification settings - Fork 0
/
mabe.go
419 lines (358 loc) · 11.4 KB
/
mabe.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
package addendas
import (
"encoding/xml"
"fmt"
"github.com/invopop/gobl.cfdi/internal"
"github.com/invopop/gobl.cfdi/internal/format"
"github.com/invopop/gobl/bill"
"github.com/invopop/gobl/cbc"
"github.com/invopop/gobl/i18n"
"github.com/invopop/gobl/l10n"
"github.com/invopop/gobl/num"
"github.com/invopop/gobl/org"
"github.com/invopop/gobl/tax"
"github.com/invopop/validation"
)
// Mabe schema constants
const (
MabeVersion = "1.0"
MabeNamespace = "https://recepcionfe.mabempresa.com/cfd/addenda/v1"
MabeSchemaLocation = "https://recepcionfe.mabempresa.com/cfd/addenda/v1/mabev1.xsd"
MabeNotApplicable = "NA"
)
// TipoDocumento valid values
const (
MabeTipoDocumentoFactura = "FACTURA"
MabeTipoDocumentoNotaCredito = "NOTA CREDITO"
MabeTipoDocumentoNotaCargo = "NOTA CARGO"
)
// MabeTipoDocumentoMap maps GOBL invoice types to Mabe's TipoDocumento
var MabeTipoDocumentoMap = map[cbc.Key]string{
bill.InvoiceTypeStandard: MabeTipoDocumentoFactura,
bill.InvoiceTypeCreditNote: MabeTipoDocumentoNotaCredito,
bill.InvoiceTypeDebitNote: MabeTipoDocumentoNotaCargo,
}
// Mabe specific identity codes.
const (
MabeKeyIdentityPurchaseOrder = "mx-mabe-purchase-order"
MabeKeyIdentityProviderCode = "mx-mabe-provider-code"
MabeKeyIdentityRef1 = "mx-mabe-reference1"
MabeKeyIdentityRef2 = "mx-mabe-reference2"
MabeKeyIdentityDeliveryPlant = "mx-mabe-delivery-plant"
MabeKeyIdentityArticleCode = "mx-mabe-article-code"
MabeKeyIdentityUnit = "mx-mabe-unit"
)
// MabeFactura is the root element of the Mabe addendum
type MabeFactura struct {
XMLName xml.Name `xml:"mabe:Factura"`
Namespace string `xml:"xmlns:mabe,attr"`
SchemaLocation string `xml:"xsi:schemaLocation,attr"`
Version string `xml:"version,attr"`
TipoDocumento string `xml:"tipoDocumento,attr"`
Folio string `xml:"folio,attr"`
Fecha string `xml:"fecha,attr"`
OrdenCompra string `xml:"ordenCompra,attr"`
Referencia1 string `xml:"referencia1,attr"`
Referencia2 string `xml:"referencia2,attr,omitempty"`
Moneda *MabeMoneda `xml:"mabe:Moneda"`
Proveedor *MabeProveedor `xml:"mabe:Proveedor"`
Entrega *MabeEntrega `xml:"mabe:Entrega"`
Detalles *MabeDetalles `xml:"mabe:Detalles"`
Descuentos *MabeDescuentos `xml:"mabe:Descuentos,omitempty"`
Subtotal *MabeImporte `xml:"mabe:Subtotal"`
Traslados *MabeTraslados `xml:"mabe:Traslados"`
Retenciones *MabeRetenciones `xml:"mabe:Retenciones"`
Total *MabeImporte `xml:"mabe:Total"`
}
// MabeMoneda carries the data about the invoice's currency
type MabeMoneda struct {
TipoMoneda string `xml:"tipoMoneda,attr"`
TipoCambio string `xml:"tipoCambio,attr,omitempty"` // Not implemented yet
ImporteConLetra string `xml:"importeConLetra,attr,omitempty"` // Not implemented yet
}
// MabeProveedor carries the data about the invoice's supplier
type MabeProveedor struct {
Codigo string `xml:"codigo,attr"`
}
// MabeEntrega carries the data about the invoice's delivery
type MabeEntrega struct {
PlantaEntrega string `xml:"plantaEntrega,attr"`
Calle string `xml:"calle,attr,omitempty"`
NoExterior string `xml:"noExterior,attr,omitempty"`
NoInterior string `xml:"noInterior,attr,omitempty"`
CodigoPostal string `xml:"codigoPostal,attr,omitempty"`
}
// MabeDetalles carries the data about an invoice's lines
type MabeDetalles struct {
Detalle []*MabeDetalle `xml:"mabe:Detalle"`
}
// MabeDetalle carries the data about one invoice's line
type MabeDetalle struct {
NoLineaArticulo int `xml:"noLineaArticulo,attr"`
CodigoArticulo string `xml:"codigoArticulo,attr"`
Descripcion string `xml:"descripcion,attr"` //nolint:misspell
Unidad string `xml:"unidad,attr"`
Cantidad string `xml:"cantidad,attr"`
PrecioSinIva string `xml:"precioSinIva,attr"`
ImporteSinIva string `xml:"importeSinIva,attr"`
PrecioConIva string `xml:"precioConIva,attr,omitempty"` // Not implemented yet
ImporteConIva string `xml:"importeConIva,attr,omitempty"` // Not implemented yet
}
// MabeImporte carries the data about an invoice's total
type MabeImporte struct {
Importe string `xml:"importe,attr"`
}
// MabeTraslados carries the data about an invoice's taxes (expect retained ones)
type MabeTraslados struct {
Traslado []*MabeImpuesto `xml:"mabe:Traslado"`
}
// MabeRetenciones carries the data about an invoice's retained taxes
type MabeRetenciones struct {
Retencion []*MabeImpuesto `xml:"mabe:Retencion"`
}
// MabeImpuesto carries the data about an invoice's tax
type MabeImpuesto struct {
Tipo string `xml:"tipo,attr"`
Tasa string `xml:"tasa,attr"`
Importe string `xml:"importe,attr"`
}
// MabeDescuentos carries the data about an invoice's discount
type MabeDescuentos struct {
Tipo string `xml:"tipo,attr"`
Descripcion string `xml:"descripcion,attr"` //nolint:misspell
Importe string `xml:"importe,attr"`
}
func isMabe(inv *bill.Invoice) bool {
if inv.Supplier == nil {
return false
}
id := extractIdentity(inv.Supplier.Identities, MabeKeyIdentityProviderCode)
return id != cbc.CodeEmpty
}
// newMabe provides a new Mabe addenda.
func newMabe(inv *bill.Invoice) (*MabeFactura, error) {
if err := validateInvoiceForMabe(inv); err != nil {
return nil, err
}
// Ref2 is not currently used by Mabe, so we set the default
// value to "NA".
ref2 := extractIdentity(inv.Ordering.Identities, MabeKeyIdentityRef2)
if ref2 == "" {
ref2 = "NA"
}
f := &MabeFactura{
Namespace: MabeNamespace,
SchemaLocation: format.SchemaLocation(MabeNamespace, MabeSchemaLocation),
Version: MabeVersion,
TipoDocumento: MabeTipoDocumentoMap[inv.Type],
Folio: formatMabeFolio(inv),
Fecha: inv.IssueDate.String(),
OrdenCompra: extractIdentity(inv.Ordering.Identities, MabeKeyIdentityPurchaseOrder).String(),
Referencia1: extractIdentity(inv.Ordering.Identities, MabeKeyIdentityRef1).String(),
Referencia2: ref2.String(),
Moneda: newMabeMoneda(inv),
Proveedor: newMabeProveedor(inv),
Entrega: newMabeEntrega(inv),
Descuentos: newMabeDescuentos(inv),
Detalles: newMabeDetalles(inv),
Subtotal: newMabeImporte(inv.Totals.Sum),
Total: newMabeImporte(inv.Totals.TotalWithTax),
}
setMabeTaxes(inv, f)
return f, nil
}
func validateInvoiceForMabe(inv *bill.Invoice) error {
return validation.ValidateStruct(inv,
validation.Field(&inv.Type, validation.In(validMabeInvoiceTypes()...)),
validation.Field(&inv.Supplier,
validation.By(validateSupplierForMabe),
),
validation.Field(&inv.Lines,
validation.Each(validation.By(validateLineForMabe), validation.Skip),
validation.Skip, // prevent GOBL validations from running
),
validation.Field(&inv.Ordering,
validation.Required,
validation.By(validateOrderingForMabe),
),
validation.Field(&inv.Delivery,
validation.Required,
validation.By(validateDeliveryForMabe),
),
)
}
func validateSupplierForMabe(value interface{}) error {
sup, _ := value.(*org.Party)
if sup == nil {
return nil
}
return validation.ValidateStruct(sup,
validation.Field(&sup.Identities, org.RequireIdentityKey(MabeKeyIdentityProviderCode)),
)
}
func validateLineForMabe(value interface{}) error {
line, _ := value.(*bill.Line)
if line == nil {
return nil
}
return validation.ValidateStruct(line,
validation.Field(&line.Item,
validation.By(validateItemForMabe),
),
)
}
func validateItemForMabe(value interface{}) error {
item, _ := value.(*org.Item)
if item == nil {
return nil
}
return validation.ValidateStruct(item,
validation.Field(&item.Identities, org.RequireIdentityKey(MabeKeyIdentityArticleCode)),
)
}
func validateDeliveryForMabe(value interface{}) error {
del, _ := value.(*bill.Delivery)
if del == nil {
return nil
}
return validation.ValidateStruct(del,
validation.Field(&del.Receiver,
validation.Required,
validation.By(validateReceiverForMabe),
),
)
}
func validateReceiverForMabe(value interface{}) error {
rec, _ := value.(*org.Party)
if rec == nil {
return nil
}
return validation.ValidateStruct(rec,
validation.Field(&rec.Identities, org.RequireIdentityKey(MabeKeyIdentityDeliveryPlant)),
)
}
func validateOrderingForMabe(value interface{}) error {
ord, _ := value.(*bill.Ordering)
if ord == nil {
return nil
}
return validation.ValidateStruct(ord,
validation.Field(&ord.Identities,
org.RequireIdentityKey(MabeKeyIdentityPurchaseOrder),
org.RequireIdentityKey(MabeKeyIdentityRef1),
),
)
}
func validMabeInvoiceTypes() []interface{} {
var types []interface{}
for t := range MabeTipoDocumentoMap {
types = append(types, t)
}
return types
}
func newMabeMoneda(inv *bill.Invoice) *MabeMoneda {
return &MabeMoneda{TipoMoneda: string(inv.Currency)}
}
func newMabeProveedor(inv *bill.Invoice) *MabeProveedor {
if inv.Supplier == nil {
return nil
}
id := extractIdentity(inv.Supplier.Identities, MabeKeyIdentityProviderCode)
return &MabeProveedor{
Codigo: id.String(),
}
}
func newMabeEntrega(inv *bill.Invoice) *MabeEntrega {
rec := inv.Delivery.Receiver
id := extractIdentity(rec.Identities, MabeKeyIdentityDeliveryPlant)
e := &MabeEntrega{
PlantaEntrega: id.String(),
}
if len(rec.Addresses) > 0 {
addr := rec.Addresses[0]
e.Calle = addr.Street
e.NoExterior = addr.Number
e.NoInterior = MabeNotApplicable
e.CodigoPostal = addr.Code.String()
}
return e
}
func newMabeDescuentos(inv *bill.Invoice) *MabeDescuentos {
d := internal.TotalInvoiceDiscount(inv)
if d.IsZero() {
return nil
}
return &MabeDescuentos{
Tipo: MabeNotApplicable,
Descripcion: MabeNotApplicable, //nolint:misspell
Importe: d.String(),
}
}
func newMabeDetalles(inv *bill.Invoice) *MabeDetalles {
var detalles []*MabeDetalle
for _, line := range inv.Lines {
id := extractIdentity(line.Item.Identities, MabeKeyIdentityArticleCode)
unit := extractIdentity(line.Item.Identities, MabeKeyIdentityUnit)
if unit == cbc.CodeEmpty {
unit = internal.ClaveUnidad(line)
}
d := &MabeDetalle{
NoLineaArticulo: line.Index,
CodigoArticulo: id.String(),
Descripcion: line.Item.Name, //nolint:misspell
Unidad: unit.String(),
Cantidad: line.Quantity.String(),
PrecioSinIva: line.Item.Price.String(),
ImporteSinIva: line.Sum.String(),
}
detalles = append(detalles, d)
}
if len(detalles) == 0 {
return nil
}
return &MabeDetalles{detalles}
}
func newMabeImporte(amount num.Amount) *MabeImporte {
return &MabeImporte{
Importe: amount.String(),
}
}
func setMabeTaxes(inv *bill.Invoice, mabe *MabeFactura) {
var traslados, retenciones []*MabeImpuesto
regime := tax.RegimeDefFor(l10n.MX)
for _, cat := range inv.Totals.Taxes.Categories {
catDef := regime.CategoryDef(cat.Code)
for _, rate := range cat.Rates {
t := &MabeImpuesto{
Tipo: catDef.Name.In(i18n.ES), // this is risky
Tasa: format.TaxPercent(rate.Percent),
Importe: rate.Amount.String(),
}
if cat.Retained {
retenciones = append(retenciones, t)
} else {
traslados = append(traslados, t)
}
}
}
if len(traslados) > 0 {
mabe.Traslados = &MabeTraslados{traslados}
}
if len(retenciones) > 0 {
mabe.Retenciones = &MabeRetenciones{retenciones}
}
}
func formatMabeFolio(inv *bill.Invoice) string {
return fmt.Sprintf("%s%s", inv.Series, inv.Code)
}
func extractIdentity(ids []*org.Identity, key cbc.Key) cbc.Code {
if ids == nil {
return ""
}
for _, id := range ids {
if id.Key == key {
return id.Code
}
}
return cbc.CodeEmpty
}