-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfacturae.go
More file actions
274 lines (237 loc) · 7.7 KB
/
Copy pathfacturae.go
File metadata and controls
274 lines (237 loc) · 7.7 KB
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
package facturae
import (
"bytes"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"github.com/invopop/gobl"
addon "github.com/invopop/gobl/addons/es/facturae"
"github.com/invopop/gobl/bill"
"github.com/invopop/xmldsig"
"github.com/invopop/xmldsig/profiles/facturae"
)
// Namespaces used for FacturaE. DSig stuff is handled in the signatures.
const (
NamespaceFacturaE = "http://www.facturae.gob.es/formato/Versiones/Facturaev3_2_2.xml"
)
// XAdES Signer Roles used for FacturaE
const (
XAdESSupplier xmldsig.XAdESSignerRole = "supplier"
XAdESCustomer xmldsig.XAdESSignerRole = "customer"
XAdESThirdParty xmldsig.XAdESSignerRole = "third party"
)
// Document is a pseudo-model for containing the XML document being created.
type Document struct {
env *gobl.Envelope `xml:"-"` // Envelope to convert.
invoice *bill.Invoice `xml:"-"` // Invoice contained in envelope.
XMLName xml.Name `xml:"fe:Facturae"`
FeNamespace string `xml:"xmlns:fe,attr"`
FileHeader *FileHeader
Parties *Parties
Invoices *Invoices
Signature *xmldsig.Signature `xml:"ds:Signature,omitempty"`
}
type options struct {
certificate *xmldsig.Certificate
addTimestamp bool
thirdParty *ThirdParty
signingOpts []xmldsig.Option
}
// Option defines a callback configuration option used to customize the
// conversion to XML process
type Option func(*options)
// WithCertificate will use the provided certificate to sign the XML document.
func WithCertificate(cert *xmldsig.Certificate) Option {
return func(opts *options) {
opts.certificate = cert
}
}
// WithTimestamp will ensure the XML document is timestamped
func WithTimestamp(val bool) Option {
return func(opts *options) {
opts.addTimestamp = val
}
}
// WithThirdParty adds optional information about who is manipulating and signing
// the document.
func WithThirdParty(tp *ThirdParty) Option {
return func(opts *options) {
opts.thirdParty = tp
}
}
// WithSigning allows passing additional xmldsig options that will be appended
// to the signing call. Useful to inject a deterministic signing time or other
// parameters in tests.
func WithSigning(opts ...xmldsig.Option) Option {
return func(o *options) {
o.signingOpts = append(o.signingOpts, opts...)
}
}
// LoadGOBL will build a FacturaE Document from the source buffer
func LoadGOBL(src io.Reader, opts ...Option) (*Document, error) {
buf := new(bytes.Buffer)
if _, err := buf.ReadFrom(src); err != nil {
return nil, err
}
env := new(gobl.Envelope)
if err := json.Unmarshal(buf.Bytes(), env); err != nil {
return nil, err
}
return NewInvoice(env, opts...)
}
// NewInvoice expects the base envelope and provides a new Document
// containing the XML version.
func NewInvoice(env *gobl.Envelope, opts ...Option) (*Document, error) {
// prepare our options
xmlOpts := new(options)
for _, opt := range opts {
opt(xmlOpts)
}
invoice, ok := env.Extract().(*bill.Invoice)
if !ok {
return nil, errors.New("expected an invoice")
}
if !addon.V3.In(invoice.GetAddons()...) {
return nil, fmt.Errorf("missing %s addon", addon.V3.String())
}
if invoice.Customer == nil {
return nil, errors.New("customer required")
}
// Make sure we're dealing with raw data
if err := invoice.RemoveIncludedTaxes(); err != nil {
return nil, fmt.Errorf("removing taxes: %w", err)
}
// Invert if we're dealing with a credit note
if invoice.Type == bill.InvoiceTypeCreditNote {
if err := invoice.Invert(); err != nil {
return nil, fmt.Errorf("inverting invoice: %w", err)
}
}
// Basic document headers
d := &Document{
env: env,
invoice: invoice,
FeNamespace: NamespaceFacturaE,
Parties: &Parties{
Seller: &Party{},
Buyer: &Party{},
},
}
d.Parties.Seller.TaxID = NewTaxID(invoice.Supplier.TaxID.Code, invoice.Supplier.TaxID.Country)
if d.Parties.Seller.TaxID.PersonTypeCode == "F" {
d.Parties.Seller.Individual = NewIndividual(invoice.Supplier)
} else {
d.Parties.Seller.LegalEntity = NewLegalEntity(invoice.Supplier)
}
if invoice.Customer != nil && invoice.Customer.TaxID != nil {
// Simplified invoices are not supported by FacturaE, but this is where
// they'd be handled if the situation changes.
b := d.Parties.Buyer
b.TaxID = NewTaxID(invoice.Customer.TaxID.Code, invoice.Customer.TaxID.Country)
b.AdministrativeCentres = NewAdministrativeCentres(invoice)
if b.TaxID.PersonTypeCode == "F" {
b.Individual = NewIndividual(invoice.Customer)
} else {
b.LegalEntity = NewLegalEntity(invoice.Customer)
}
}
d.Invoices = &Invoices{
List: []*Invoice{d.newInvoice(invoice)},
}
d.FileHeader = newFileHeader(invoice, xmlOpts.thirdParty)
if xmlOpts.certificate != nil {
data, err := d.Canonical()
if err != nil {
return nil, fmt.Errorf("converting to canonincal format: %w", err)
}
dsigCfg := facturae.XMLDSigConfig()
dsigCfg.OmitDataCanonicalizationTransform = true
xadesCfg := facturae.XAdESConfig(
xmldsig.XAdESConfig{
Role: XAdESThirdParty,
Description: "Factura Electrónica",
Policy: &xmldsig.XAdESPolicyConfig{
URL: "http://www.facturae.es/politica_de_firma_formato_facturae/politica_de_firma_formato_facturae_v3_1.pdf",
Description: "Política de Firma FacturaE v3.1",
Algorithm: "http://www.w3.org/2000/09/xmldsig#sha1",
Hash: "Ohixl6upD6av8N7pEvDABhEL6hM=",
},
},
)
sigopts := []xmldsig.Option{
xmldsig.WithDocID(env.Head.UUID.String()),
xmldsig.WithXMLDSigConfig(dsigCfg),
xmldsig.WithXAdESConfig(xadesCfg),
xmldsig.WithCertificate(xmlOpts.certificate),
}
if xmlOpts.addTimestamp {
sigopts = append(sigopts, xmldsig.WithTimestamp(xmldsig.TimestampFreeTSA))
}
sigopts = append(sigopts, xmlOpts.signingOpts...)
sig, err := xmldsig.Sign(data, sigopts...)
if err != nil {
return nil, err
}
d.Signature = sig
}
return d, nil
}
// Buffer returns a byte buffer representation of the complete XML document.
func (d *Document) Buffer() (*bytes.Buffer, error) {
return d.buffer(xml.Header)
}
// String converts a struct representation to its string representation
func (d *Document) String() (string, error) {
buf, err := d.Buffer()
if err != nil {
return "", err
}
return buf.String(), nil
}
// Bytes returns the XML document bytes
func (d *Document) Bytes() ([]byte, error) {
buf, err := d.Buffer()
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// BytesIndent returns the XML document bytes with indentation for readability.
// This is useful for debugging and testing purposes, but should not be used in
// production as it will not work correctly with digital signatures.
func (d *Document) BytesIndent() ([]byte, error) {
buf := bytes.NewBufferString(xml.Header)
data, err := xml.MarshalIndent(d, "", "\t")
if err != nil {
return nil, fmt.Errorf("marshal document: %w", err)
}
if _, err := buf.Write(data); err != nil {
return nil, fmt.Errorf("writing to buffer: %w", err)
}
return buf.Bytes(), nil
}
func (d *Document) buffer(base string) (*bytes.Buffer, error) {
buf := bytes.NewBufferString(base)
// data, err := xml.MarshalIndent(d, "", " ") // not compatible with certificates
data, err := xml.Marshal(d)
if err != nil {
return nil, fmt.Errorf("marshal document: %w", err)
}
if _, err := buf.Write(data); err != nil {
return nil, fmt.Errorf("writing to buffer: %w", err)
}
return buf, nil
}
// Canonical converts a struct representation of facturae to its
// canonical representation as defined in https://www.w3.org/TR/2001/REC-xml-c14n-20010315
// (for a simpler explanation look at https://www.di-mgt.com.au/xmldsig-c14n.html)
// This is used when we need to create a hash for signing, timestamping, ...
func (d *Document) Canonical() ([]byte, error) {
buf, err := d.buffer("")
if err != nil {
return nil, err
}
return buf.Bytes(), nil
}