@vicacha-devs/medusa-plugin-einvoicing 0.0.0-stage → 0.2.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.
Files changed (70) hide show
  1. package/.medusa/server/src/admin/index.cjs +107 -0
  2. package/.medusa/server/src/admin/index.js +107 -0
  3. package/.medusa/server/src/api/admin/einvoicing/configs/route.d.ts +3 -0
  4. package/.medusa/server/src/api/admin/einvoicing/configs/route.js +23 -0
  5. package/.medusa/server/src/api/admin/einvoicing/configs/route.js.map +1 -0
  6. package/.medusa/server/src/api/admin/einvoicing/drivers/route.d.ts +2 -0
  7. package/.medusa/server/src/api/admin/einvoicing/drivers/route.js +6 -0
  8. package/.medusa/server/src/api/admin/einvoicing/drivers/route.js.map +1 -0
  9. package/.medusa/server/src/api/admin/einvoicing/route.d.ts +3 -0
  10. package/.medusa/server/src/api/admin/einvoicing/route.js +13 -0
  11. package/.medusa/server/src/api/admin/einvoicing/route.js.map +1 -0
  12. package/.medusa/server/src/api/middlewares.d.ts +2 -0
  13. package/.medusa/server/src/api/middlewares.js +21 -0
  14. package/.medusa/server/src/api/middlewares.js.map +1 -0
  15. package/.medusa/server/src/api/validators.d.ts +34 -0
  16. package/.medusa/server/src/api/validators.js +29 -0
  17. package/.medusa/server/src/api/validators.js.map +1 -0
  18. package/.medusa/server/src/index.d.ts +6 -0
  19. package/.medusa/server/src/index.js +7 -0
  20. package/.medusa/server/src/index.js.map +1 -0
  21. package/.medusa/server/src/modules/einvoicing/drivers/country-drivers.d.ts +34 -0
  22. package/.medusa/server/src/modules/einvoicing/drivers/country-drivers.js +221 -0
  23. package/.medusa/server/src/modules/einvoicing/drivers/country-drivers.js.map +1 -0
  24. package/.medusa/server/src/modules/einvoicing/index.d.ts +35 -0
  25. package/.medusa/server/src/modules/einvoicing/index.js +7 -0
  26. package/.medusa/server/src/modules/einvoicing/index.js.map +1 -0
  27. package/.medusa/server/src/modules/einvoicing/integrations/optional-bridges.d.ts +28 -0
  28. package/.medusa/server/src/modules/einvoicing/integrations/optional-bridges.js +67 -0
  29. package/.medusa/server/src/modules/einvoicing/integrations/optional-bridges.js.map +1 -0
  30. package/.medusa/server/src/modules/einvoicing/models/fiscal-config.d.ts +12 -0
  31. package/.medusa/server/src/modules/einvoicing/models/fiscal-config.js +14 -0
  32. package/.medusa/server/src/modules/einvoicing/models/fiscal-config.js.map +1 -0
  33. package/.medusa/server/src/modules/einvoicing/models/fiscal-document.d.ts +18 -0
  34. package/.medusa/server/src/modules/einvoicing/models/fiscal-document.js +24 -0
  35. package/.medusa/server/src/modules/einvoicing/models/fiscal-document.js.map +1 -0
  36. package/.medusa/server/src/modules/einvoicing/service.d.ts +70 -0
  37. package/.medusa/server/src/modules/einvoicing/service.js +112 -0
  38. package/.medusa/server/src/modules/einvoicing/service.js.map +1 -0
  39. package/.medusa/server/src/sdk/index.d.ts +4 -0
  40. package/.medusa/server/src/sdk/index.js +5 -0
  41. package/.medusa/server/src/sdk/index.js.map +1 -0
  42. package/.medusa/server/src/types/index.d.ts +66 -0
  43. package/.medusa/server/src/types/index.js +2 -0
  44. package/.medusa/server/src/types/index.js.map +1 -0
  45. package/.medusa/server/src/workflows/index.d.ts +43 -0
  46. package/.medusa/server/src/workflows/index.js +12 -0
  47. package/.medusa/server/src/workflows/index.js.map +1 -0
  48. package/README.md +58 -2
  49. package/package.json +93 -3
  50. package/src/__tests__/einvoicing.spec.ts +117 -0
  51. package/src/admin/i18n/en.json +4 -0
  52. package/src/admin/i18n/es.json +4 -0
  53. package/src/admin/i18n/index.ts +9 -0
  54. package/src/admin/routes/einvoicing/page.tsx +92 -0
  55. package/src/api/admin/einvoicing/configs/route.ts +39 -0
  56. package/src/api/admin/einvoicing/drivers/route.ts +16 -0
  57. package/src/api/admin/einvoicing/route.ts +31 -0
  58. package/src/api/middlewares.ts +28 -0
  59. package/src/api/validators.ts +30 -0
  60. package/src/index.ts +9 -0
  61. package/src/modules/einvoicing/drivers/country-drivers.ts +266 -0
  62. package/src/modules/einvoicing/index.ts +8 -0
  63. package/src/modules/einvoicing/integrations/optional-bridges.ts +83 -0
  64. package/src/modules/einvoicing/models/fiscal-config.ts +14 -0
  65. package/src/modules/einvoicing/models/fiscal-document.ts +24 -0
  66. package/src/modules/einvoicing/service.ts +156 -0
  67. package/src/sdk/index.ts +4 -0
  68. package/src/types/index.ts +82 -0
  69. package/src/workflows/index.ts +28 -0
  70. package/tsconfig.json +17 -0
