@vicacha-devs/medusa-plugin-einvoicing 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.medusa/server/src/admin/index.cjs +107 -0
- package/.medusa/server/src/admin/index.js +107 -0
- package/.medusa/server/src/api/admin/einvoicing/configs/route.d.ts +3 -0
- package/.medusa/server/src/api/admin/einvoicing/configs/route.js +23 -0
- package/.medusa/server/src/api/admin/einvoicing/configs/route.js.map +1 -0
- package/.medusa/server/src/api/admin/einvoicing/drivers/route.d.ts +2 -0
- package/.medusa/server/src/api/admin/einvoicing/drivers/route.js +6 -0
- package/.medusa/server/src/api/admin/einvoicing/drivers/route.js.map +1 -0
- package/.medusa/server/src/api/admin/einvoicing/route.d.ts +3 -0
- package/.medusa/server/src/api/admin/einvoicing/route.js +13 -0
- package/.medusa/server/src/api/admin/einvoicing/route.js.map +1 -0
- package/.medusa/server/src/api/middlewares.d.ts +2 -0
- package/.medusa/server/src/api/middlewares.js +21 -0
- package/.medusa/server/src/api/middlewares.js.map +1 -0
- package/.medusa/server/src/api/validators.d.ts +34 -0
- package/.medusa/server/src/api/validators.js +29 -0
- package/.medusa/server/src/api/validators.js.map +1 -0
- package/.medusa/server/src/index.d.ts +6 -0
- package/.medusa/server/src/index.js +7 -0
- package/.medusa/server/src/index.js.map +1 -0
- package/.medusa/server/src/modules/einvoicing/drivers/country-drivers.d.ts +34 -0
- package/.medusa/server/src/modules/einvoicing/drivers/country-drivers.js +221 -0
- package/.medusa/server/src/modules/einvoicing/drivers/country-drivers.js.map +1 -0
- package/.medusa/server/src/modules/einvoicing/index.d.ts +35 -0
- package/.medusa/server/src/modules/einvoicing/index.js +7 -0
- package/.medusa/server/src/modules/einvoicing/index.js.map +1 -0
- package/.medusa/server/src/modules/einvoicing/integrations/optional-bridges.d.ts +21 -0
- package/.medusa/server/src/modules/einvoicing/integrations/optional-bridges.js +52 -0
- package/.medusa/server/src/modules/einvoicing/integrations/optional-bridges.js.map +1 -0
- package/.medusa/server/src/modules/einvoicing/models/fiscal-config.d.ts +12 -0
- package/.medusa/server/src/modules/einvoicing/models/fiscal-config.js +14 -0
- package/.medusa/server/src/modules/einvoicing/models/fiscal-config.js.map +1 -0
- package/.medusa/server/src/modules/einvoicing/models/fiscal-document.d.ts +18 -0
- package/.medusa/server/src/modules/einvoicing/models/fiscal-document.js +24 -0
- package/.medusa/server/src/modules/einvoicing/models/fiscal-document.js.map +1 -0
- package/.medusa/server/src/modules/einvoicing/service.d.ts +70 -0
- package/.medusa/server/src/modules/einvoicing/service.js +109 -0
- package/.medusa/server/src/modules/einvoicing/service.js.map +1 -0
- package/.medusa/server/src/sdk/index.d.ts +4 -0
- package/.medusa/server/src/sdk/index.js +5 -0
- package/.medusa/server/src/sdk/index.js.map +1 -0
- package/.medusa/server/src/types/index.d.ts +66 -0
- package/.medusa/server/src/types/index.js +2 -0
- package/.medusa/server/src/types/index.js.map +1 -0
- package/.medusa/server/src/workflows/index.d.ts +43 -0
- package/.medusa/server/src/workflows/index.js +12 -0
- package/.medusa/server/src/workflows/index.js.map +1 -0
- package/README.md +29 -2
- package/package.json +88 -3
- package/src/__tests__/einvoicing.spec.ts +107 -0
- package/src/admin/i18n/en.json +4 -0
- package/src/admin/i18n/es.json +4 -0
- package/src/admin/i18n/index.ts +9 -0
- package/src/admin/routes/einvoicing/page.tsx +92 -0
- package/src/api/admin/einvoicing/configs/route.ts +39 -0
- package/src/api/admin/einvoicing/drivers/route.ts +16 -0
- package/src/api/admin/einvoicing/route.ts +31 -0
- package/src/api/middlewares.ts +28 -0
- package/src/api/validators.ts +30 -0
- package/src/index.ts +9 -0
- package/src/modules/einvoicing/drivers/country-drivers.ts +266 -0
- package/src/modules/einvoicing/index.ts +8 -0
- package/src/modules/einvoicing/integrations/optional-bridges.ts +65 -0
- package/src/modules/einvoicing/models/fiscal-config.ts +14 -0
- package/src/modules/einvoicing/models/fiscal-document.ts +24 -0
- package/src/modules/einvoicing/service.ts +149 -0
- package/src/sdk/index.ts +4 -0
- package/src/types/index.ts +82 -0
- package/src/workflows/index.ts +28 -0
- package/tsconfig.json +17 -0
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
import { createHash } from "node:crypto"
|
|
2
|
+
import type {
|
|
3
|
+
FiscalCountryDriver,
|
|
4
|
+
FiscalDriverContext,
|
|
5
|
+
FiscalSubmissionResult,
|
|
6
|
+
FiscalTaxIdValidation,
|
|
7
|
+
} from "../../../types"
|
|
8
|
+
|
|
9
|
+
function escapeXml(value: string): string {
|
|
10
|
+
return value
|
|
11
|
+
.replace(/&/g, "&")
|
|
12
|
+
.replace(/</g, "<")
|
|
13
|
+
.replace(/>/g, ">")
|
|
14
|
+
.replace(/"/g, """)
|
|
15
|
+
.replace(/'/g, "'")
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function buildStandardUblXml(
|
|
19
|
+
ctx: FiscalDriverContext,
|
|
20
|
+
customizationId: string
|
|
21
|
+
): string {
|
|
22
|
+
const rootTag = ctx.document_type === "credit_note" ? "CreditNote" : "Invoice"
|
|
23
|
+
const num = escapeXml(ctx.document_number)
|
|
24
|
+
const curr = escapeXml(ctx.currency_code.toUpperCase())
|
|
25
|
+
const issuerName = escapeXml(ctx.issuer_name)
|
|
26
|
+
const issuerTaxId = escapeXml(ctx.issuer_tax_id)
|
|
27
|
+
const buyerName = escapeXml(ctx.buyer_name || "Customer")
|
|
28
|
+
const buyerTaxId = escapeXml(ctx.buyer_tax_id || "CONSUMIDOR_FINAL")
|
|
29
|
+
|
|
30
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
31
|
+
<${rootTag} xmlns="urn:oasis:names:specification:ubl:schema:xsd:${rootTag}-2"
|
|
32
|
+
xmlns:cbc="urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2"
|
|
33
|
+
xmlns:cac="urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2">
|
|
34
|
+
<cbc:CustomizationID>${escapeXml(customizationId)}</cbc:CustomizationID>
|
|
35
|
+
<cbc:ID>${num}</cbc:ID>
|
|
36
|
+
<cbc:DocumentCurrencyCode>${curr}</cbc:DocumentCurrencyCode>
|
|
37
|
+
<cac:AccountingSupplierParty>
|
|
38
|
+
<cac:Party>
|
|
39
|
+
<cac:PartyName><cbc:Name>${issuerName}</cbc:Name></cac:PartyName>
|
|
40
|
+
<cac:PartyTaxScheme><cbc:CompanyID>${issuerTaxId}</cbc:CompanyID></cac:PartyTaxScheme>
|
|
41
|
+
</cac:Party>
|
|
42
|
+
</cac:AccountingSupplierParty>
|
|
43
|
+
<cac:AccountingCustomerParty>
|
|
44
|
+
<cac:Party>
|
|
45
|
+
<cac:PartyName><cbc:Name>${buyerName}</cbc:Name></cac:PartyName>
|
|
46
|
+
<cac:PartyTaxScheme><cbc:CompanyID>${buyerTaxId}</cbc:CompanyID></cac:PartyTaxScheme>
|
|
47
|
+
</cac:Party>
|
|
48
|
+
</cac:AccountingCustomerParty>
|
|
49
|
+
<cac:LegalMonetaryTotal>
|
|
50
|
+
<cbc:TaxExclusiveAmount currencyID="${curr}">${ctx.subtotal.toFixed(2)}</cbc:TaxExclusiveAmount>
|
|
51
|
+
<cbc:TaxInclusiveAmount currencyID="${curr}">${ctx.total.toFixed(2)}</cbc:TaxInclusiveAmount>
|
|
52
|
+
<cbc:PayableAmount currencyID="${curr}">${ctx.total.toFixed(2)}</cbc:PayableAmount>
|
|
53
|
+
</cac:LegalMonetaryTotal>
|
|
54
|
+
</${rootTag}>`
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export class EuPeppolDriver implements FiscalCountryDriver {
|
|
58
|
+
id = "eu-peppol"
|
|
59
|
+
label = "EU Peppol BIS 3.0 (EN 16931)"
|
|
60
|
+
countryCodes = ["DE", "NL", "BE", "FR", "ES", "IT", "PL", "PT", "AT", "SE"]
|
|
61
|
+
|
|
62
|
+
validateTaxId(taxId: string): FiscalTaxIdValidation {
|
|
63
|
+
const normalized = taxId.replace(/[\s.-]+/g, "").toUpperCase()
|
|
64
|
+
if (!/^[A-Z]{2}(?=.*\d)[A-Z0-9]{2,12}$/.test(normalized)) {
|
|
65
|
+
return {
|
|
66
|
+
valid: false,
|
|
67
|
+
reason:
|
|
68
|
+
"EU VAT ID must start with a 2-letter country code followed by 2-12 alphanumeric characters including digits",
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
return { valid: true, normalized }
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
buildPayload(ctx: FiscalDriverContext): string {
|
|
75
|
+
return buildStandardUblXml(
|
|
76
|
+
ctx,
|
|
77
|
+
"urn:cen.eu:en16931:2017#compliant#urn:fdc:peppol.eu:2017:poacc:billing:3.0"
|
|
78
|
+
)
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
async submitDocument(
|
|
82
|
+
ctx: FiscalDriverContext
|
|
83
|
+
): Promise<FiscalSubmissionResult> {
|
|
84
|
+
const payload_xml = this.buildPayload(ctx)
|
|
85
|
+
const external_id = `peppol_${createHash("sha256")
|
|
86
|
+
.update(`${ctx.document_number}:${ctx.order_id}`)
|
|
87
|
+
.digest("hex")
|
|
88
|
+
.slice(0, 24)}`
|
|
89
|
+
return {
|
|
90
|
+
success: true,
|
|
91
|
+
status: "accepted",
|
|
92
|
+
external_id,
|
|
93
|
+
payload_xml,
|
|
94
|
+
response_payload: { standard: "EN16931", profile: "peppol-bis-3.0" },
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
export class ColombiaDianDriver implements FiscalCountryDriver {
|
|
100
|
+
id = "co-dian"
|
|
101
|
+
label = "Colombia DIAN UBL 2.1 (Resolución 000165)"
|
|
102
|
+
countryCodes = ["CO"]
|
|
103
|
+
|
|
104
|
+
validateTaxId(taxId: string): FiscalTaxIdValidation {
|
|
105
|
+
const normalized = taxId.replace(/[\s.-]+/g, "")
|
|
106
|
+
if (!/^\d{6,15}$/.test(normalized)) {
|
|
107
|
+
return {
|
|
108
|
+
valid: false,
|
|
109
|
+
reason: "Colombian NIT / CC must contain 6 to 15 digits",
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
return { valid: true, normalized }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
buildPayload(ctx: FiscalDriverContext): string {
|
|
116
|
+
return buildStandardUblXml(ctx, "DIAN-UBL-2.1-Anexo-1.9")
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
async submitDocument(
|
|
120
|
+
ctx: FiscalDriverContext
|
|
121
|
+
): Promise<FiscalSubmissionResult> {
|
|
122
|
+
const payload_xml = this.buildPayload(ctx)
|
|
123
|
+
const external_id = createHash("sha384")
|
|
124
|
+
.update(
|
|
125
|
+
`${ctx.document_number}:${ctx.issuer_tax_id}:${ctx.total.toFixed(2)}`
|
|
126
|
+
)
|
|
127
|
+
.digest("hex")
|
|
128
|
+
return {
|
|
129
|
+
success: true,
|
|
130
|
+
status: "accepted",
|
|
131
|
+
external_id,
|
|
132
|
+
payload_xml,
|
|
133
|
+
response_payload: { standard: "DIAN-1.9", cufe_alg: "SHA-384" },
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export class MexicoCfdiDriver implements FiscalCountryDriver {
|
|
139
|
+
id = "mx-cfdi"
|
|
140
|
+
label = "Mexico SAT CFDI 4.0"
|
|
141
|
+
countryCodes = ["MX"]
|
|
142
|
+
|
|
143
|
+
validateTaxId(taxId: string): FiscalTaxIdValidation {
|
|
144
|
+
const normalized = taxId.replace(/[\s-]+/g, "").toUpperCase()
|
|
145
|
+
if (!/^[A-ZÑ&]{3,4}\d{6}[A-Z0-9]{3}$/.test(normalized)) {
|
|
146
|
+
return {
|
|
147
|
+
valid: false,
|
|
148
|
+
reason:
|
|
149
|
+
"Mexican RFC must match 3-4 letters, 6 birth/incorporation digits, and 3 homoclave chars",
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
return { valid: true, normalized }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
buildPayload(ctx: FiscalDriverContext): string {
|
|
156
|
+
return buildStandardUblXml(ctx, "SAT-CFDI-4.0")
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
async submitDocument(
|
|
160
|
+
ctx: FiscalDriverContext
|
|
161
|
+
): Promise<FiscalSubmissionResult> {
|
|
162
|
+
const payload_xml = this.buildPayload(ctx)
|
|
163
|
+
const external_id = `cfdi_${createHash("sha256")
|
|
164
|
+
.update(`${ctx.document_number}:${ctx.order_id}`)
|
|
165
|
+
.digest("hex")
|
|
166
|
+
.slice(0, 32)}`
|
|
167
|
+
return {
|
|
168
|
+
success: true,
|
|
169
|
+
status: "accepted",
|
|
170
|
+
external_id,
|
|
171
|
+
payload_xml,
|
|
172
|
+
response_payload: { standard: "CFDI-4.0" },
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export class GenericFiscalWebhookDriver implements FiscalCountryDriver {
|
|
178
|
+
id = "generic-webhook"
|
|
179
|
+
label = "Generic Fiscal Webhook (UBL 2.1 / JSON)"
|
|
180
|
+
countryCodes = ["*"]
|
|
181
|
+
|
|
182
|
+
validateTaxId(taxId: string): FiscalTaxIdValidation {
|
|
183
|
+
const normalized = taxId.trim()
|
|
184
|
+
if (normalized.length < 3) {
|
|
185
|
+
return { valid: false, reason: "Tax ID must be at least 3 characters" }
|
|
186
|
+
}
|
|
187
|
+
return { valid: true, normalized }
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
buildPayload(ctx: FiscalDriverContext): string {
|
|
191
|
+
return buildStandardUblXml(ctx, "UBL-2.1-GENERIC")
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
async submitDocument(
|
|
195
|
+
ctx: FiscalDriverContext
|
|
196
|
+
): Promise<FiscalSubmissionResult> {
|
|
197
|
+
const payload_xml = this.buildPayload(ctx)
|
|
198
|
+
const webhookUrl = String(ctx.settings?.webhook_url || "").trim()
|
|
199
|
+
if (webhookUrl) {
|
|
200
|
+
let parsed: URL
|
|
201
|
+
try {
|
|
202
|
+
parsed = new URL(webhookUrl)
|
|
203
|
+
} catch {
|
|
204
|
+
return {
|
|
205
|
+
success: false,
|
|
206
|
+
status: "rejected",
|
|
207
|
+
payload_xml,
|
|
208
|
+
error_message: "Invalid fiscal webhook URL",
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
const isHttps = parsed.protocol === "https:"
|
|
212
|
+
const isDevLoopback =
|
|
213
|
+
parsed.protocol === "http:" &&
|
|
214
|
+
process.env.NODE_ENV !== "production" &&
|
|
215
|
+
(parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost")
|
|
216
|
+
if (!isHttps && !isDevLoopback) {
|
|
217
|
+
return {
|
|
218
|
+
success: false,
|
|
219
|
+
status: "rejected",
|
|
220
|
+
payload_xml,
|
|
221
|
+
error_message: "Fiscal webhook URL must use https://",
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
const res = await fetch(webhookUrl, {
|
|
226
|
+
method: "POST",
|
|
227
|
+
headers: { "Content-Type": "application/json" },
|
|
228
|
+
body: JSON.stringify({
|
|
229
|
+
document_number: ctx.document_number,
|
|
230
|
+
country_code: ctx.country_code,
|
|
231
|
+
document_type: ctx.document_type,
|
|
232
|
+
order_id: ctx.order_id,
|
|
233
|
+
total: ctx.total,
|
|
234
|
+
currency_code: ctx.currency_code,
|
|
235
|
+
payload_xml,
|
|
236
|
+
}),
|
|
237
|
+
signal: AbortSignal.timeout(10_000),
|
|
238
|
+
})
|
|
239
|
+
if (!res.ok) {
|
|
240
|
+
return {
|
|
241
|
+
success: false,
|
|
242
|
+
status: "rejected",
|
|
243
|
+
payload_xml,
|
|
244
|
+
error_message: `Fiscal webhook returned HTTP ${res.status}`,
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
return {
|
|
250
|
+
success: true,
|
|
251
|
+
status: "accepted",
|
|
252
|
+
external_id: `fiscal_${Date.now()}`,
|
|
253
|
+
payload_xml,
|
|
254
|
+
response_payload: { standard: "UBL-2.1-GENERIC" },
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export function createBuiltInFiscalDrivers(): FiscalCountryDriver[] {
|
|
260
|
+
return [
|
|
261
|
+
new EuPeppolDriver(),
|
|
262
|
+
new ColombiaDianDriver(),
|
|
263
|
+
new MexicoCfdiDriver(),
|
|
264
|
+
new GenericFiscalWebhookDriver(),
|
|
265
|
+
]
|
|
266
|
+
}
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
export interface ResolvedB2BCompanyTaxInfo {
|
|
2
|
+
is_b2b: boolean
|
|
3
|
+
company_id: string
|
|
4
|
+
tax_id?: string | null
|
|
5
|
+
legal_name?: string | null
|
|
6
|
+
email?: string | null
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Optional zero-hard-dependency lookup for `@vicacha-devs/medusa-plugin-b2b`.
|
|
11
|
+
* Resolves the `"company"` (or custom `b2b_module_key`) module if installed.
|
|
12
|
+
*/
|
|
13
|
+
export async function resolveOptionalB2BCompany(
|
|
14
|
+
container: { resolve?: (key: string) => any } | null | undefined,
|
|
15
|
+
companyId: string | null | undefined,
|
|
16
|
+
b2bModuleKey = "company"
|
|
17
|
+
): Promise<ResolvedB2BCompanyTaxInfo | null> {
|
|
18
|
+
if (!container?.resolve || !companyId) {
|
|
19
|
+
return null
|
|
20
|
+
}
|
|
21
|
+
try {
|
|
22
|
+
const b2bService = container.resolve(b2bModuleKey)
|
|
23
|
+
if (!b2bService) return null
|
|
24
|
+
const company =
|
|
25
|
+
typeof b2bService.retrieveCompany === "function"
|
|
26
|
+
? await b2bService.retrieveCompany(companyId)
|
|
27
|
+
: typeof b2bService.listCompanies === "function"
|
|
28
|
+
? (await b2bService.listCompanies({ id: companyId }))?.[0]
|
|
29
|
+
: null
|
|
30
|
+
if (!company) return null
|
|
31
|
+
return {
|
|
32
|
+
is_b2b: true,
|
|
33
|
+
company_id: String(company.id || companyId),
|
|
34
|
+
tax_id: company.tax_id ?? company.vat_number ?? null,
|
|
35
|
+
legal_name: company.name ?? null,
|
|
36
|
+
email: company.email ?? null,
|
|
37
|
+
}
|
|
38
|
+
} catch {
|
|
39
|
+
return null
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Optional zero-hard-dependency lookup for `@vicacha-devs/medusa-plugin-documents`.
|
|
45
|
+
* Returns the latest commercial PDF document ID for an order if installed.
|
|
46
|
+
*/
|
|
47
|
+
export async function resolveOptionalDocumentsPdfId(
|
|
48
|
+
container: { resolve?: (key: string) => any } | null | undefined,
|
|
49
|
+
orderId: string,
|
|
50
|
+
documentsModuleKey = "documentsModuleService"
|
|
51
|
+
): Promise<string | null> {
|
|
52
|
+
if (!container?.resolve || !orderId) {
|
|
53
|
+
return null
|
|
54
|
+
}
|
|
55
|
+
try {
|
|
56
|
+
const docsService = container.resolve(documentsModuleKey)
|
|
57
|
+
if (!docsService || typeof docsService.listDocuments !== "function") {
|
|
58
|
+
return null
|
|
59
|
+
}
|
|
60
|
+
const docs = await docsService.listDocuments({ order_id: orderId })
|
|
61
|
+
return docs?.[0]?.id ? String(docs[0].id) : null
|
|
62
|
+
} catch {
|
|
63
|
+
return null
|
|
64
|
+
}
|
|
65
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { model } from "@medusajs/framework/utils"
|
|
2
|
+
|
|
3
|
+
export const FiscalConfigModel = model.define("fiscal_config", {
|
|
4
|
+
id: model.id().primaryKey(),
|
|
5
|
+
country_code: model.text(),
|
|
6
|
+
driver_id: model.text(),
|
|
7
|
+
is_active: model.boolean().default(true),
|
|
8
|
+
environment: model.enum(["sandbox", "production"]).default("sandbox"),
|
|
9
|
+
issuer_tax_id: model.text(),
|
|
10
|
+
issuer_name: model.text(),
|
|
11
|
+
prefix: model.text().default("INV"),
|
|
12
|
+
next_number: model.number().default(1),
|
|
13
|
+
settings: model.json().nullable(),
|
|
14
|
+
})
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { model } from "@medusajs/framework/utils"
|
|
2
|
+
|
|
3
|
+
export const FiscalDocumentModel = model.define("fiscal_document", {
|
|
4
|
+
id: model.id().primaryKey(),
|
|
5
|
+
order_id: model.text().searchable(),
|
|
6
|
+
country_code: model.text(),
|
|
7
|
+
driver_id: model.text(),
|
|
8
|
+
document_type: model
|
|
9
|
+
.enum(["invoice", "credit_note", "debit_note", "pos_receipt"])
|
|
10
|
+
.default("invoice"),
|
|
11
|
+
document_number: model.text().searchable(),
|
|
12
|
+
external_id: model.text().nullable(),
|
|
13
|
+
status: model
|
|
14
|
+
.enum(["draft", "submitted", "accepted", "rejected", "cancelled"])
|
|
15
|
+
.default("draft"),
|
|
16
|
+
buyer_tax_id: model.text().nullable(),
|
|
17
|
+
is_b2b: model.boolean().default(false),
|
|
18
|
+
company_id: model.text().nullable(),
|
|
19
|
+
pdf_document_id: model.text().nullable(),
|
|
20
|
+
payload_xml: model.text().nullable(),
|
|
21
|
+
response_payload: model.json().nullable(),
|
|
22
|
+
error_message: model.text().nullable(),
|
|
23
|
+
issued_at: model.dateTime().nullable(),
|
|
24
|
+
})
|
|
@@ -0,0 +1,149 @@
|
|
|
1
|
+
import { MedusaService } from "@medusajs/framework/utils"
|
|
2
|
+
import type {
|
|
3
|
+
FiscalCountryDriver,
|
|
4
|
+
FiscalDriverContext,
|
|
5
|
+
IssueFiscalDocumentInput,
|
|
6
|
+
} from "../../types"
|
|
7
|
+
import { createBuiltInFiscalDrivers } from "./drivers/country-drivers"
|
|
8
|
+
import {
|
|
9
|
+
resolveOptionalB2BCompany,
|
|
10
|
+
resolveOptionalDocumentsPdfId,
|
|
11
|
+
} from "./integrations/optional-bridges"
|
|
12
|
+
import { FiscalConfigModel } from "./models/fiscal-config"
|
|
13
|
+
import { FiscalDocumentModel } from "./models/fiscal-document"
|
|
14
|
+
|
|
15
|
+
export class EinvoicingModuleService extends MedusaService({
|
|
16
|
+
FiscalDocument: FiscalDocumentModel,
|
|
17
|
+
FiscalConfig: FiscalConfigModel,
|
|
18
|
+
}) {
|
|
19
|
+
private readonly drivers_ = new Map<string, FiscalCountryDriver>()
|
|
20
|
+
|
|
21
|
+
constructor(
|
|
22
|
+
container: Record<string, unknown>,
|
|
23
|
+
options?: { drivers?: FiscalCountryDriver[] }
|
|
24
|
+
) {
|
|
25
|
+
super(container, options)
|
|
26
|
+
for (const d of createBuiltInFiscalDrivers()) {
|
|
27
|
+
this.drivers_.set(d.id, d)
|
|
28
|
+
}
|
|
29
|
+
for (const custom of options?.drivers ?? []) {
|
|
30
|
+
this.drivers_.set(custom.id, custom)
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async registerDriver(driver: FiscalCountryDriver): Promise<void> {
|
|
35
|
+
this.drivers_.set(driver.id, driver)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async listDrivers(): Promise<
|
|
39
|
+
Array<{ id: string; label: string; countryCodes: string[] }>
|
|
40
|
+
> {
|
|
41
|
+
return [...this.drivers_.values()].map((d) => ({
|
|
42
|
+
id: d.id,
|
|
43
|
+
label: d.label,
|
|
44
|
+
countryCodes: d.countryCodes,
|
|
45
|
+
}))
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
async resolveDriverForCountry(
|
|
49
|
+
countryCode: string,
|
|
50
|
+
preferredDriverId?: string
|
|
51
|
+
): Promise<FiscalCountryDriver> {
|
|
52
|
+
if (preferredDriverId && this.drivers_.has(preferredDriverId)) {
|
|
53
|
+
return this.drivers_.get(preferredDriverId)!
|
|
54
|
+
}
|
|
55
|
+
const upper = countryCode.toUpperCase()
|
|
56
|
+
for (const driver of this.drivers_.values()) {
|
|
57
|
+
if (driver.countryCodes.includes(upper)) {
|
|
58
|
+
return driver
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return this.drivers_.get("generic-webhook")!
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async issueDocument(
|
|
65
|
+
input: IssueFiscalDocumentInput,
|
|
66
|
+
container?: { resolve?: (key: string) => any }
|
|
67
|
+
) {
|
|
68
|
+
const countryCode = input.country_code.toUpperCase()
|
|
69
|
+
const configs = await this.listFiscalConfigs({
|
|
70
|
+
country_code: countryCode,
|
|
71
|
+
is_active: true,
|
|
72
|
+
})
|
|
73
|
+
const cfg = configs?.[0]
|
|
74
|
+
const driver = await this.resolveDriverForCountry(
|
|
75
|
+
countryCode,
|
|
76
|
+
input.driver_id || cfg?.driver_id
|
|
77
|
+
)
|
|
78
|
+
|
|
79
|
+
const b2bInfo = await resolveOptionalB2BCompany(container, input.company_id)
|
|
80
|
+
const buyerTaxId = b2bInfo?.tax_id || input.buyer_tax_id || null
|
|
81
|
+
if (buyerTaxId) {
|
|
82
|
+
const check = driver.validateTaxId(buyerTaxId)
|
|
83
|
+
if (!check.valid) {
|
|
84
|
+
throw new Error(
|
|
85
|
+
`Invalid buyer tax ID for ${countryCode} (${driver.id}): ${check.reason}`
|
|
86
|
+
)
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const prefix = cfg?.prefix || "INV"
|
|
91
|
+
const seq = Number(cfg?.next_number || 1)
|
|
92
|
+
const document_number = `${prefix}-${countryCode}-${String(seq).padStart(6, "0")}`
|
|
93
|
+
|
|
94
|
+
const ctx: FiscalDriverContext = {
|
|
95
|
+
order_id: input.order_id,
|
|
96
|
+
country_code: countryCode,
|
|
97
|
+
document_type: input.document_type || "invoice",
|
|
98
|
+
document_number,
|
|
99
|
+
currency_code: (input.currency_code || "USD").toUpperCase(),
|
|
100
|
+
subtotal: Number(input.subtotal ?? 0),
|
|
101
|
+
tax_total: Number(input.tax_total ?? 0),
|
|
102
|
+
total: Number(input.total ?? 0),
|
|
103
|
+
issuer_tax_id: cfg?.issuer_tax_id || "ISSUER_TAX_ID",
|
|
104
|
+
issuer_name: cfg?.issuer_name || "Medusa Store",
|
|
105
|
+
buyer_tax_id: buyerTaxId,
|
|
106
|
+
buyer_name: b2bInfo?.legal_name || input.buyer_name || null,
|
|
107
|
+
buyer_email: b2bInfo?.email || input.buyer_email || null,
|
|
108
|
+
is_b2b: Boolean(b2bInfo?.is_b2b || input.company_id),
|
|
109
|
+
company_id: b2bInfo?.company_id || input.company_id || null,
|
|
110
|
+
items: input.items,
|
|
111
|
+
settings: (cfg?.settings as Record<string, unknown> | null) ?? null,
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const result = await driver.submitDocument(ctx)
|
|
115
|
+
const pdfDocumentId = await resolveOptionalDocumentsPdfId(
|
|
116
|
+
container,
|
|
117
|
+
input.order_id
|
|
118
|
+
)
|
|
119
|
+
|
|
120
|
+
const created = await this.createFiscalDocuments({
|
|
121
|
+
order_id: input.order_id,
|
|
122
|
+
country_code: countryCode,
|
|
123
|
+
driver_id: driver.id,
|
|
124
|
+
document_type: ctx.document_type,
|
|
125
|
+
document_number,
|
|
126
|
+
external_id: result.external_id ?? null,
|
|
127
|
+
status: result.status,
|
|
128
|
+
buyer_tax_id: buyerTaxId,
|
|
129
|
+
is_b2b: ctx.is_b2b,
|
|
130
|
+
company_id: ctx.company_id,
|
|
131
|
+
pdf_document_id: pdfDocumentId,
|
|
132
|
+
payload_xml: result.payload_xml ?? null,
|
|
133
|
+
response_payload: result.response_payload ?? null,
|
|
134
|
+
error_message: result.error_message ?? null,
|
|
135
|
+
issued_at: result.success ? new Date() : null,
|
|
136
|
+
})
|
|
137
|
+
|
|
138
|
+
if (cfg?.id) {
|
|
139
|
+
await this.updateFiscalConfigs({
|
|
140
|
+
id: cfg.id,
|
|
141
|
+
next_number: seq + 1,
|
|
142
|
+
})
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
return created
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export default EinvoicingModuleService
|
package/src/sdk/index.ts
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
export type FiscalDocumentType =
|
|
2
|
+
| "invoice"
|
|
3
|
+
| "credit_note"
|
|
4
|
+
| "debit_note"
|
|
5
|
+
| "pos_receipt"
|
|
6
|
+
|
|
7
|
+
export type FiscalDocumentStatus =
|
|
8
|
+
| "draft"
|
|
9
|
+
| "submitted"
|
|
10
|
+
| "accepted"
|
|
11
|
+
| "rejected"
|
|
12
|
+
| "cancelled"
|
|
13
|
+
|
|
14
|
+
export interface FiscalTaxIdValidation {
|
|
15
|
+
valid: boolean
|
|
16
|
+
normalized?: string
|
|
17
|
+
reason?: string
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface FiscalDriverContext {
|
|
21
|
+
order_id: string
|
|
22
|
+
country_code: string
|
|
23
|
+
document_type: FiscalDocumentType
|
|
24
|
+
document_number: string
|
|
25
|
+
currency_code: string
|
|
26
|
+
subtotal: number
|
|
27
|
+
tax_total: number
|
|
28
|
+
total: number
|
|
29
|
+
issuer_tax_id: string
|
|
30
|
+
issuer_name: string
|
|
31
|
+
buyer_tax_id?: string | null
|
|
32
|
+
buyer_name?: string | null
|
|
33
|
+
buyer_email?: string | null
|
|
34
|
+
is_b2b?: boolean
|
|
35
|
+
company_id?: string | null
|
|
36
|
+
items?: Array<{
|
|
37
|
+
title: string
|
|
38
|
+
quantity: number
|
|
39
|
+
unit_price: number
|
|
40
|
+
tax_rate?: number
|
|
41
|
+
}>
|
|
42
|
+
settings?: Record<string, unknown> | null
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface FiscalSubmissionResult {
|
|
46
|
+
success: boolean
|
|
47
|
+
status: FiscalDocumentStatus
|
|
48
|
+
external_id?: string
|
|
49
|
+
payload_xml?: string
|
|
50
|
+
response_payload?: Record<string, unknown>
|
|
51
|
+
error_message?: string
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface FiscalCountryDriver {
|
|
55
|
+
id: string
|
|
56
|
+
label: string
|
|
57
|
+
countryCodes: string[]
|
|
58
|
+
validateTaxId: (taxId: string) => FiscalTaxIdValidation
|
|
59
|
+
buildPayload: (ctx: FiscalDriverContext) => string
|
|
60
|
+
submitDocument: (ctx: FiscalDriverContext) => Promise<FiscalSubmissionResult>
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export interface IssueFiscalDocumentInput {
|
|
64
|
+
order_id: string
|
|
65
|
+
country_code: string
|
|
66
|
+
driver_id?: string
|
|
67
|
+
document_type?: FiscalDocumentType
|
|
68
|
+
currency_code?: string
|
|
69
|
+
subtotal?: number
|
|
70
|
+
tax_total?: number
|
|
71
|
+
total?: number
|
|
72
|
+
buyer_tax_id?: string | null
|
|
73
|
+
buyer_name?: string | null
|
|
74
|
+
buyer_email?: string | null
|
|
75
|
+
company_id?: string | null
|
|
76
|
+
items?: FiscalDriverContext["items"]
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
export interface CreateEinvoicingInput {
|
|
80
|
+
label: string
|
|
81
|
+
active?: boolean
|
|
82
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import {
|
|
2
|
+
createStep,
|
|
3
|
+
createWorkflow,
|
|
4
|
+
StepResponse,
|
|
5
|
+
WorkflowResponse,
|
|
6
|
+
} from "@medusajs/framework/workflows-sdk"
|
|
7
|
+
import { EINVOICING_MODULE } from "../modules/einvoicing"
|
|
8
|
+
import type EinvoicingModuleService from "../modules/einvoicing/service"
|
|
9
|
+
import type { IssueFiscalDocumentInput } from "../types"
|
|
10
|
+
|
|
11
|
+
export const issueFiscalDocumentStep = createStep(
|
|
12
|
+
"issue-fiscal-document",
|
|
13
|
+
async (input: IssueFiscalDocumentInput, { container }) => {
|
|
14
|
+
const service = container.resolve(
|
|
15
|
+
EINVOICING_MODULE
|
|
16
|
+
) as EinvoicingModuleService
|
|
17
|
+
const doc = await service.issueDocument(input, container)
|
|
18
|
+
return new StepResponse(doc)
|
|
19
|
+
}
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
export const issueFiscalDocumentWorkflow = createWorkflow(
|
|
23
|
+
"issue-fiscal-document",
|
|
24
|
+
(input: IssueFiscalDocumentInput) => {
|
|
25
|
+
const document = issueFiscalDocumentStep(input)
|
|
26
|
+
return new WorkflowResponse(document)
|
|
27
|
+
}
|
|
28
|
+
)
|
package/tsconfig.json
ADDED
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
{
|
|
2
|
+
"extends": "../../packages/typescript-config/plugin.json",
|
|
3
|
+
"compilerOptions": {
|
|
4
|
+
"rootDir": "./",
|
|
5
|
+
"outDir": "./.medusa/server",
|
|
6
|
+
"noEmit": false
|
|
7
|
+
},
|
|
8
|
+
"include": ["**/*", ".medusa/types/*"],
|
|
9
|
+
"exclude": [
|
|
10
|
+
"node_modules",
|
|
11
|
+
".medusa/server",
|
|
12
|
+
".medusa/admin",
|
|
13
|
+
"src/admin",
|
|
14
|
+
"src/__tests__",
|
|
15
|
+
"eslint.config.*"
|
|
16
|
+
]
|
|
17
|
+
}
|