-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathcdar_status_parse.go
More file actions
487 lines (460 loc) · 14.2 KB
/
Copy pathcdar_status_parse.go
File metadata and controls
487 lines (460 loc) · 14.2 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
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
package cii
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/invopop/gobl.fr.ctc/addon/flow6"
"github.com/invopop/gobl/bill"
"github.com/invopop/gobl/cal"
"github.com/invopop/gobl/catalogues/iso"
"github.com/invopop/gobl/catalogues/untdid"
"github.com/invopop/gobl/cbc"
"github.com/invopop/gobl/org"
"github.com/invopop/gobl/tax"
)
// ParseCDARStatus parses a raw CDAR XML byte slice into a *bill.Status
// without going through an envelope.
//
// The returned status carries the CDAR codes on the flow6 extensions
// (fr-ctc-flow6-status / -reason / -action) with the addon declared;
// the GOBL-level fields they derive (Status.Type, line and reason keys)
// are filled by the flow6 normalizer when the document is calculated —
// wrap it in an envelope (gobl.Envelop / Envelope.Insert) or run
// Calculate to complete it.
func ParseCDARStatus(data []byte) (*bill.Status, error) {
cdar, err := UnmarshalCDAR(data)
if err != nil {
return nil, err
}
return goblStatusFromCDAR(cdar, routing{})
}
// parseCDAR converts a raw CDAR XML byte slice into the GOBL document
// matching its ProcessConditionCode: payment lifecycle codes (211 /
// 212) produce a *bill.Payment, everything else a *bill.Status.
func parseCDAR(data []byte, r routing) (any, error) {
cdar, err := UnmarshalCDAR(data)
if err != nil {
return nil, err
}
if code := cdarProcessCode(cdar); code == "211" || code == "212" {
return goblPaymentFromCDAR(cdar, r)
}
return goblStatusFromCDAR(cdar, r)
}
// cdarProcessCode returns the ProcessConditionCode of the first
// referenced document in the CDAR, or "".
func cdarProcessCode(cdar *CDAR) string {
for _, ack := range cdar.AcknowledgementDocuments {
if ack == nil {
continue
}
for _, ref := range ack.ReferenceReferencedDocument {
if ref != nil && ref.ProcessConditionCode != "" {
return ref.ProcessConditionCode
}
}
}
return ""
}
func goblStatusFromCDAR(cdar *CDAR, r routing) (*bill.Status, error) {
if cdar == nil || cdar.ExchangedDocument == nil {
return nil, fmt.Errorf("invalid CDAR document")
}
st := &bill.Status{}
st.SetAddons(flow6.V1)
if cdar.ExchangedDocument.ID != "" {
st.Code = cbc.Code(cdar.ExchangedDocument.ID)
}
if cdar.ExchangedDocument.IssueDateTime != nil && cdar.ExchangedDocument.IssueDateTime.DateTimeString != nil {
d, t, err := parseCDARDateTime(cdar.ExchangedDocument.IssueDateTime.DateTimeString.Value)
if err != nil {
return nil, err
}
st.IssueDate = d
if t != nil {
st.IssueTime = t
}
}
// bill.Status only has the two business-party slots. Map the CDAR
// trade parties onto them by their RoleCode: SE → Supplier, BY →
// Customer. Platform-level parties (WK sender, DFH PPF) have no
// GOBL slot and are dropped — they are transport detail that the
// generator re-derives.
assignStatusParty := func(tp *CDARTradeParty) {
p := goblPartyFromCDAR(tp)
if p == nil {
return
}
switch p.Ext.Get(flow6.ExtKeyRole) {
case flow6.RoleSeller:
if st.Supplier == nil {
st.Supplier = p
}
case flow6.RoleBuyer:
if st.Customer == nil {
st.Customer = p
}
}
}
assignStatusParty(cdar.ExchangedDocument.IssuerTradeParty)
for _, rp := range cdar.ExchangedDocument.RecipientTradeParties {
assignStatusParty(rp)
}
st.Supplier = supplierWithReferencedSIREN(st.Supplier, cdar)
// Build StatusLines from each AcknowledgementDocument. The CDAR
// ProcessConditionCode is pinned on the fr-ctc-flow6-status ext;
// flow6's reverse mapping derives line.Key and Status.Type from it
// at normalize-time.
for _, ack := range cdar.AcknowledgementDocuments {
if ack == nil {
continue
}
for _, ref := range ack.ReferenceReferencedDocument {
if ref == nil {
continue
}
st.Lines = append(st.Lines, goblStatusLineFromCDAR(ref))
}
}
hydratePartyInboxes(st.Supplier, st.Customer, r)
return st, nil
}
func goblStatusLineFromCDAR(ref *CDARReferencedDocument) *bill.StatusLine {
line := &bill.StatusLine{}
if ref.ProcessConditionCode != "" {
line.Ext = line.Ext.Set(flow6.ExtKeyStatus, cbc.Code(ref.ProcessConditionCode))
}
if dr := goblDocRefFromCDAR(ref); dr != nil {
line.Doc = dr
}
// MDT-95: when the referenced invoice was received / deposited —
// the date this lifecycle row is effective from.
if ref.ReceiptDateTime != nil && ref.ReceiptDateTime.DateTimeString != nil {
if d, _, err := parseCDARDateTime(ref.ReceiptDateTime.DateTimeString.Value); err == nil {
line.Date = &d
}
}
for _, ds := range ref.SpecifiedDocumentStatuses {
if ds == nil {
continue
}
var r *bill.Reason
if ds.ReasonCode != "" {
// Reason.Key is recovered from the ext by flow6's
// prepareReasonKey at normalize-time.
r = &bill.Reason{
Ext: tax.MakeExtensions().Set(flow6.ExtKeyReason, cbc.Code(ds.ReasonCode)),
Description: strings.Join(ds.Reason, "\n"),
}
}
// Field-level corrections and amount markers
// (SpecifiedDocumentCharacteristics: DIV/DVA/MAJ, MAP/MNA…)
// become faults on the status's reason, so the inbound detail
// is preserved for display.
for _, dc := range ds.SpecifiedDocumentCharacteristics {
f := goblFaultFromCDAR(dc)
if f == nil {
continue
}
if r == nil {
// Characteristics without a ReasonCode still need a
// host; "other" is the neutral bucket.
r = &bill.Reason{Key: bill.ReasonKeyOther}
}
r.Faults = append(r.Faults, f)
}
if r != nil {
line.Reasons = append(line.Reasons, r)
}
if ds.RequestedActionCode != "" {
// Action.Key is recovered from the ext by flow6's
// prepareActionKey at normalize-time.
a := &bill.Action{
Ext: tax.MakeExtensions().Set(flow6.ExtKeyAction, cbc.Code(ds.RequestedActionCode)),
}
if ds.RequestedAction != "" {
a.Description = ds.RequestedAction
}
line.Actions = append(line.Actions, a)
}
}
return line
}
// goblFaultFromCDAR maps a SpecifiedDocumentCharacteristic onto a
// bill.Fault: the CharacteristicTypeCode (MDT-207) becomes the fault
// code, the XML Location (MDT-213) the fault path, and the remaining
// detail — data name (MDT-211), business-term ID (MDT-206) and the
// typed value (amount / percent / date) — composes the human-readable
// message, e.g. "Taux TVA (BT-152): 10.00%".
func goblFaultFromCDAR(dc *CDARDocumentCharacteristic) *bill.Fault {
if dc == nil {
return nil
}
code := dc.TypeCode
if code == "" {
code = dc.ID
}
if code == "" {
return nil
}
f := &bill.Fault{Code: cbc.Code(code)}
msg := dc.Name
if dc.ID != "" && dc.TypeCode != "" {
if msg != "" {
msg += " (" + dc.ID + ")"
} else {
msg = dc.ID
}
}
var value string
switch {
case dc.ValueAmount != nil && dc.ValueAmount.Value != "":
value = dc.ValueAmount.Value
if dc.ValueAmount.CurrencyID != "" {
value += " " + dc.ValueAmount.CurrencyID
}
case dc.ValuePercent != "":
value = dc.ValuePercent + "%"
case dc.ValueDateTime != nil && dc.ValueDateTime.DateTimeString != nil:
if d, _, err := parseCDARDateTime(dc.ValueDateTime.DateTimeString.Value); err == nil {
value = d.String()
}
}
if value != "" {
if msg != "" {
msg += ": " + value
} else {
msg = value
}
}
f.Message = msg
if dc.Location != "" {
f.Paths = []string{dc.Location}
}
return f
}
// goblDocRefFromCDAR maps the referenced-document identity (invoice
// number, type code, issue date) onto an org.DocumentRef.
//
// The CDAR's IssuerTradeParty names the referenced invoice's issuer (its
// supplier). The CDAR's own SE/BY trade parties describe the status issuer,
// which for buyer-issued events (e.g. a 211 payment advice) is the buyer, not
// the invoice supplier — so the invoice's supplier identity survives only here.
// It is carried onto the doc ref's Identities so a recipient can resolve the
// invoice by its supplier SIREN regardless of who issued the status.
func goblDocRefFromCDAR(ref *CDARReferencedDocument) *org.DocumentRef {
if ref.IssuerAssignedID == "" {
return nil
}
dr := &org.DocumentRef{Code: cbc.Code(ref.IssuerAssignedID)}
if ref.TypeCode != "" {
// MDT-91 → the canonical untdid-document-type extension (not the Type
// key), so the referenced type is represented the same way inbound and
// outbound and downstream can always rely on the extension.
dr.Ext = dr.Ext.Set(untdid.ExtKeyDocumentType, cbc.Code(ref.TypeCode))
}
if ref.FormattedIssueDateTime != nil && ref.FormattedIssueDateTime.DateTimeString != nil {
d, _, err := parseCDARDateTime(ref.FormattedIssueDateTime.DateTimeString.Value)
if err == nil {
dd := d
dr.IssueDate = &dd
}
}
if issuer := goblPartyFromCDAR(ref.IssuerTradeParty); issuer != nil {
dr.Identities = issuer.Identities
}
return dr
}
// participantInbox parses a Peppol participant id into an org.Inbox. It accepts
// both the bare "scheme:code" form the Peppol layer returns (e.g.
// "0225:698680774") and the full "iso6523-actorid-upis::scheme:code" endpoint
// URI. Returns nil when the value is empty or has no scheme separator.
func participantInbox(uri cbc.URI) *org.Inbox {
s := string(uri)
if s == "" {
return nil
}
if i := strings.Index(s, "::"); i >= 0 { // drop the iso6523-actorid-upis authority
s = s[i+2:]
}
i := strings.Index(s, ":")
if i < 0 {
return nil
}
return &org.Inbox{Scheme: cbc.Code(s[:i]), Code: cbc.Code(s[i+1:])}
}
// hydratePartyInboxes fills a business party's Peppol inbox from the envelope's
// transport routing (the SBD From / To) when the CDV body omitted it. A
// conformant CDAR need not repeat the issuer's electronic address in the
// document body — it travels at the SBD layer — yet BR-FR-CDV-08 requires every
// non-WK/DFH party to carry an inbox, so a received status would otherwise fail
// validation. Each routing participant is matched to the party whose SIREN it
// carries; any leftover participant fills a party still missing an inbox.
// Parties that already have an inbox are left untouched.
func hydratePartyInboxes(supplier, customer *org.Party, r routing) {
parties := make([]*org.Party, 0, 2)
for _, p := range []*org.Party{supplier, customer} {
if p != nil {
parties = append(parties, p)
}
}
if len(parties) == 0 {
return
}
inboxes := make([]*org.Inbox, 0, 2)
for _, uri := range []cbc.URI{r.from, r.to} {
if ib := participantInbox(uri); ib != nil {
inboxes = append(inboxes, ib)
}
}
used := make([]bool, len(inboxes))
// First pass: match each participant to the party carrying its SIREN.
for _, p := range parties {
if len(p.Inboxes) > 0 {
continue
}
siren := partySIREN(p)
if siren == "" {
continue
}
for i, ib := range inboxes {
if used[i] {
continue
}
if code := ib.Code.String(); code == siren || strings.HasPrefix(code, siren) {
p.Inboxes = []*org.Inbox{ib}
used[i] = true
break
}
}
}
// Second pass: assign any leftover participant to a party still missing one.
for _, p := range parties {
if len(p.Inboxes) > 0 {
continue
}
for i := range inboxes {
if used[i] {
continue
}
p.Inboxes = []*org.Inbox{inboxes[i]}
used[i] = true
break
}
}
}
func goblPartyFromCDAR(tp *CDARTradeParty) *org.Party {
if tp == nil {
return nil
}
p := &org.Party{Name: tp.Name}
if tp.RoleCode != "" {
p.Ext = tax.MakeExtensions().Set(flow6.ExtKeyRole, cbc.Code(tp.RoleCode))
}
for _, gid := range tp.GlobalIDs {
if gid == nil || gid.Value == "" {
continue
}
id := &org.Identity{Code: cbc.Code(gid.Value)}
// Only carry the ISO 6523 scheme when the GlobalID actually has one —
// an empty schemeID would otherwise become a present-but-empty ext.
if gid.SchemeID != "" {
id.Ext = tax.MakeExtensions().Set(iso.ExtKeySchemeID, cbc.Code(gid.SchemeID))
}
p.Identities = append(p.Identities, id)
}
if tp.URIUniversalCommunication != nil && tp.URIUniversalCommunication.URIID != nil {
ib := &org.Inbox{
Scheme: cbc.Code(tp.URIUniversalCommunication.URIID.SchemeID),
Code: cbc.Code(tp.URIUniversalCommunication.URIID.Value),
}
p.Inboxes = []*org.Inbox{ib}
}
if p.Name == "" && len(p.Identities) == 0 && p.Ext.IsZero() && len(p.Inboxes) == 0 {
return nil
}
return p
}
// supplierWithReferencedSIREN makes sure the supplier carries the referenced
// invoice's issuer SIREN, which every CDV puts in MDT-129 (BR-FR-CDV-13).
// With no SE party declared, the MDT-129 issuer becomes the supplier; an SE
// party that came without a SIREN gets it added.
func supplierWithReferencedSIREN(supplier *org.Party, cdar *CDAR) *org.Party {
issuer := referencedIssuerParty(cdar)
if issuer == nil {
return supplier
}
if supplier == nil {
return issuer
}
if partySIREN(supplier) == "" {
if siren := partySIREN(issuer); siren != "" {
supplier.Identities = append(supplier.Identities, sirenIdentity(siren))
}
}
return supplier
}
// referencedIssuerParty returns the first referenced document's issuer
// (MDT-129) as a party, or nil.
func referencedIssuerParty(cdar *CDAR) *org.Party {
for _, ack := range cdar.AcknowledgementDocuments {
if ack == nil {
continue
}
for _, ref := range ack.ReferenceReferencedDocument {
if ref == nil || ref.IssuerTradeParty == nil {
continue
}
if p := goblPartyFromCDAR(ref.IssuerTradeParty); p != nil {
return p
}
}
}
return nil
}
// sirenIdentity builds a SIREN identity under ISO 6523 scheme 0002.
func sirenIdentity(siren string) *org.Identity {
return &org.Identity{
Code: cbc.Code(siren),
Ext: tax.MakeExtensions().Set(iso.ExtKeySchemeID, schemeIDSIREN),
}
}
// parseCDARDateTime parses a CDAR CCYYMMDD or CCYYMMDDHHMMSS string into
// (date, optional time). The format attribute hints at the structure but
// the function is tolerant of either length.
func parseCDARDateTime(s string) (cal.Date, *cal.Time, error) {
if len(s) < 8 {
return cal.Date{}, nil, fmt.Errorf("invalid CDAR date %q", s)
}
y, err := strconv.Atoi(s[0:4])
if err != nil {
return cal.Date{}, nil, err
}
m, err := strconv.Atoi(s[4:6])
if err != nil {
return cal.Date{}, nil, err
}
d, err := strconv.Atoi(s[6:8])
if err != nil {
return cal.Date{}, nil, err
}
date := cal.MakeDate(y, time.Month(m), d)
if len(s) >= 14 {
hh, err := strconv.Atoi(s[8:10])
if err != nil {
return cal.Date{}, nil, err
}
mm, err := strconv.Atoi(s[10:12])
if err != nil {
return cal.Date{}, nil, err
}
ss, err := strconv.Atoi(s[12:14])
if err != nil {
return cal.Date{}, nil, err
}
t := cal.MakeTime(hh, mm, ss)
return date, &t, nil
}
return date, nil, nil
}