@@ -0,0 +1,39 @@
1
+ import type {
2
+ AuthenticatedMedusaRequest,
3
+ MedusaResponse,
4
+ } from "@medusajs/framework/http"
5
+ import { EINVOICING_MODULE } from "../../../../modules/einvoicing"
6
+ import type EinvoicingModuleService from "../../../../modules/einvoicing/service"
7
+
8
+ export async function GET(
9
+ req: AuthenticatedMedusaRequest,
10
+ res: MedusaResponse
11
+ ) {
12
+ const service = req.scope.resolve(
13
+ EINVOICING_MODULE
14
+ ) as EinvoicingModuleService
15
+ const configs = await service.listFiscalConfigs({})
16
+ res.json({ configs })
17
+ }
18
+
19
+ export async function POST(
20
+ req: AuthenticatedMedusaRequest,
21
+ res: MedusaResponse
22
+ ) {
23
+ const service = req.scope.resolve(
24
+ EINVOICING_MODULE
25
+ ) as EinvoicingModuleService
26
+ const body = req.validatedBody as Record<string, any>
27
+ const config = await service.createFiscalConfigs({
28
+ country_code: String(body.country_code).toUpperCase(),
29
+ driver_id: String(body.driver_id),
30
+ is_active: body.is_active ?? true,
31
+ environment: body.environment ?? "sandbox",
32
+ issuer_tax_id: String(body.issuer_tax_id),
33
+ issuer_name: String(body.issuer_name),
34
+ prefix: body.prefix ?? "INV",
35
+ next_number: Number(body.next_number ?? 1),
36
+ settings: body.settings ?? null,
37
+ })
38
+ res.status(201).json({ config })
39
+ }
@@ -0,0 +1,16 @@
1
+ import type {
2
+ AuthenticatedMedusaRequest,
3
+ MedusaResponse,
4
+ } from "@medusajs/framework/http"
5
+ import { EINVOICING_MODULE } from "../../../../modules/einvoicing"
6
+ import type EinvoicingModuleService from "../../../../modules/einvoicing/service"
7
+
8
+ export async function GET(
9
+ req: AuthenticatedMedusaRequest,
10
+ res: MedusaResponse
11
+ ) {
12
+ const service = req.scope.resolve(
13
+ EINVOICING_MODULE
14
+ ) as EinvoicingModuleService
15
+ res.json({ drivers: await service.listDrivers() })
16
+ }
@@ -0,0 +1,31 @@
1
+ import type {
2
+ AuthenticatedMedusaRequest,
3
+ MedusaResponse,
4
+ } from "@medusajs/framework/http"
5
+ import { EINVOICING_MODULE } from "../../../modules/einvoicing"
6
+ import type EinvoicingModuleService from "../../../modules/einvoicing/service"
7
+ import type { IssueFiscalDocumentInput } from "../../../types"
8
+ import { issueFiscalDocumentWorkflow } from "../../../workflows"
9
+
10
+ export async function GET(
11
+ req: AuthenticatedMedusaRequest,
12
+ res: MedusaResponse
13
+ ) {
14
+ const service = req.scope.resolve(
15
+ EINVOICING_MODULE
16
+ ) as EinvoicingModuleService
17
+ const documents = await service.listFiscalDocuments(
18
+ {},
19
+ { order: { created_at: "DESC" }, take: 50 }
20
+ )
21
+ res.json({ documents })
22
+ }
23
+
24
+ export async function POST(
25
+ req: AuthenticatedMedusaRequest,
26
+ res: MedusaResponse
27
+ ) {
28
+ const input = req.validatedBody as IssueFiscalDocumentInput
29
+ const { result } = await issueFiscalDocumentWorkflow(req.scope).run({ input })
30
+ res.status(201).json({ document: result })
31
+ }
@@ -0,0 +1,28 @@
1
+ import {
2
+ authenticate,
3
+ defineMiddlewares,
4
+ validateAndTransformBody,
5
+ } from "@medusajs/framework/http"
6
+ import {
7
+ issueFiscalDocumentSchema,
8
+ upsertFiscalConfigSchema,
9
+ } from "./validators"
10
+
11
+ export default defineMiddlewares({
12
+ routes: [
13
+ {
14
+ matcher: "/admin/einvoicing*",
15
+ middlewares: [authenticate("user", ["session", "bearer", "api-key"])],
16
+ },
17
+ {
18
+ matcher: "/admin/einvoicing",
19
+ method: "POST",
20
+ middlewares: [validateAndTransformBody(issueFiscalDocumentSchema)],
21
+ },
22
+ {
23
+ matcher: "/admin/einvoicing/configs",
24
+ method: "POST",
25
+ middlewares: [validateAndTransformBody(upsertFiscalConfigSchema)],
26
+ },
27
+ ],
28
+ })
@@ -0,0 +1,30 @@
1
+ import { z } from "@medusajs/framework/zod"
2
+
3
+ export const issueFiscalDocumentSchema = z.object({
4
+ order_id: z.string().min(1),
5
+ country_code: z.string().min(2).max(2),
6
+ driver_id: z.string().optional(),
7
+ document_type: z
8
+ .enum(["invoice", "credit_note", "debit_note", "pos_receipt"])
9
+ .optional(),
10
+ currency_code: z.string().min(3).max(3).optional(),
11
+ subtotal: z.number().nonnegative().optional(),
12
+ tax_total: z.number().nonnegative().optional(),
13
+ total: z.number().nonnegative().optional(),
14
+ buyer_tax_id: z.string().nullable().optional(),
15
+ buyer_name: z.string().nullable().optional(),
16
+ buyer_email: z.string().email().nullable().optional(),
17
+ company_id: z.string().nullable().optional(),
18
+ })
19
+
20
+ export const upsertFiscalConfigSchema = z.object({
21
+ country_code: z.string().min(2).max(2),
22
+ driver_id: z.string().min(1),
23
+ is_active: z.boolean().optional(),
24
+ environment: z.enum(["sandbox", "production"]).optional(),
25
+ issuer_tax_id: z.string().min(1),
26
+ issuer_name: z.string().min(1),
27
+ prefix: z.string().min(1).optional(),
28
+ next_number: z.number().int().positive().optional(),
29
+ settings: z.record(z.string(), z.unknown()).nullable().optional(),
30
+ })
package/src/index.ts ADDED
@@ -0,0 +1,9 @@
1
+ export * from "./types"
2
+ export {
3
+ EINVOICING_MODULE,
4
+ default as EinvoicingModule,
5
+ } from "./modules/einvoicing"
6
+ export { EinvoicingModuleService } from "./modules/einvoicing/service"
7
+ export * from "./modules/einvoicing/drivers/country-drivers"
8
+ export * from "./modules/einvoicing/integrations/optional-bridges"
9
+ export * from "./workflows"
@@ -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, "&amp;")
12
+ .replace(/</g, "&lt;")
13
+ .replace(/>/g, "&gt;")
14
+ .replace(/"/g, "&quot;")
15
+ .replace(/'/g, "&apos;")
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,8 @@
1
+ import { Module } from "@medusajs/framework/utils"
2
+ import EinvoicingModuleService from "./service"
3
+
4
+ export const EINVOICING_MODULE = "einvoicing"
5
+
6
+ export default Module(EINVOICING_MODULE, {
7
+ service: EinvoicingModuleService,
8
+ })
@@ -0,0 +1,83 @@
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
+ }
66
+
67
+ /**
68
+ * Optional zero-hard-dependency lookup for `@vicacha-devs/medusa-plugin-dian`.
69
+ * Resolves the `"dian"` module when installed for Colombia (CO) e-invoicing.
70
+ */
71
+ export function resolveOptionalDianService(
72
+ container: { resolve?: (key: string) => any } | null | undefined,
73
+ dianModuleKey = "dian"
74
+ ): Record<string, any> | null {
75
+ if (!container?.resolve) {
76
+ return null
77
+ }
78
+ try {
79
+ return container.resolve(dianModuleKey) || null
80
+ } catch {
81
+ return null
82
+ }
83
+ }
@@ -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
+ })