@vicacha-devs/medusa-plugin-barcode 0.0.0-stage → 0.0.1

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 (176) hide show
  1. package/.medusa/server/src/admin/index.cjs +3960 -0
  2. package/.medusa/server/src/admin/index.js +3938 -0
  3. package/.medusa/server/src/api/admin/barcodes/[barcode]/route.js +43 -0
  4. package/.medusa/server/src/api/admin/barcodes/batch/route.js +9 -0
  5. package/.medusa/server/src/api/admin/barcodes/bulk-generate/route.js +9 -0
  6. package/.medusa/server/src/api/admin/barcodes/cache/route.js +25 -0
  7. package/.medusa/server/src/api/admin/barcodes/count-sessions/[id]/apply/route.js +13 -0
  8. package/.medusa/server/src/api/admin/barcodes/count-sessions/[id]/scan/route.js +13 -0
  9. package/.medusa/server/src/api/admin/barcodes/count-sessions/route.js +27 -0
  10. package/.medusa/server/src/api/admin/barcodes/create-from-barcode/route.js +9 -0
  11. package/.medusa/server/src/api/admin/barcodes/lookup/route.js +12 -0
  12. package/.medusa/server/src/api/admin/barcodes/print/route.js +11 -0
  13. package/.medusa/server/src/api/admin/barcodes/route.js +27 -0
  14. package/.medusa/server/src/api/admin/barcodes/scan/route.js +23 -0
  15. package/.medusa/server/src/api/admin/barcodes/tags/[id]/route.js +28 -0
  16. package/.medusa/server/src/api/admin/barcodes/tags/route.js +25 -0
  17. package/.medusa/server/src/api/admin/barcodes/templates/route.js +40 -0
  18. package/.medusa/server/src/api/admin/plugin/route.js +4 -0
  19. package/.medusa/server/src/api/admin/variants/barcode/[code]/route.js +28 -0
  20. package/.medusa/server/src/api/middlewares.js +73 -0
  21. package/.medusa/server/src/api/store/barcodes/[code]/route.js +28 -0
  22. package/.medusa/server/src/api/store/barcodes/[code]/verify/route.js +20 -0
  23. package/.medusa/server/src/api/store/plugin/route.js +4 -0
  24. package/.medusa/server/src/api/store/variants/barcode/[code]/route.js +28 -0
  25. package/.medusa/server/src/api/validators.js +173 -0
  26. package/.medusa/server/src/hooks/index.js +202 -0
  27. package/.medusa/server/src/index.js +5 -0
  28. package/.medusa/server/src/jobs/purge-expired-barcode-cache.js +10 -0
  29. package/.medusa/server/src/modules/barcode/index.js +16 -0
  30. package/.medusa/server/src/modules/barcode/migrations/Migration20260522000000.js +165 -0
  31. package/.medusa/server/src/modules/barcode/models/index.js +162 -0
  32. package/.medusa/server/src/modules/barcode/operations/context.js +2 -0
  33. package/.medusa/server/src/modules/barcode/operations/data-service.js +10 -0
  34. package/.medusa/server/src/modules/barcode/operations/generation.js +33 -0
  35. package/.medusa/server/src/modules/barcode/operations/index.js +9 -0
  36. package/.medusa/server/src/modules/barcode/operations/labels.js +57 -0
  37. package/.medusa/server/src/modules/barcode/operations/lookup.js +135 -0
  38. package/.medusa/server/src/modules/barcode/operations/maintenance.js +37 -0
  39. package/.medusa/server/src/modules/barcode/operations/stock-count.js +129 -0
  40. package/.medusa/server/src/modules/barcode/operations/tags.js +298 -0
  41. package/.medusa/server/src/modules/barcode/providers/index.js +721 -0
  42. package/.medusa/server/src/modules/barcode/service.js +161 -0
  43. package/.medusa/server/src/modules/barcode/types.js +21 -0
  44. package/.medusa/server/src/modules/barcode/utils/barcode-parser.js +399 -0
  45. package/.medusa/server/src/modules/barcode/utils/label-printer.js +533 -0
  46. package/.medusa/server/src/modules/barcode/utils/normalize-product.js +443 -0
  47. package/.medusa/server/src/modules/barcode/utils/security.js +114 -0
  48. package/.medusa/server/src/modules/barcode/utils/svg-renderer.js +492 -0
  49. package/.medusa/server/src/rbac.js +130 -0
  50. package/.medusa/server/src/sdk/index.js +164 -0
  51. package/.medusa/server/src/subscribers/product-created.js +34 -0
  52. package/.medusa/server/src/types/index.js +2 -0
  53. package/.medusa/server/src/ui/index.js +138 -0
  54. package/.medusa/server/src/workflows/apply-inventory-count.js +68 -0
  55. package/.medusa/server/src/workflows/batch-barcode-import.js +153 -0
  56. package/.medusa/server/src/workflows/bulk-generate-variant-barcodes.js +143 -0
  57. package/.medusa/server/src/workflows/generate-barcode-tag.js +44 -0
  58. package/.medusa/server/src/workflows/helpers.js +15 -0
  59. package/.medusa/server/src/workflows/index.js +7 -0
  60. package/.medusa/server/src/workflows/lookup-and-create-product.js +215 -0
  61. package/.medusa/server/src/workflows/scan-inventory-count.js +15 -0
  62. package/LICENSE +21 -0
  63. package/README.md +844 -2
  64. package/package.json +129 -3
  65. package/src/__tests__/barcode.spec.ts +836 -0
  66. package/src/__tests__/medusa-shim.mjs +331 -0
  67. package/src/__tests__/register-ts-resolver.mjs +135 -0
  68. package/src/admin/README.md +134 -0
  69. package/src/admin/components/barcode-studio-header.tsx +73 -0
  70. package/src/admin/components/batch-import-section.tsx +99 -0
  71. package/src/admin/components/dynamic-qr-tag-drawer-form.tsx +230 -0
  72. package/src/admin/components/dynamic-qr-tag-form.tsx +129 -0
  73. package/src/admin/components/dynamic-qr-tags-table.tsx +136 -0
  74. package/src/admin/components/gtin-lookup-section.tsx +155 -0
  75. package/src/admin/components/index.tsx +14 -0
  76. package/src/admin/components/label-designer-section.tsx +151 -0
  77. package/src/admin/components/label-output-section.tsx +63 -0
  78. package/src/admin/components/overview-cards.tsx +98 -0
  79. package/src/admin/components/product-barcode-card.tsx +127 -0
  80. package/src/admin/components/providers-cache-table.tsx +61 -0
  81. package/src/admin/components/providers-overview-section.tsx +49 -0
  82. package/src/admin/components/rbac-guard.tsx +153 -0
  83. package/src/admin/components/stock-take-scanner-section.tsx +116 -0
  84. package/src/admin/components/stock-take-sessions-section.tsx +109 -0
  85. package/src/admin/hooks/use-barcode-studio.ts +466 -0
  86. package/src/admin/hooks/use-product-barcodes.ts +139 -0
  87. package/src/admin/i18n/README.md +130 -0
  88. package/src/admin/i18n/index.ts +36 -0
  89. package/src/admin/i18n/json/ar.json +157 -0
  90. package/src/admin/i18n/json/de.json +157 -0
  91. package/src/admin/i18n/json/en.json +157 -0
  92. package/src/admin/i18n/json/es.json +157 -0
  93. package/src/admin/i18n/json/fr.json +157 -0
  94. package/src/admin/i18n/json/it.json +157 -0
  95. package/src/admin/i18n/json/nl.json +157 -0
  96. package/src/admin/i18n/json/pl.json +157 -0
  97. package/src/admin/i18n/json/pt.json +157 -0
  98. package/src/admin/i18n/json/tr.json +157 -0
  99. package/src/admin/routes/barcodes/lookup/page.tsx +75 -0
  100. package/src/admin/routes/barcodes/page.tsx +212 -0
  101. package/src/admin/routes/barcodes/print/page.tsx +67 -0
  102. package/src/admin/routes/barcodes/providers/page.tsx +66 -0
  103. package/src/admin/routes/barcodes/stock-take/page.tsx +74 -0
  104. package/src/admin/routes/barcodes/tags/@create/page.tsx +56 -0
  105. package/src/admin/routes/barcodes/tags/page.tsx +72 -0
  106. package/src/admin/tsconfig.json +20 -0
  107. package/src/admin/vite-env.d.ts +1 -0
  108. package/src/admin/widgets/product-barcode-widget.tsx +43 -0
  109. package/src/api/README.md +117 -0
  110. package/src/api/admin/barcodes/[barcode]/route.ts +64 -0
  111. package/src/api/admin/barcodes/batch/route.ts +12 -0
  112. package/src/api/admin/barcodes/bulk-generate/route.ts +12 -0
  113. package/src/api/admin/barcodes/cache/route.ts +35 -0
  114. package/src/api/admin/barcodes/count-sessions/[id]/apply/route.ts +17 -0
  115. package/src/api/admin/barcodes/count-sessions/[id]/scan/route.ts +17 -0
  116. package/src/api/admin/barcodes/count-sessions/route.ts +43 -0
  117. package/src/api/admin/barcodes/create-from-barcode/route.ts +16 -0
  118. package/src/api/admin/barcodes/lookup/route.ts +19 -0
  119. package/src/api/admin/barcodes/print/route.ts +18 -0
  120. package/src/api/admin/barcodes/route.ts +36 -0
  121. package/src/api/admin/barcodes/scan/route.ts +32 -0
  122. package/src/api/admin/barcodes/tags/[id]/route.ts +41 -0
  123. package/src/api/admin/barcodes/tags/route.ts +36 -0
  124. package/src/api/admin/barcodes/templates/route.ts +51 -0
  125. package/src/api/admin/plugin/route.ts +5 -0
  126. package/src/api/admin/variants/barcode/[code]/route.ts +36 -0
  127. package/src/api/middlewares.ts +91 -0
  128. package/src/api/store/barcodes/[code]/route.ts +43 -0
  129. package/src/api/store/barcodes/[code]/verify/route.ts +35 -0
  130. package/src/api/store/plugin/route.ts +5 -0
  131. package/src/api/store/variants/barcode/[code]/route.ts +36 -0
  132. package/src/api/validators.ts +217 -0
  133. package/src/hooks/index.ts +270 -0
  134. package/src/index.ts +4 -0
  135. package/src/jobs/README.md +54 -0
  136. package/src/jobs/purge-expired-barcode-cache.ts +18 -0
  137. package/src/links/README.md +44 -0
  138. package/src/modules/README.md +85 -0
  139. package/src/modules/barcode/index.ts +18 -0
  140. package/src/modules/barcode/migrations/Migration20260522000000.ts +225 -0
  141. package/src/modules/barcode/models/index.ts +168 -0
  142. package/src/modules/barcode/operations/context.ts +14 -0
  143. package/src/modules/barcode/operations/data-service.ts +10 -0
  144. package/src/modules/barcode/operations/generation.ts +57 -0
  145. package/src/modules/barcode/operations/index.ts +8 -0
  146. package/src/modules/barcode/operations/labels.ts +90 -0
  147. package/src/modules/barcode/operations/lookup.ts +202 -0
  148. package/src/modules/barcode/operations/maintenance.ts +53 -0
  149. package/src/modules/barcode/operations/stock-count.ts +217 -0
  150. package/src/modules/barcode/operations/tags.ts +425 -0
  151. package/src/modules/barcode/providers/index.ts +958 -0
  152. package/src/modules/barcode/service.ts +243 -0
  153. package/src/modules/barcode/types.ts +297 -0
  154. package/src/modules/barcode/utils/barcode-parser.ts +453 -0
  155. package/src/modules/barcode/utils/label-printer.ts +641 -0
  156. package/src/modules/barcode/utils/normalize-product.ts +524 -0
  157. package/src/modules/barcode/utils/security.ts +136 -0
  158. package/src/modules/barcode/utils/svg-renderer.ts +574 -0
  159. package/src/providers/README.md +105 -0
  160. package/src/rbac.ts +144 -0
  161. package/src/sdk/index.ts +253 -0
  162. package/src/subscribers/README.md +73 -0
  163. package/src/subscribers/product-created.ts +45 -0
  164. package/src/types/index.ts +1 -0
  165. package/src/types/medusa-ui.d.ts +118 -0
  166. package/src/ui/index.tsx +311 -0
  167. package/src/workflows/README.md +56 -0
  168. package/src/workflows/apply-inventory-count.ts +115 -0
  169. package/src/workflows/batch-barcode-import.ts +218 -0
  170. package/src/workflows/bulk-generate-variant-barcodes.ts +214 -0
  171. package/src/workflows/generate-barcode-tag.ts +85 -0
  172. package/src/workflows/helpers.ts +21 -0
  173. package/src/workflows/index.ts +6 -0
  174. package/src/workflows/lookup-and-create-product.ts +298 -0
  175. package/src/workflows/scan-inventory-count.ts +45 -0
  176. package/tsconfig.json +40 -0
