@vicacha-devs/medusa-plugin-barcode 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.
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 +134 -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,311 @@
1
+ import React, { useState } from "react"
2
+
3
+ import {
4
+ useCameraBarcodeScanner,
5
+ useHidBarcodeScanner,
6
+ useStoreBarcodeResolver,
7
+ } from "../hooks"
8
+ import type { BarcodeSymbology } from "../modules/barcode/types"
9
+ import { createBarcodeSdk, type BarcodeSdkOptions } from "../sdk"
10
+
11
+ export function svgMarkupToDataUri(svgMarkup: string): string {
12
+ return `data:image/svg+xml;utf8,${encodeURIComponent(svgMarkup)}`
13
+ }
14
+
15
+ export interface BarcodeImageProps {
16
+ code: string
17
+ symbology?: BarcodeSymbology
18
+ svgMarkup?: string | null
19
+ baseUrl?: string
20
+ alt?: string
21
+ width?: number
22
+ height?: number
23
+ className?: string
24
+ }
25
+
26
+ /**
27
+ * Renders a 1D/2D barcode or QR SVG safely via `<img>` without dangerouslySetInnerHTML.
28
+ */
29
+ export function BarcodeImage({
30
+ code,
31
+ symbology = "ean13",
32
+ svgMarkup,
33
+ baseUrl = "",
34
+ alt,
35
+ width = 220,
36
+ height = 88,
37
+ className,
38
+ }: BarcodeImageProps) {
39
+ const sdk = createBarcodeSdk({ baseUrl })
40
+ const src = svgMarkup
41
+ ? svgMarkupToDataUri(svgMarkup)
42
+ : sdk.store.getSvgUrl(code, symbology)
43
+
44
+ return (
45
+ <img
46
+ src={src}
47
+ alt={alt || `${symbology.toUpperCase()} ${code}`}
48
+ width={width}
49
+ height={height}
50
+ className={className}
51
+ style={{
52
+ display: "block",
53
+ maxWidth: "100%",
54
+ height: "auto",
55
+ background: "#ffffff",
56
+ borderRadius: 6,
57
+ padding: 4,
58
+ }}
59
+ />
60
+ )
61
+ }
62
+
63
+ export interface AuthenticityVerifierBadgeProps {
64
+ code: string
65
+ signature: string
66
+ sdkOptions?: BarcodeSdkOptions
67
+ }
68
+
69
+ /**
70
+ * Storefront Anti-Counterfeit HMAC-SHA256 Verification Badge.
71
+ */
72
+ export function AuthenticityVerifierBadge({
73
+ code,
74
+ signature,
75
+ sdkOptions,
76
+ }: AuthenticityVerifierBadgeProps) {
77
+ const { loading, verificationResult, verifyAuthenticity } =
78
+ useStoreBarcodeResolver(sdkOptions)
79
+
80
+ return (
81
+ <div
82
+ style={{
83
+ border: "1px solid #e5e7eb",
84
+ borderRadius: 10,
85
+ padding: 14,
86
+ background: "#f9fafb",
87
+ display: "flex",
88
+ flexDirection: "column",
89
+ gap: 8,
90
+ }}
91
+ >
92
+ <div
93
+ style={{
94
+ display: "flex",
95
+ justifyContent: "space-between",
96
+ alignItems: "center",
97
+ gap: 12,
98
+ }}
99
+ >
100
+ <div>
101
+ <div style={{ fontWeight: 600, fontSize: 14, color: "#111827" }}>
102
+ Product Authenticity Verification
103
+ </div>
104
+ <div style={{ fontSize: 12, color: "#6b7280" }}>
105
+ Code: <code>{code}</code>
106
+ </div>
107
+ </div>
108
+ <button
109
+ type="button"
110
+ disabled={loading}
111
+ onClick={() => void verifyAuthenticity(code, signature)}
112
+ style={{
113
+ padding: "6px 12px",
114
+ borderRadius: 6,
115
+ border: "1px solid #111827",
116
+ background: "#111827",
117
+ color: "#ffffff",
118
+ fontSize: 12,
119
+ fontWeight: 600,
120
+ cursor: loading ? "wait" : "pointer",
121
+ }}
122
+ >
123
+ {loading ? "Verifying..." : "Verify HMAC Seal"}
124
+ </button>
125
+ </div>
126
+
127
+ {verificationResult ? (
128
+ <div
129
+ style={{
130
+ padding: "8px 10px",
131
+ borderRadius: 6,
132
+ fontSize: 12,
133
+ fontWeight: 600,
134
+ background: verificationResult.valid ? "#ecfdf5" : "#fef2f2",
135
+ color: verificationResult.valid ? "#065f46" : "#991b1b",
136
+ border: `1px solid ${
137
+ verificationResult.valid ? "#a7f3d0" : "#fecaca"
138
+ }`,
139
+ }}
140
+ >
141
+ {verificationResult.valid
142
+ ? `Authentic Verified: ${verificationResult.reason}`
143
+ : `Verification Failed: ${verificationResult.reason}`}
144
+ </div>
145
+ ) : null}
146
+ </div>
147
+ )
148
+ }
149
+
150
+ export interface StorefrontBarcodeScannerProps {
151
+ sdkOptions?: BarcodeSdkOptions
152
+ enableHidScanner?: boolean
153
+ onResolved?: (result: Record<string, unknown>) => void
154
+ }
155
+
156
+ /**
157
+ * Interactive Storefront Camera & USB HID Barcode/QR Scanner widget.
158
+ */
159
+ export function StorefrontBarcodeScanner({
160
+ sdkOptions,
161
+ enableHidScanner = true,
162
+ onResolved,
163
+ }: StorefrontBarcodeScannerProps) {
164
+ const [manualCode, setManualCode] = useState("")
165
+ const { loading, error, scanResult, resolveScan } =
166
+ useStoreBarcodeResolver(sdkOptions)
167
+
168
+ const handleDetected = async (barcode: string) => {
169
+ setManualCode(barcode)
170
+ const res = await resolveScan(barcode)
171
+ if (res && onResolved) {
172
+ onResolved(res)
173
+ }
174
+ }
175
+
176
+ useHidBarcodeScanner({
177
+ enabled: enableHidScanner,
178
+ onScan: (barcode) => {
179
+ void handleDetected(barcode)
180
+ },
181
+ })
182
+
183
+ const { videoRef, isScanning, cameraError, startCamera, stopCamera } =
184
+ useCameraBarcodeScanner({
185
+ onScan: (barcode) => {
186
+ void handleDetected(barcode)
187
+ },
188
+ })
189
+
190
+ return (
191
+ <div
192
+ style={{
193
+ border: "1px solid #e5e7eb",
194
+ borderRadius: 12,
195
+ padding: 16,
196
+ background: "#ffffff",
197
+ display: "flex",
198
+ flexDirection: "column",
199
+ gap: 12,
200
+ }}
201
+ >
202
+ <div
203
+ style={{
204
+ display: "flex",
205
+ justifyContent: "space-between",
206
+ alignItems: "center",
207
+ }}
208
+ >
209
+ <span style={{ fontWeight: 700, fontSize: 15, color: "#111827" }}>
210
+ Scan Product Barcode or QR
211
+ </span>
212
+ <button
213
+ type="button"
214
+ onClick={() => (isScanning ? stopCamera() : void startCamera())}
215
+ style={{
216
+ padding: "6px 12px",
217
+ borderRadius: 6,
218
+ border: "1px solid #d1d5db",
219
+ background: isScanning ? "#fee2e2" : "#f3f4f6",
220
+ color: isScanning ? "#991b1b" : "#111827",
221
+ fontSize: 12,
222
+ fontWeight: 600,
223
+ cursor: "pointer",
224
+ }}
225
+ >
226
+ {isScanning ? "Stop Camera" : "Use Camera Scanner"}
227
+ </button>
228
+ </div>
229
+
230
+ {isScanning ? (
231
+ <video
232
+ ref={videoRef}
233
+ muted
234
+ playsInline
235
+ style={{
236
+ width: "100%",
237
+ maxHeight: 220,
238
+ borderRadius: 8,
239
+ background: "#000000",
240
+ objectFit: "cover",
241
+ }}
242
+ />
243
+ ) : null}
244
+
245
+ {cameraError ? (
246
+ <div style={{ fontSize: 12, color: "#b91c1c" }}>{cameraError}</div>
247
+ ) : null}
248
+
249
+ <div style={{ display: "flex", gap: 8 }}>
250
+ <input
251
+ type="text"
252
+ value={manualCode}
253
+ onChange={(e) => setManualCode(e.target.value)}
254
+ placeholder="Scan or enter EAN-13, UPC, ISBN, or QR code..."
255
+ style={{
256
+ flex: 1,
257
+ padding: "8px 10px",
258
+ borderRadius: 6,
259
+ border: "1px solid #d1d5db",
260
+ fontSize: 13,
261
+ }}
262
+ />
263
+ <button
264
+ type="button"
265
+ disabled={loading || !manualCode.trim()}
266
+ onClick={() => void handleDetected(manualCode.trim())}
267
+ style={{
268
+ padding: "8px 14px",
269
+ borderRadius: 6,
270
+ border: "1px solid #111827",
271
+ background: "#111827",
272
+ color: "#ffffff",
273
+ fontSize: 13,
274
+ fontWeight: 600,
275
+ cursor: "pointer",
276
+ }}
277
+ >
278
+ {loading ? "Looking up..." : "Lookup"}
279
+ </button>
280
+ </div>
281
+
282
+ {error ? (
283
+ <div style={{ fontSize: 12, color: "#b91c1c" }}>{error}</div>
284
+ ) : null}
285
+
286
+ {scanResult ? (
287
+ <div
288
+ style={{
289
+ padding: 10,
290
+ borderRadius: 8,
291
+ background: "#f9fafb",
292
+ border: "1px solid #e5e7eb",
293
+ fontSize: 12,
294
+ }}
295
+ >
296
+ <div>
297
+ <strong>Code:</strong> {String(scanResult.code || "")}
298
+ </div>
299
+ <div>
300
+ <strong>Action:</strong> {String(scanResult.action || "view")}
301
+ </div>
302
+ {scanResult.target_url ? (
303
+ <div>
304
+ <strong>Target URL:</strong> {String(scanResult.target_url)}
305
+ </div>
306
+ ) : null}
307
+ </div>
308
+ ) : null}
309
+ </div>
310
+ )
311
+ }
@@ -0,0 +1,56 @@
1
+ # Workflows
2
+
3
+ Medusa v2 workflows that implement `medusa-plugin-barcode` catalog enrichment, batch importing, GS1 variant barcode generation, dynamic tag signing, and warehouse stock-take reconciliation. Each workflow is composed of atomic, compensable steps.
4
+
5
+ ```sh
6
+ workflows/
7
+ ├── index.ts re-exports every workflow and input type
8
+ ├── helpers.ts shared tryResolveService
9
+ ├── lookup-and-create-product.ts
10
+ ├── batch-barcode-import.ts
11
+ ├── bulk-generate-variant-barcodes.ts
12
+ ├── generate-barcode-tag.ts
13
+ ├── scan-inventory-count.ts
14
+ └── apply-inventory-count.ts
15
+ ```
16
+
17
+ ---
18
+
19
+ ## Step & workflow conventions
20
+
21
+ - Every step is created with `createStep` and every workflow is created with `createWorkflow` from `@medusajs/framework/workflows-sdk`.
22
+ - Every step ID and workflow ID uses explicit kebab-case matching its name (e.g. `"lookup-and-create-product"`), satisfying `@medusajs/eslint-plugin` rules.
23
+ - Steps resolve `BARCODE_MODULE` (`"barcode"`) and optional Medusa core modules (`Modules.PRODUCT`, `Modules.FILE`, `Modules.INVENTORY`) from `container`.
24
+ - Every mutating step defines a `compensate` handler to roll back created records or restore previous state if a downstream error occurs.
25
+
26
+ ---
27
+
28
+ ## Workflow index
29
+
30
+ | Workflow Export | Workflow / Step ID | Trigger / Caller | Step Actions | Rollback Compensation |
31
+ | ------------------------------------- | ---------------------------------- | ------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
32
+ | `lookupAndCreateProductWorkflow` | `"lookup-and-create-product"` | `POST /admin/barcodes/create-from-barcode` | 1. Calls `barcodeService.lookupBarcode` (`first-hit` or `deep-merge`).<br>2. Optionally downloads external product images (`downloadProductImageBuffer`, SSRF-checked) and uploads them to `Modules.FILE`.<br>3. Maps metadata via `mapToMedusaCreateProduct` and creates a Medusa Product + Variant in `Modules.PRODUCT`.<br>4. Upserts `BarcodeProduct` via `barcodeService.upsertBarcodeProductLink`. | Deletes the created `BarcodeProduct` row (`deleteBarcodeProducts`) and deletes the created Medusa Product (`productService.deleteProducts`). |
33
+ | `batchBarcodeImportWorkflow` | `"batch-barcode-import"` | `POST /admin/barcodes/batch` | Deduplicates up to 100 barcodes, looks up each across the 10-provider chain, creates Medusa Products + Variants in `Modules.PRODUCT` (or draft placeholders when `createMissingAsDraft: true`), and links each via `BarcodeProduct`. | Deletes all `BarcodeProduct` links created during the batch and deletes all Medusa Products created in `Modules.PRODUCT`. |
34
+ | `bulkGenerateVariantBarcodesWorkflow` | `"bulk-generate-variant-barcodes"` | `POST /admin/barcodes/bulk-generate` & `product-created` subscriber | Lists target variants from `Modules.PRODUCT`, generates GS1 in-store (`200`–`299`) EAN-13 codes (`generateInternalVariantBarcode`), updates `barcode`, `ean`, and `upc` on each variant (`upsertProductVariants`), and creates a `BarcodeTag` per variant. | Deletes all newly created `BarcodeTag` rows (`deleteBarcodeTags`) and restores each variant's previous `barcode`, `ean`, and `upc` values via `upsertProductVariants`. |
35
+ | `generateBarcodeTagWorkflow` | `"generate-barcode-tag"` | `POST /admin/barcodes/tags` | Creates or updates a 1D/2D `BarcodeTag` with rendered SVG markup and `HMAC-SHA256` signature (`createOrUpdateBarcodeTag`). When `upload_svg_to_file_module: true`, uploads `<code >.svg` to `Modules.FILE` and stores `svg_url`. | Deletes the created `BarcodeTag` (`deleteBarcodeTags`). |
36
+ | `scanInventoryCountWorkflow` | `"scan-inventory-count"` | `POST /admin/barcodes/count-sessions/:id/scan` | Calls `barcodeService.recordCountSessionScan` to apply a `+1`, `-1`, or `set_quantity` scan to a `BarcodeCountItem` and recalculate `BarcodeCountSession` totals and variance. | Returns `{ sessionId, itemId }` context for audit tracking. |
37
+ | `applyInventoryCountWorkflow` | `"apply-inventory-count"` | `POST /admin/barcodes/count-sessions/:id/apply` | Marks the `BarcodeCountSession` as `"completed"` (`completeCountSession`) and, for every item with a non-zero variance and SKU, updates `stocked_quantity` at `location_id` in `Modules.INVENTORY` (`updateInventoryLevels`). | Reverts the `BarcodeCountSession` status back to `"in_progress"` and clears `completed_at`. |
38
+
39
+ ---
40
+
41
+ ## Executing a workflow
42
+
43
+ All workflows can be imported from `medusa-plugin-barcode` or `medusa-plugin-barcode/workflows` and executed in API routes, subscribers, or custom services:
44
+
45
+ ```ts
46
+ import { lookupAndCreateProductWorkflow } from "medusa-plugin-barcode/workflows"
47
+
48
+ const { result } = await lookupAndCreateProductWorkflow(req.scope).run({
49
+ input: {
50
+ barcode: "3017620422003",
51
+ status: "draft",
52
+ strategy: "deep-merge",
53
+ downloadImages: false,
54
+ },
55
+ })
56
+ ```
@@ -0,0 +1,115 @@
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 { tryResolveService } from "./helpers"
12
+
13
+ export interface ApplyInventoryCountInput {
14
+ session_id: string
15
+ location_id?: string | null
16
+ }
17
+
18
+ const applyInventoryCountStep = createStep(
19
+ "apply-inventory-count",
20
+ async (input: ApplyInventoryCountInput, { container }) => {
21
+ const barcodeService = container.resolve(
22
+ BARCODE_MODULE
23
+ ) as BarcodeModuleService
24
+
25
+ const completed = await barcodeService.completeCountSession(
26
+ input.session_id
27
+ )
28
+ const inventoryService = tryResolveService(container, [
29
+ Modules.INVENTORY,
30
+ "inventory",
31
+ ])
32
+
33
+ const adjustments: Array<{
34
+ barcode: string
35
+ variant_id: string | null
36
+ expected_quantity: number
37
+ counted_quantity: number
38
+ variance: number
39
+ applied_to_inventory_module: boolean
40
+ }> = []
41
+
42
+ const locationId =
43
+ input.location_id || completed.session.location_id || null
44
+
45
+ for (const item of completed.items) {
46
+ const variance = Number(item.variance || 0)
47
+ let applied = false
48
+
49
+ if (
50
+ variance !== 0 &&
51
+ locationId &&
52
+ item.sku &&
53
+ inventoryService &&
54
+ typeof inventoryService.listInventoryItems === "function" &&
55
+ typeof inventoryService.updateInventoryLevels === "function"
56
+ ) {
57
+ try {
58
+ const invItems = (await inventoryService.listInventoryItems(
59
+ { sku: item.sku },
60
+ { take: 1 }
61
+ )) as Array<{ id: string }>
62
+ if (invItems?.[0]?.id) {
63
+ await inventoryService.updateInventoryLevels([
64
+ {
65
+ inventory_item_id: invItems[0].id,
66
+ location_id: locationId,
67
+ stocked_quantity: Number(item.counted_quantity || 0),
68
+ },
69
+ ])
70
+ applied = true
71
+ }
72
+ } catch {
73
+ applied = false
74
+ }
75
+ }
76
+
77
+ adjustments.push({
78
+ barcode: item.barcode,
79
+ variant_id: item.variant_id ?? null,
80
+ expected_quantity: Number(item.expected_quantity || 0),
81
+ counted_quantity: Number(item.counted_quantity || 0),
82
+ variance,
83
+ applied_to_inventory_module: applied,
84
+ })
85
+ }
86
+
87
+ return new StepResponse(
88
+ {
89
+ session: completed.session,
90
+ adjustments_count: adjustments.length,
91
+ adjustments,
92
+ },
93
+ { sessionId: input.session_id }
94
+ )
95
+ },
96
+ async (compInput, { container }) => {
97
+ if (!compInput?.sessionId) return
98
+ const barcodeService = container.resolve(
99
+ BARCODE_MODULE
100
+ ) as BarcodeModuleService
101
+ await barcodeService.updateBarcodeCountSessions({
102
+ id: compInput.sessionId,
103
+ status: "in_progress",
104
+ completed_at: null,
105
+ })
106
+ }
107
+ )
108
+
109
+ export const applyInventoryCountWorkflow = createWorkflow(
110
+ "apply-inventory-count",
111
+ (input: ApplyInventoryCountInput) => {
112
+ const result = applyInventoryCountStep(input)
113
+ return new WorkflowResponse(result)
114
+ }
115
+ )
@@ -0,0 +1,218 @@
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_EVENTS,
12
+ BARCODE_MODULE,
13
+ type EnrichmentStrategy,
14
+ type NormalizedBarcodeProduct,
15
+ type VariantPriceInput,
16
+ } from "../modules/barcode/types"
17
+ import { mapToMedusaCreateProduct } from "../modules/barcode/utils/normalize-product"
18
+ import { tryResolveService } from "./helpers"
19
+
20
+ export interface BatchBarcodeImportInput {
21
+ barcodes: string[]
22
+ status?: "draft" | "published"
23
+ publishImmediately?: boolean
24
+ strategy?: EnrichmentStrategy
25
+ createMissingAsDraft?: boolean
26
+ prices?: VariantPriceInput[]
27
+ salesChannelIds?: string[]
28
+ categoryIds?: string[]
29
+ collectionId?: string | null
30
+ }
31
+
32
+ const batchBarcodeImportStep = createStep(
33
+ "batch-barcode-import",
34
+ async (input: BatchBarcodeImportInput, { container }) => {
35
+ const barcodeService = container.resolve(
36
+ BARCODE_MODULE
37
+ ) as BarcodeModuleService
38
+ const productService = tryResolveService(container, [
39
+ Modules.PRODUCT,
40
+ "product",
41
+ ])
42
+ const eventBus = tryResolveService(container, [
43
+ Modules.EVENT_BUS,
44
+ "event_bus",
45
+ ])
46
+
47
+ const imported: Array<{
48
+ barcode: string
49
+ product_id: string
50
+ variant_id: string | null
51
+ name: string
52
+ provider: string
53
+ }> = []
54
+ const notFound: string[] = []
55
+ const errors: Array<{ barcode: string; error: string }> = []
56
+ const createdBarcodeProductIds: string[] = []
57
+ const createdMedusaProductIds: string[] = []
58
+
59
+ const uniqueBarcodes = Array.from(
60
+ new Set(input.barcodes.map((b) => String(b).trim()).filter(Boolean))
61
+ ).slice(0, 100)
62
+
63
+ for (const rawBarcode of uniqueBarcodes) {
64
+ try {
65
+ const lookup = await barcodeService.lookupBarcode(rawBarcode, {
66
+ strategy: input.strategy,
67
+ })
68
+
69
+ if (!lookup.found && !input.createMissingAsDraft) {
70
+ notFound.push(lookup.barcode)
71
+ continue
72
+ }
73
+
74
+ const normalized: NormalizedBarcodeProduct = lookup.product || {
75
+ barcode: lookup.barcode,
76
+ barcode_type: lookup.parsed.type,
77
+ name: `Draft Product ${lookup.barcode}`,
78
+ description: null,
79
+ brand: null,
80
+ manufacturer: null,
81
+ categories: [],
82
+ images: [],
83
+ weight: null,
84
+ weight_unit: null,
85
+ dimensions: null,
86
+ quantity_label: null,
87
+ ingredients: null,
88
+ nutrition: null,
89
+ country_of_origin: null,
90
+ suggested_price: null,
91
+ currency_code: "USD",
92
+ isbn: null,
93
+ authors: [],
94
+ publisher: null,
95
+ published_date: null,
96
+ page_count: null,
97
+ provider: "manual",
98
+ raw_data: {},
99
+ }
100
+
101
+ const createPayload = mapToMedusaCreateProduct(normalized, {
102
+ status: input.status || "draft",
103
+ publishImmediately: input.publishImmediately,
104
+ prices: input.prices,
105
+ salesChannelIds: input.salesChannelIds,
106
+ categoryIds: input.categoryIds,
107
+ collectionId: input.collectionId ?? undefined,
108
+ })
109
+
110
+ let productId = `prod_${lookup.barcode}`
111
+ let variantId: string | null = `variant_${lookup.barcode}`
112
+
113
+ if (
114
+ productService &&
115
+ typeof productService.createProducts === "function"
116
+ ) {
117
+ const created = await productService.createProducts([createPayload])
118
+ const first = Array.isArray(created) ? created[0] : created
119
+ if (first && typeof first === "object" && "id" in first) {
120
+ productId = String((first as { id: string }).id)
121
+ const variants = (first as { variants?: Array<{ id?: string }> })
122
+ .variants
123
+ variantId = variants?.[0]?.id ? String(variants[0].id) : null
124
+ createdMedusaProductIds.push(productId)
125
+ }
126
+ }
127
+
128
+ const link = await barcodeService.upsertBarcodeProductLink({
129
+ barcode: lookup.barcode,
130
+ product_id: productId,
131
+ variant_id: variantId,
132
+ provider: normalized.provider,
133
+ product_data: normalized,
134
+ status: "created",
135
+ })
136
+ createdBarcodeProductIds.push(link.id)
137
+
138
+ if (eventBus && typeof eventBus.emit === "function") {
139
+ try {
140
+ await eventBus.emit({
141
+ name: BARCODE_EVENTS.PRODUCT_CREATED,
142
+ data: {
143
+ barcode: lookup.barcode,
144
+ product_id: productId,
145
+ variant_id: variantId,
146
+ provider: normalized.provider,
147
+ },
148
+ })
149
+ } catch {
150
+ // Non-fatal
151
+ }
152
+ }
153
+
154
+ imported.push({
155
+ barcode: lookup.barcode,
156
+ product_id: productId,
157
+ variant_id: variantId,
158
+ name: normalized.name,
159
+ provider: normalized.provider,
160
+ })
161
+ } catch (err) {
162
+ errors.push({
163
+ barcode: rawBarcode,
164
+ error: err instanceof Error ? err.message : "Import failed",
165
+ })
166
+ }
167
+ }
168
+
169
+ return new StepResponse(
170
+ {
171
+ total_requested: uniqueBarcodes.length,
172
+ imported_count: imported.length,
173
+ not_found_count: notFound.length,
174
+ error_count: errors.length,
175
+ imported,
176
+ not_found: notFound,
177
+ errors,
178
+ },
179
+ {
180
+ createdBarcodeProductIds,
181
+ createdMedusaProductIds,
182
+ }
183
+ )
184
+ },
185
+ async (compInput, { container }) => {
186
+ if (!compInput) return
187
+ const barcodeService = container.resolve(
188
+ BARCODE_MODULE
189
+ ) as BarcodeModuleService
190
+
191
+ if (compInput.createdBarcodeProductIds.length > 0) {
192
+ await barcodeService.deleteBarcodeProducts(
193
+ compInput.createdBarcodeProductIds
194
+ )
195
+ }
196
+
197
+ if (compInput.createdMedusaProductIds.length > 0) {
198
+ const productService = tryResolveService(container, [
199
+ Modules.PRODUCT,
200
+ "product",
201
+ ])
202
+ if (
203
+ productService &&
204
+ typeof productService.deleteProducts === "function"
205
+ ) {
206
+ await productService.deleteProducts(compInput.createdMedusaProductIds)
207
+ }
208
+ }
209
+ }
210
+ )
211
+
212
+ export const batchBarcodeImportWorkflow = createWorkflow(
213
+ "batch-barcode-import",
214
+ (input: BatchBarcodeImportInput) => {
215
+ const result = batchBarcodeImportStep(input)
216
+ return new WorkflowResponse(result)
217
+ }
218
+ )