@@ -0,0 +1,214 @@
1
+ import { Modules } from "@medusajs/framework/utils"
2
+ import {
3
+ createStep,
4
+ createWorkflow,
5
+ StepResponse,
6
+ WorkflowResponse,
7
+ } from "@medusajs/framework/workflows-sdk"
8
+
9
+ import type { BarcodeModuleService } from "../modules/barcode/service"
10
+ import { BARCODE_MODULE } from "../modules/barcode/types"
11
+ import { parseBarcode } from "../modules/barcode/utils/barcode-parser"
12
+ import { tryResolveService } from "./helpers"
13
+
14
+ export interface BulkGenerateVariantBarcodesInput {
15
+ variant_ids?: string[]
16
+ product_ids?: string[]
17
+ prefix?: string
18
+ overwrite?: boolean
19
+ }
20
+
21
+ const bulkGenerateVariantBarcodesStep = createStep(
22
+ "bulk-generate-variant-barcodes",
23
+ async (input: BulkGenerateVariantBarcodesInput, { container }) => {
24
+ const barcodeService = container.resolve(
25
+ BARCODE_MODULE
26
+ ) as BarcodeModuleService
27
+ const productService = tryResolveService(container, [
28
+ Modules.PRODUCT,
29
+ "product",
30
+ ])
31
+
32
+ const generated: Array<{
33
+ variant_id: string
34
+ product_id: string | null
35
+ barcode: string
36
+ ean: string
37
+ upc: string
38
+ }> = []
39
+ const createdTagIds: string[] = []
40
+ const previousVariants: Array<{
41
+ id: string
42
+ barcode: string | null
43
+ ean: string | null
44
+ upc: string | null
45
+ }> = []
46
+
47
+ const targetVariants: Array<{
48
+ id: string
49
+ product_id?: string | null
50
+ title?: string | null
51
+ barcode?: string | null
52
+ ean?: string | null
53
+ upc?: string | null
54
+ }> = []
55
+
56
+ if (
57
+ productService &&
58
+ typeof productService.listProductVariants === "function"
59
+ ) {
60
+ const filter: Record<string, unknown> = {}
61
+ if (input.variant_ids && input.variant_ids.length > 0) {
62
+ filter.id = input.variant_ids
63
+ }
64
+ if (input.product_ids && input.product_ids.length > 0) {
65
+ filter.product_id = input.product_ids
66
+ }
67
+ const rows = (await productService.listProductVariants(filter, {
68
+ take: 250,
69
+ })) as typeof targetVariants
70
+ if (Array.isArray(rows)) {
71
+ const filteredRows = rows.filter((r) => {
72
+ if (
73
+ input.variant_ids &&
74
+ input.variant_ids.length > 0 &&
75
+ !input.variant_ids.includes(r.id)
76
+ ) {
77
+ return false
78
+ }
79
+ if (
80
+ input.product_ids &&
81
+ input.product_ids.length > 0 &&
82
+ r.product_id &&
83
+ !input.product_ids.includes(r.product_id)
84
+ ) {
85
+ return false
86
+ }
87
+ return true
88
+ })
89
+ targetVariants.push(...filteredRows)
90
+ }
91
+ } else if (input.variant_ids && input.variant_ids.length > 0) {
92
+ for (const vid of input.variant_ids) {
93
+ targetVariants.push({ id: vid, product_id: null })
94
+ }
95
+ }
96
+
97
+ let seq = 1
98
+ for (const variant of targetVariants) {
99
+ if (variant.barcode && !input.overwrite) {
100
+ // Ensure a BarcodeTag exists even when variant already has an assigned barcode
101
+ const existingTags = await barcodeService.listBarcodeTags(
102
+ { code: variant.barcode },
103
+ { take: 1 }
104
+ )
105
+ if (!existingTags[0]) {
106
+ const parsedExisting = parseBarcode(variant.barcode)
107
+ const tag = await barcodeService.createOrUpdateBarcodeTag({
108
+ code: variant.barcode,
109
+ target_type: "variant",
110
+ target_id: variant.id,
111
+ product_id: variant.product_id ?? null,
112
+ variant_id: variant.id,
113
+ label: variant.title ?? variant.id,
114
+ symbology:
115
+ parsedExisting.type === "unknown"
116
+ ? "code128"
117
+ : parsedExisting.type,
118
+ scan_action: "view",
119
+ })
120
+ createdTagIds.push(tag.id)
121
+ }
122
+ continue
123
+ }
124
+
125
+ previousVariants.push({
126
+ id: variant.id,
127
+ barcode: variant.barcode ?? null,
128
+ ean: variant.ean ?? null,
129
+ upc: variant.upc ?? null,
130
+ })
131
+
132
+ const codeInfo = await barcodeService.generateInternalVariantBarcode({
133
+ seed: variant.id,
134
+ sequence: seq++,
135
+ prefix: input.prefix,
136
+ })
137
+
138
+ if (
139
+ productService &&
140
+ typeof productService.upsertProductVariants === "function"
141
+ ) {
142
+ await productService.upsertProductVariants([
143
+ {
144
+ id: variant.id,
145
+ barcode: codeInfo.barcode,
146
+ ean: codeInfo.ean,
147
+ upc: codeInfo.upc,
148
+ },
149
+ ])
150
+ }
151
+
152
+ const tag = await barcodeService.createOrUpdateBarcodeTag({
153
+ code: codeInfo.barcode,
154
+ target_type: "variant",
155
+ target_id: variant.id,
156
+ product_id: variant.product_id ?? null,
157
+ variant_id: variant.id,
158
+ label: variant.title ?? variant.id,
159
+ symbology: "ean13",
160
+ scan_action: "view",
161
+ })
162
+ createdTagIds.push(tag.id)
163
+
164
+ generated.push({
165
+ variant_id: variant.id,
166
+ product_id: variant.product_id ?? null,
167
+ barcode: codeInfo.barcode,
168
+ ean: codeInfo.ean,
169
+ upc: codeInfo.upc,
170
+ })
171
+ }
172
+
173
+ return new StepResponse(
174
+ {
175
+ generated_count: generated.length,
176
+ generated,
177
+ },
178
+ {
179
+ createdTagIds,
180
+ previousVariants,
181
+ }
182
+ )
183
+ },
184
+ async (compInput, { container }) => {
185
+ if (!compInput) return
186
+ const barcodeService = container.resolve(
187
+ BARCODE_MODULE
188
+ ) as BarcodeModuleService
189
+
190
+ if (compInput.createdTagIds.length > 0) {
191
+ await barcodeService.deleteBarcodeTags(compInput.createdTagIds)
192
+ }
193
+
194
+ const productService = tryResolveService(container, [
195
+ Modules.PRODUCT,
196
+ "product",
197
+ ])
198
+ if (
199
+ productService &&
200
+ typeof productService.upsertProductVariants === "function" &&
201
+ compInput.previousVariants.length > 0
202
+ ) {
203
+ await productService.upsertProductVariants(compInput.previousVariants)
204
+ }
205
+ }
206
+ )
207
+
208
+ export const bulkGenerateVariantBarcodesWorkflow = createWorkflow(
209
+ "bulk-generate-variant-barcodes",
210
+ (input: BulkGenerateVariantBarcodesInput) => {
211
+ const result = bulkGenerateVariantBarcodesStep(input)
212
+ return new WorkflowResponse(result)
213
+ }
214
+ )
@@ -0,0 +1,85 @@
1
+ import { Modules } from "@medusajs/framework/utils"
2
+ import {
3
+ createStep,
4
+ createWorkflow,
5
+ StepResponse,
6
+ WorkflowResponse,
7
+ } from "@medusajs/framework/workflows-sdk"
8
+
9
+ import type { BarcodeModuleService } from "../modules/barcode/service"
10
+ import {
11
+ BARCODE_MODULE,
12
+ type BarcodeScanAction,
13
+ type BarcodeSymbology,
14
+ } from "../modules/barcode/types"
15
+ import { tryResolveService } from "./helpers"
16
+
17
+ export interface GenerateBarcodeTagInput {
18
+ code?: string
19
+ target_type?: "product" | "variant" | "order" | "custom"
20
+ target_id: string
21
+ product_id?: string | null
22
+ variant_id?: string | null
23
+ label?: string | null
24
+ symbology?: BarcodeSymbology
25
+ scan_action?: BarcodeScanAction
26
+ gs1_gtin?: string | null
27
+ batch_lot?: string | null
28
+ serial_number?: string | null
29
+ target_url?: string | null
30
+ upload_svg_to_file_module?: boolean
31
+ metadata?: Record<string, unknown> | null
32
+ }
33
+
34
+ const generateBarcodeTagStep = createStep(
35
+ "generate-barcode-tag",
36
+ async (input: GenerateBarcodeTagInput, { container }) => {
37
+ const barcodeService = container.resolve(
38
+ BARCODE_MODULE
39
+ ) as BarcodeModuleService
40
+
41
+ const tag = await barcodeService.createOrUpdateBarcodeTag(input)
42
+
43
+ if (input.upload_svg_to_file_module && tag.svg_markup) {
44
+ const fileService = tryResolveService(container, [Modules.FILE, "file"])
45
+ if (fileService && typeof fileService.createFiles === "function") {
46
+ try {
47
+ const uploaded = (await fileService.createFiles([
48
+ {
49
+ filename: `${tag.code}.svg`,
50
+ mimeType: "image/svg+xml",
51
+ content: Buffer.from(tag.svg_markup, "utf-8").toString("base64"),
52
+ access: "public",
53
+ },
54
+ ])) as Array<{ url?: string }>
55
+ if (uploaded?.[0]?.url) {
56
+ const updated = await barcodeService.updateBarcodeTags({
57
+ id: tag.id,
58
+ svg_url: uploaded[0].url,
59
+ })
60
+ return new StepResponse(updated, { tagId: updated.id })
61
+ }
62
+ } catch {
63
+ // Non-fatal if File Module is not configured
64
+ }
65
+ }
66
+ }
67
+
68
+ return new StepResponse(tag, { tagId: tag.id })
69
+ },
70
+ async (compInput, { container }) => {
71
+ if (!compInput?.tagId) return
72
+ const barcodeService = container.resolve(
73
+ BARCODE_MODULE
74
+ ) as BarcodeModuleService
75
+ await barcodeService.deleteBarcodeTags([compInput.tagId])
76
+ }
77
+ )
78
+
79
+ export const generateBarcodeTagWorkflow = createWorkflow(
80
+ "generate-barcode-tag",
81
+ (input: GenerateBarcodeTagInput) => {
82
+ const tag = generateBarcodeTagStep(input)
83
+ return new WorkflowResponse(tag)
84
+ }
85
+ )
@@ -0,0 +1,21 @@
1
+ export type AnyService = Record<
2
+ string,
3
+ (...args: unknown[]) => Promise<unknown>
4
+ >
5
+
6
+ export function tryResolveService(
7
+ container: { resolve: (key: string) => unknown },
8
+ keys: string[]
9
+ ): AnyService | null {
10
+ for (const key of keys) {
11
+ try {
12
+ const resolved = container.resolve(key)
13
+ if (resolved && typeof resolved === "object") {
14
+ return resolved as AnyService
15
+ }
16
+ } catch {
17
+ // try next
18
+ }
19
+ }
20
+ return null
21
+ }
@@ -0,0 +1,6 @@
1
+ export * from "./lookup-and-create-product"
2
+ export * from "./batch-barcode-import"
3
+ export * from "./bulk-generate-variant-barcodes"
4
+ export * from "./generate-barcode-tag"
5
+ export * from "./scan-inventory-count"
6
+ export * from "./apply-inventory-count"
@@ -0,0 +1,298 @@
1
+ import { Modules } from "@medusajs/framework/utils"
2
+ import {
3
+ createStep,
4
+ createWorkflow,
5
+ StepResponse,
6
+ WorkflowResponse,
7
+ } from "@medusajs/framework/workflows-sdk"
8
+
9
+ import { downloadProductImageBuffer } from "../modules/barcode/providers"
10
+ import type { BarcodeModuleService } from "../modules/barcode/service"
11
+ import {
12
+ BARCODE_EVENTS,
13
+ BARCODE_MODULE,
14
+ type BarcodeLookupChainResult,
15
+ type CreateProductPayload,
16
+ type LookupAndCreateProductInput,
17
+ type NormalizedBarcodeProduct,
18
+ } from "../modules/barcode/types"
19
+ import { mapToMedusaCreateProduct } from "../modules/barcode/utils/normalize-product"
20
+ import { tryResolveService } from "./helpers"
21
+
22
+ export type { LookupAndCreateProductInput }
23
+
24
+ type LookupAndCreateProductOutput = {
25
+ created: boolean
26
+ existing: boolean
27
+ product: Record<string, unknown> | null
28
+ lookup: BarcodeLookupChainResult
29
+ product_id: string
30
+ variant_id: string | null
31
+ product_payload: CreateProductPayload | null
32
+ barcode_product: Awaited<
33
+ ReturnType<BarcodeModuleService["upsertBarcodeProductLink"]>
34
+ >
35
+ }
36
+
37
+ type LookupAndCreateProductCompensation = {
38
+ barcodeProductId: string | null
39
+ createdProductId: string | null
40
+ }
41
+
42
+ const lookupAndCreateProductStep = createStep(
43
+ "lookup-and-create-product",
44
+ async (
45
+ input: LookupAndCreateProductInput,
46
+ { container }
47
+ ): Promise<
48
+ StepResponse<
49
+ LookupAndCreateProductOutput,
50
+ LookupAndCreateProductCompensation
51
+ >
52
+ > => {
53
+ const barcodeService = container.resolve(
54
+ BARCODE_MODULE
55
+ ) as BarcodeModuleService
56
+ const moduleOptions = await barcodeService.getModuleOptions()
57
+ const productService = tryResolveService(container, [
58
+ Modules.PRODUCT,
59
+ "product",
60
+ ])
61
+
62
+ // Self-healing existing product check
63
+ if (input.skipExistingCheck !== true) {
64
+ const existingMapping = await barcodeService.findBarcodeProduct(
65
+ input.barcode
66
+ )
67
+ if (existingMapping) {
68
+ if (
69
+ productService &&
70
+ typeof productService.listProducts === "function"
71
+ ) {
72
+ const existingProducts = (await productService.listProducts({
73
+ id: [existingMapping.product_id],
74
+ })) as Array<Record<string, unknown>>
75
+ const foundExisting = Array.isArray(existingProducts)
76
+ ? (existingProducts.find(
77
+ (p) => p.id === existingMapping.product_id
78
+ ) ?? existingProducts[0])
79
+ : null
80
+ if (foundExisting) {
81
+ const parsed = await barcodeService.parseAndValidateBarcode(
82
+ input.barcode
83
+ )
84
+ const cachedProduct =
85
+ (existingMapping.product_data as unknown as NormalizedBarcodeProduct) ||
86
+ null
87
+ return new StepResponse(
88
+ {
89
+ created: false,
90
+ existing: true,
91
+ product: foundExisting,
92
+ product_id: existingMapping.product_id,
93
+ variant_id: existingMapping.variant_id ?? null,
94
+ product_payload: null,
95
+ barcode_product: existingMapping,
96
+ lookup: {
97
+ barcode: existingMapping.barcode,
98
+ parsed,
99
+ found: Boolean(cachedProduct),
100
+ cached: true,
101
+ strategy:
102
+ input.strategy ||
103
+ moduleOptions.enrichmentStrategy ||
104
+ "first-hit",
105
+ product: cachedProduct,
106
+ outcomes: [],
107
+ },
108
+ },
109
+ {
110
+ barcodeProductId: null,
111
+ createdProductId: null,
112
+ }
113
+ )
114
+ }
115
+ // Product was deleted in Medusa — self-heal stale BarcodeProduct link
116
+ await barcodeService.removeBarcodeProduct(input.barcode)
117
+ }
118
+ }
119
+ }
120
+
121
+ const lookupResult = await barcodeService.lookupBarcode(input.barcode, {
122
+ skipCache: input.skipCache,
123
+ strategy: input.strategy || moduleOptions.enrichmentStrategy,
124
+ })
125
+
126
+ const normalized: NormalizedBarcodeProduct = lookupResult.product || {
127
+ barcode: lookupResult.barcode,
128
+ barcode_type: lookupResult.parsed.type,
129
+ name: input.overrideTitle || `Product ${lookupResult.barcode}`,
130
+ description: input.overrideDescription || null,
131
+ brand: null,
132
+ manufacturer: null,
133
+ categories: [],
134
+ images: [],
135
+ weight: null,
136
+ weight_unit: null,
137
+ dimensions: null,
138
+ quantity_label: null,
139
+ ingredients: null,
140
+ nutrition: null,
141
+ country_of_origin: null,
142
+ suggested_price: input.overridePrice ?? null,
143
+ currency_code: input.currencyCode || "USD",
144
+ isbn: lookupResult.parsed.isIsbn ? lookupResult.barcode : null,
145
+ authors: [],
146
+ publisher: null,
147
+ published_date: null,
148
+ page_count: null,
149
+ provider: "manual",
150
+ raw_data: {},
151
+ }
152
+
153
+ // Optional File Module image upload
154
+ const shouldDownload =
155
+ input.downloadImages ?? moduleOptions.downloadProductImages ?? false
156
+ if (shouldDownload && normalized.images.length > 0) {
157
+ const fileService = tryResolveService(container, [Modules.FILE, "file"])
158
+ if (fileService && typeof fileService.createFiles === "function") {
159
+ const uploadedUrls: string[] = []
160
+ for (const imageUrl of normalized.images.slice(0, 3)) {
161
+ const downloaded = await downloadProductImageBuffer(imageUrl)
162
+ if (downloaded) {
163
+ try {
164
+ const createdFiles = (await fileService.createFiles([
165
+ {
166
+ filename: downloaded.filename,
167
+ mimeType: downloaded.mimeType,
168
+ content: downloaded.buffer.toString("base64"),
169
+ access: "public",
170
+ },
171
+ ])) as Array<{ url?: string }>
172
+ if (createdFiles?.[0]?.url) {
173
+ uploadedUrls.push(createdFiles[0].url)
174
+ }
175
+ } catch {
176
+ uploadedUrls.push(imageUrl)
177
+ }
178
+ }
179
+ }
180
+ if (uploadedUrls.length > 0) {
181
+ normalized.images = uploadedUrls
182
+ }
183
+ }
184
+ }
185
+
186
+ const createPayload = mapToMedusaCreateProduct(normalized, {
187
+ status: input.status || moduleOptions.defaultProductStatus || "draft",
188
+ publishImmediately: input.publishImmediately,
189
+ skuPrefix: input.skuPrefix || "GTIN",
190
+ overrideTitle: input.overrideTitle,
191
+ overrideDescription: input.overrideDescription,
192
+ overridePrice: input.overridePrice,
193
+ currencyCode: input.currencyCode,
194
+ prices: input.prices,
195
+ salesChannelIds: input.salesChannelIds,
196
+ categoryIds: input.categoryIds,
197
+ collectionId: input.collectionId,
198
+ })
199
+
200
+ let createdProductId = `prod_${lookupResult.barcode}`
201
+ let createdVariantId: string | null = `variant_${lookupResult.barcode}`
202
+ let createdProductObj: Record<string, unknown> | null = null
203
+ let createdInProductModule = false
204
+
205
+ if (productService && typeof productService.createProducts === "function") {
206
+ const created = await productService.createProducts([createPayload])
207
+ const firstProduct = Array.isArray(created) ? created[0] : created
208
+ if (
209
+ firstProduct &&
210
+ typeof firstProduct === "object" &&
211
+ "id" in firstProduct
212
+ ) {
213
+ createdProductObj = firstProduct as Record<string, unknown>
214
+ createdProductId = String((firstProduct as { id: string }).id)
215
+ const variants = (firstProduct as { variants?: Array<{ id?: string }> })
216
+ .variants
217
+ createdVariantId = variants?.[0]?.id ? String(variants[0].id) : null
218
+ createdInProductModule = true
219
+ }
220
+ }
221
+
222
+ const barcodeProduct = await barcodeService.upsertBarcodeProductLink({
223
+ barcode: lookupResult.barcode,
224
+ product_id: createdProductId,
225
+ variant_id: createdVariantId,
226
+ provider: normalized.provider,
227
+ product_data: normalized,
228
+ status: "created",
229
+ })
230
+
231
+ const eventBus = tryResolveService(container, [
232
+ Modules.EVENT_BUS,
233
+ "event_bus",
234
+ ])
235
+ if (eventBus && typeof eventBus.emit === "function") {
236
+ try {
237
+ await eventBus.emit({
238
+ name: BARCODE_EVENTS.PRODUCT_CREATED,
239
+ data: {
240
+ barcode: lookupResult.barcode,
241
+ product_id: createdProductId,
242
+ variant_id: createdVariantId,
243
+ provider: normalized.provider,
244
+ },
245
+ })
246
+ } catch {
247
+ // Non-fatal if event bus fails
248
+ }
249
+ }
250
+
251
+ return new StepResponse(
252
+ {
253
+ created: true,
254
+ existing: false,
255
+ product: createdProductObj,
256
+ lookup: lookupResult,
257
+ product_id: createdProductId,
258
+ variant_id: createdVariantId,
259
+ product_payload: createPayload,
260
+ barcode_product: barcodeProduct,
261
+ },
262
+ {
263
+ barcodeProductId: barcodeProduct.id,
264
+ createdProductId: createdInProductModule ? createdProductId : null,
265
+ }
266
+ )
267
+ },
268
+ async (compInput, { container }) => {
269
+ if (!compInput) return
270
+ const barcodeService = container.resolve(
271
+ BARCODE_MODULE
272
+ ) as BarcodeModuleService
273
+
274
+ if (compInput.barcodeProductId) {
275
+ await barcodeService.deleteBarcodeProducts([compInput.barcodeProductId])
276
+ }
277
+ if (compInput.createdProductId) {
278
+ const productService = tryResolveService(container, [
279
+ Modules.PRODUCT,
280
+ "product",
281
+ ])
282
+ if (
283
+ productService &&
284
+ typeof productService.deleteProducts === "function"
285
+ ) {
286
+ await productService.deleteProducts([compInput.createdProductId])
287
+ }
288
+ }
289
+ }
290
+ )
291
+
292
+ export const lookupAndCreateProductWorkflow = createWorkflow(
293
+ "lookup-and-create-product",
294
+ (input: LookupAndCreateProductInput) => {
295
+ const result = lookupAndCreateProductStep(input)
296
+ return new WorkflowResponse(result)
297
+ }
298
+ )
@@ -0,0 +1,45 @@
1
+ import {
2
+ createStep,
3
+ createWorkflow,
4
+ StepResponse,
5
+ WorkflowResponse,
6
+ } from "@medusajs/framework/workflows-sdk"
7
+
8
+ import type { BarcodeModuleService } from "../modules/barcode/service"
9
+ import { BARCODE_MODULE } from "../modules/barcode/types"
10
+
11
+ export interface ScanInventoryCountInput {
12
+ session_id: string
13
+ barcode: string
14
+ delta?: number
15
+ set_quantity?: number
16
+ variant_id?: string | null
17
+ product_id?: string | null
18
+ title?: string
19
+ variant_title?: string | null
20
+ sku?: string | null
21
+ expected_quantity?: number
22
+ }
23
+
24
+ const scanInventoryCountStep = createStep(
25
+ "scan-inventory-count",
26
+ async (input: ScanInventoryCountInput, { container }) => {
27
+ const barcodeService = container.resolve(
28
+ BARCODE_MODULE
29
+ ) as BarcodeModuleService
30
+
31
+ const result = await barcodeService.recordCountSessionScan(input)
32
+ return new StepResponse(result, {
33
+ sessionId: input.session_id,
34
+ itemId: result.item.id,
35
+ })
36
+ }
37
+ )
38
+
39
+ export const scanInventoryCountWorkflow = createWorkflow(
40
+ "scan-inventory-count",
41
+ (input: ScanInventoryCountInput) => {
42
+ const result = scanInventoryCountStep(input)
43
+ return new WorkflowResponse(result)
44
+ }
45
+ )