@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,466 @@
1
+ import { useCallback, useEffect, useState } from "react"
2
+ import { toast } from "@medusajs/ui"
3
+ import { useTranslation } from "react-i18next"
4
+
5
+ import { useHidBarcodeScanner } from "../../hooks"
6
+ import type {
7
+ BarcodeLookupChainResult,
8
+ BarcodeScanAction,
9
+ BarcodeSymbology,
10
+ EnrichmentStrategy,
11
+ LabelPrintOutput,
12
+ LabelTemplateSpec,
13
+ } from "../../modules/barcode/types"
14
+ import { createBarcodeSdk } from "../../sdk"
15
+
16
+ const defaultAdminSdk = createBarcodeSdk()
17
+
18
+ export interface LookupFormState {
19
+ barcode: string
20
+ strategy: EnrichmentStrategy
21
+ status: "draft" | "published"
22
+ downloadImages: boolean
23
+ batchInput: string
24
+ }
25
+
26
+ export interface TagFormState {
27
+ target_id: string
28
+ label: string
29
+ symbology: BarcodeSymbology
30
+ scan_action: BarcodeScanAction
31
+ gs1_gtin: string
32
+ batch_lot: string
33
+ serial_number: string
34
+ }
35
+
36
+ export interface PrintFormState {
37
+ template_id: string
38
+ barcode: string
39
+ title: string
40
+ variant_title: string
41
+ sku: string
42
+ brand: string
43
+ price: number
44
+ compare_at_price: number
45
+ currency_code: string
46
+ quantity: number
47
+ }
48
+
49
+ export interface CountSessionFormState {
50
+ name: string
51
+ location_id: string
52
+ notes: string
53
+ scan_barcode: string
54
+ scan_title: string
55
+ expected_quantity: number
56
+ }
57
+
58
+ export const useBarcodeStudio = () => {
59
+ const { t } = useTranslation()
60
+ const [barcodes, setBarcodes] = useState<Array<Record<string, unknown>>>([])
61
+ const [overview, setOverview] = useState<Record<string, unknown>>({})
62
+ const [tags, setTags] = useState<Array<Record<string, unknown>>>([])
63
+ const [templates, setTemplates] = useState<LabelTemplateSpec[]>([])
64
+ const [sessions, setSessions] = useState<Array<Record<string, unknown>>>([])
65
+ const [cacheEntries, setCacheEntries] = useState<
66
+ Array<Record<string, unknown>>
67
+ >([])
68
+
69
+ const [bannerMessage, setBannerMessage] = useState<string | null>(null)
70
+ const [bannerTone, setBannerTone] = useState<"success" | "error">("success")
71
+ const [isLoading, setIsLoading] = useState(false)
72
+
73
+ const [lookupForm, setLookupForm] = useState<LookupFormState>({
74
+ barcode: "3017620422003",
75
+ strategy: "first-hit",
76
+ status: "draft",
77
+ downloadImages: false,
78
+ batchInput: "3017620422003\n9780140328721",
79
+ })
80
+ const [lookupResult, setLookupResult] =
81
+ useState<BarcodeLookupChainResult | null>(null)
82
+
83
+ const [tagForm, setTagForm] = useState<TagFormState>({
84
+ target_id: "prod_01",
85
+ label: "Flagship Edition",
86
+ symbology: "qr",
87
+ scan_action: "verify",
88
+ gs1_gtin: "09506000134352",
89
+ batch_lot: "LOT-2026-A",
90
+ serial_number: "SN-000192",
91
+ })
92
+
93
+ const [printForm, setPrintForm] = useState<PrintFormState>({
94
+ template_id: "thermal_50x25",
95
+ barcode: "2001234567893",
96
+ title: "Organic Espresso Beans",
97
+ variant_title: "250g Whole Bean",
98
+ sku: "ESP-250-WB",
99
+ brand: "Medusa Roasters",
100
+ price: 14.5,
101
+ compare_at_price: 18.0,
102
+ currency_code: "USD",
103
+ quantity: 4,
104
+ })
105
+ const [printOutput, setPrintOutput] = useState<LabelPrintOutput | null>(null)
106
+
107
+ const [countForm, setCountForm] = useState<CountSessionFormState>({
108
+ name: "Q4 Warehouse Cycle Count",
109
+ location_id: "sloc_main_warehouse",
110
+ notes: "Aisle 1-4 audit",
111
+ scan_barcode: "2001234567893",
112
+ scan_title: "Organic Espresso Beans",
113
+ expected_quantity: 10,
114
+ })
115
+ const [selectedSessionId, setSelectedSessionId] = useState<string | null>(
116
+ null
117
+ )
118
+
119
+ const notify = useCallback(
120
+ (msg: string, tone: "success" | "error" = "success") => {
121
+ setBannerTone(tone)
122
+ setBannerMessage(msg)
123
+ if (tone === "error") {
124
+ toast.error(msg)
125
+ } else {
126
+ toast.success(msg)
127
+ }
128
+ },
129
+ []
130
+ )
131
+
132
+ const refreshAll = useCallback(async () => {
133
+ setIsLoading(true)
134
+ try {
135
+ const [barcodesRes, tagsRes, templatesRes, sessionsRes, cacheRes] =
136
+ await Promise.all([
137
+ defaultAdminSdk.admin.listBarcodes(),
138
+ defaultAdminSdk.admin.listTags(),
139
+ defaultAdminSdk.admin.listTemplates(),
140
+ defaultAdminSdk.admin.listCountSessions(),
141
+ defaultAdminSdk.admin.listCache(),
142
+ ])
143
+
144
+ setBarcodes(barcodesRes.barcodes || [])
145
+ setOverview(barcodesRes.overview || {})
146
+ setTags(tagsRes.tags || [])
147
+ setTemplates(templatesRes.templates || [])
148
+ setSessions(sessionsRes.sessions || [])
149
+ setCacheEntries(cacheRes.cache_entries || [])
150
+ if (!selectedSessionId && sessionsRes.sessions?.[0]?.id) {
151
+ setSelectedSessionId(String(sessionsRes.sessions[0].id))
152
+ }
153
+ } catch (err) {
154
+ notify(
155
+ err instanceof Error ? err.message : t("messages.loadStudioError"),
156
+ "error"
157
+ )
158
+ } finally {
159
+ setIsLoading(false)
160
+ }
161
+ }, [selectedSessionId, t])
162
+
163
+ useEffect(() => {
164
+ void refreshAll()
165
+ }, [refreshAll])
166
+
167
+ // Hardware USB HID keyboard-wedge scanner integration
168
+ const { lastScanned } = useHidBarcodeScanner({
169
+ enabled: true,
170
+ onScan: (scannedBarcode) => {
171
+ setLookupForm((prev) => ({ ...prev, barcode: scannedBarcode }))
172
+ notify(t("messages.hidScanDetected", { barcode: scannedBarcode }))
173
+ },
174
+ })
175
+
176
+ const handleLookupBarcode = async () => {
177
+ if (!lookupForm.barcode.trim()) return
178
+ try {
179
+ const res = await defaultAdminSdk.admin.lookup({
180
+ barcode: lookupForm.barcode.trim(),
181
+ strategy: lookupForm.strategy,
182
+ })
183
+ setLookupResult(res)
184
+ notify(
185
+ res.found
186
+ ? t("messages.lookupFound", {
187
+ name: res.product?.name ?? "",
188
+ provider: res.product?.provider ?? "",
189
+ })
190
+ : t("messages.lookupNotFound", { barcode: res.barcode }),
191
+ res.found ? "success" : "error"
192
+ )
193
+ await refreshAll()
194
+ } catch (err) {
195
+ notify(
196
+ err instanceof Error ? err.message : t("messages.lookupError"),
197
+ "error"
198
+ )
199
+ }
200
+ }
201
+
202
+ const handleCreateProductFromBarcode = async () => {
203
+ if (!lookupForm.barcode.trim()) return
204
+ try {
205
+ const res = await defaultAdminSdk.admin.createFromBarcode({
206
+ barcode: lookupForm.barcode.trim(),
207
+ status: lookupForm.status,
208
+ strategy: lookupForm.strategy,
209
+ downloadImages: lookupForm.downloadImages,
210
+ })
211
+ notify(
212
+ t("messages.productCreated", {
213
+ productId: String(res.product_id || ""),
214
+ barcode: lookupForm.barcode,
215
+ })
216
+ )
217
+ await refreshAll()
218
+ } catch (err) {
219
+ notify(
220
+ err instanceof Error ? err.message : t("messages.productCreateError"),
221
+ "error"
222
+ )
223
+ }
224
+ }
225
+
226
+ const handleBatchImport = async () => {
227
+ const lines = lookupForm.batchInput
228
+ .split(/[\r\n,;]+/)
229
+ .map((s) => s.trim())
230
+ .filter(Boolean)
231
+ if (lines.length === 0) return
232
+
233
+ try {
234
+ const res = await defaultAdminSdk.admin.batchImport({
235
+ barcodes: lines,
236
+ status: lookupForm.status,
237
+ strategy: lookupForm.strategy,
238
+ createMissingAsDraft: true,
239
+ })
240
+ notify(
241
+ t("messages.batchImportFinished", {
242
+ imported: String(res.imported_count || 0),
243
+ notFound: String(res.not_found_count || 0),
244
+ })
245
+ )
246
+ await refreshAll()
247
+ } catch (err) {
248
+ notify(
249
+ err instanceof Error ? err.message : t("messages.batchImportError"),
250
+ "error"
251
+ )
252
+ }
253
+ }
254
+
255
+ const handleBulkGenerateBarcodes = async () => {
256
+ try {
257
+ const res = await defaultAdminSdk.admin.bulkGenerate({
258
+ prefix: "200",
259
+ overwrite: false,
260
+ })
261
+ notify(
262
+ t("messages.bulkGenerated", {
263
+ count: String(res.generated_count || 0),
264
+ })
265
+ )
266
+ await refreshAll()
267
+ } catch (err) {
268
+ notify(
269
+ err instanceof Error ? err.message : t("messages.bulkGenerateError"),
270
+ "error"
271
+ )
272
+ }
273
+ }
274
+
275
+ const handleCreateTag = async (override?: Partial<TagFormState>) => {
276
+ const payload = { ...tagForm, ...override }
277
+ if (!payload.target_id.trim()) return
278
+ try {
279
+ const res = await defaultAdminSdk.admin.createTag({
280
+ target_id: payload.target_id.trim(),
281
+ label: payload.label.trim() || null,
282
+ symbology: payload.symbology,
283
+ scan_action: payload.scan_action,
284
+ gs1_gtin: payload.gs1_gtin.trim() || null,
285
+ batch_lot: payload.batch_lot.trim() || null,
286
+ serial_number: payload.serial_number.trim() || null,
287
+ })
288
+ notify(t("messages.tagCreated", { code: String(res.tag?.code || "") }))
289
+ await refreshAll()
290
+ } catch (err) {
291
+ notify(
292
+ err instanceof Error ? err.message : t("messages.tagCreateError"),
293
+ "error"
294
+ )
295
+ }
296
+ }
297
+
298
+ const handleDeleteTag = async (id: string) => {
299
+ try {
300
+ await defaultAdminSdk.admin.deleteTag(id)
301
+ notify(t("messages.tagDeleted"))
302
+ await refreshAll()
303
+ } catch (err) {
304
+ notify(
305
+ err instanceof Error ? err.message : t("messages.tagDeleteError"),
306
+ "error"
307
+ )
308
+ }
309
+ }
310
+
311
+ const handleRenderLabels = async () => {
312
+ try {
313
+ const res = await defaultAdminSdk.admin.printLabels({
314
+ template_id: printForm.template_id,
315
+ items: [
316
+ {
317
+ barcode: printForm.barcode,
318
+ title: printForm.title,
319
+ variant_title: printForm.variant_title || null,
320
+ sku: printForm.sku || null,
321
+ brand: printForm.brand || null,
322
+ price: printForm.price,
323
+ compare_at_price: printForm.compare_at_price,
324
+ currency_code: printForm.currency_code,
325
+ quantity: printForm.quantity,
326
+ },
327
+ ],
328
+ })
329
+ setPrintOutput(res)
330
+ notify(
331
+ t("messages.labelsRendered", {
332
+ count: res.total_labels,
333
+ name: res.template.name,
334
+ })
335
+ )
336
+ } catch (err) {
337
+ notify(
338
+ err instanceof Error ? err.message : t("messages.labelsRenderError"),
339
+ "error"
340
+ )
341
+ }
342
+ }
343
+
344
+ const handleCreateCountSession = async () => {
345
+ if (!countForm.name.trim()) return
346
+ try {
347
+ const res = await defaultAdminSdk.admin.createCountSession({
348
+ name: countForm.name.trim(),
349
+ location_id: countForm.location_id.trim() || null,
350
+ notes: countForm.notes.trim() || null,
351
+ expected_items: countForm.scan_barcode
352
+ ? [
353
+ {
354
+ barcode: countForm.scan_barcode.trim(),
355
+ title:
356
+ countForm.scan_title.trim() ||
357
+ t("messages.defaultCatalogItemTitle"),
358
+ expected_quantity: countForm.expected_quantity,
359
+ },
360
+ ]
361
+ : [],
362
+ })
363
+ const newSession = res.session as { id?: string } | undefined
364
+ if (newSession?.id) {
365
+ setSelectedSessionId(newSession.id)
366
+ }
367
+ notify(t("messages.sessionCreated", { name: countForm.name }))
368
+ await refreshAll()
369
+ } catch (err) {
370
+ notify(
371
+ err instanceof Error ? err.message : t("messages.sessionCreateError"),
372
+ "error"
373
+ )
374
+ }
375
+ }
376
+
377
+ const handleScanIntoSession = async (delta = 1) => {
378
+ if (!selectedSessionId || !countForm.scan_barcode.trim()) return
379
+ try {
380
+ await defaultAdminSdk.admin.recordCountScan(selectedSessionId, {
381
+ barcode: countForm.scan_barcode.trim(),
382
+ delta,
383
+ title: countForm.scan_title.trim() || undefined,
384
+ expected_quantity: countForm.expected_quantity,
385
+ })
386
+ notify(
387
+ t("messages.scanRecorded", {
388
+ delta: delta > 0 ? `+${delta}` : String(delta),
389
+ barcode: countForm.scan_barcode,
390
+ })
391
+ )
392
+ await refreshAll()
393
+ } catch (err) {
394
+ notify(
395
+ err instanceof Error ? err.message : t("messages.scanError"),
396
+ "error"
397
+ )
398
+ }
399
+ }
400
+
401
+ const handleApplyCountSession = async (sessionId: string) => {
402
+ try {
403
+ await defaultAdminSdk.admin.applyCountSession(sessionId, {
404
+ location_id: countForm.location_id || null,
405
+ })
406
+ notify(t("messages.sessionApplied"))
407
+ await refreshAll()
408
+ } catch (err) {
409
+ notify(
410
+ err instanceof Error ? err.message : t("messages.sessionApplyError"),
411
+ "error"
412
+ )
413
+ }
414
+ }
415
+
416
+ const handlePurgeCache = async (clearAll = false) => {
417
+ try {
418
+ const res = await defaultAdminSdk.admin.purgeCache(clearAll)
419
+ notify(t("messages.cachePurged", { count: res.purged_count }))
420
+ await refreshAll()
421
+ } catch (err) {
422
+ notify(
423
+ err instanceof Error ? err.message : t("messages.cachePurgeError"),
424
+ "error"
425
+ )
426
+ }
427
+ }
428
+
429
+ return {
430
+ barcodes,
431
+ overview,
432
+ tags,
433
+ templates,
434
+ sessions,
435
+ cacheEntries,
436
+ bannerMessage,
437
+ bannerTone,
438
+ isLoading,
439
+ lastScanned,
440
+ lookupForm,
441
+ setLookupForm,
442
+ lookupResult,
443
+ tagForm,
444
+ setTagForm,
445
+ printForm,
446
+ setPrintForm,
447
+ printOutput,
448
+ countForm,
449
+ setCountForm,
450
+ selectedSessionId,
451
+ setSelectedSessionId,
452
+ dismissBanner: () => setBannerMessage(null),
453
+ onRefresh: () => void refreshAll(),
454
+ handleLookupBarcode,
455
+ handleCreateProductFromBarcode,
456
+ handleBatchImport,
457
+ handleBulkGenerateBarcodes,
458
+ handleCreateTag,
459
+ handleDeleteTag,
460
+ handleRenderLabels,
461
+ handleCreateCountSession,
462
+ handleScanIntoSession,
463
+ handleApplyCountSession,
464
+ handlePurgeCache,
465
+ }
466
+ }
@@ -0,0 +1,139 @@
1
+ import { useCallback, useEffect, useState } from "react"
2
+ import { toast } from "@medusajs/ui"
3
+ import { useTranslation } from "react-i18next"
4
+
5
+ import type { LabelPrintOutput } from "../../modules/barcode/types"
6
+ import { createBarcodeSdk } from "../../sdk"
7
+
8
+ const defaultAdminSdk = createBarcodeSdk()
9
+
10
+ export interface ProductBarcodeWidgetEntity {
11
+ id?: string
12
+ title?: string
13
+ handle?: string
14
+ variants?: Array<{
15
+ id: string
16
+ title?: string | null
17
+ sku?: string | null
18
+ barcode?: string | null
19
+ ean?: string | null
20
+ upc?: string | null
21
+ }>
22
+ }
23
+
24
+ /**
25
+ * Decoupled hook for the Product Detail Barcode & Label Widget (`product.details.after`).
26
+ */
27
+ export const useProductBarcodes = (product?: ProductBarcodeWidgetEntity) => {
28
+ const { t } = useTranslation()
29
+ const productId = product?.id ?? ""
30
+ const [tags, setTags] = useState<Array<Record<string, unknown>>>([])
31
+ const [linkedBarcodes, setLinkedBarcodes] = useState<
32
+ Array<Record<string, unknown>>
33
+ >([])
34
+ const [printPreview, setPrintPreview] = useState<LabelPrintOutput | null>(
35
+ null
36
+ )
37
+ const [isBusy, setIsBusy] = useState(false)
38
+ const [feedback, setFeedback] = useState<string | null>(null)
39
+
40
+ const loadProductBarcodeData = useCallback(async () => {
41
+ if (!productId) return
42
+ try {
43
+ const [barcodesRes, tagsRes] = await Promise.all([
44
+ defaultAdminSdk.admin.listBarcodes({ product_id: productId }),
45
+ defaultAdminSdk.admin.listTags({ product_id: productId }),
46
+ ])
47
+ setLinkedBarcodes(barcodesRes.barcodes || [])
48
+ setTags(tagsRes.tags || [])
49
+ } catch {
50
+ // Non-fatal widget load error
51
+ }
52
+ }, [productId])
53
+
54
+ useEffect(() => {
55
+ void loadProductBarcodeData()
56
+ }, [loadProductBarcodeData])
57
+
58
+ const handleGenerateProductBarcodes = async () => {
59
+ if (!productId) return
60
+ setIsBusy(true)
61
+ try {
62
+ const variantIds = (product?.variants || []).map((v) => v.id)
63
+ const tagRes = await defaultAdminSdk.admin.createTag({
64
+ target_type: "product",
65
+ target_id: productId,
66
+ product_id: productId,
67
+ label: product?.title || productId,
68
+ symbology: "ean13",
69
+ scan_action: "view",
70
+ })
71
+
72
+ if (variantIds.length > 0) {
73
+ await defaultAdminSdk.admin.bulkGenerate({
74
+ variant_ids: variantIds,
75
+ prefix: "200",
76
+ overwrite: false,
77
+ })
78
+ }
79
+
80
+ const msg = t("messages.widgetBarcodeGenerated", {
81
+ code: String(tagRes.tag?.code || ""),
82
+ title: product?.title || productId,
83
+ })
84
+ setFeedback(msg)
85
+ toast.success(msg)
86
+ await loadProductBarcodeData()
87
+ } catch (err) {
88
+ const msg =
89
+ err instanceof Error ? err.message : t("messages.widgetBarcodeError")
90
+ setFeedback(msg)
91
+ toast.error(msg)
92
+ } finally {
93
+ setIsBusy(false)
94
+ }
95
+ }
96
+
97
+ const handleQuickPrintProductLabels = async () => {
98
+ if (!productId) return
99
+ setIsBusy(true)
100
+ try {
101
+ const firstTag = tags[0]
102
+ const code = String(firstTag?.code || "2001234567893")
103
+ const output = await defaultAdminSdk.admin.printLabels({
104
+ template_id: "thermal_50x25",
105
+ items: [
106
+ {
107
+ barcode: code,
108
+ title: product?.title || t("messages.defaultProductLabelTitle"),
109
+ sku: product?.variants?.[0]?.sku || null,
110
+ price: 19.99,
111
+ currency_code: "USD",
112
+ quantity: 1,
113
+ },
114
+ ],
115
+ })
116
+ setPrintPreview(output)
117
+ const msg = t("messages.widgetLabelPrepared", { code })
118
+ setFeedback(msg)
119
+ toast.success(msg)
120
+ } catch (err) {
121
+ const msg =
122
+ err instanceof Error ? err.message : t("messages.widgetLabelError")
123
+ setFeedback(msg)
124
+ toast.error(msg)
125
+ } finally {
126
+ setIsBusy(false)
127
+ }
128
+ }
129
+
130
+ return {
131
+ tags,
132
+ linkedBarcodes,
133
+ printPreview,
134
+ isBusy,
135
+ feedback,
136
+ handleGenerateProductBarcodes,
137
+ handleQuickPrintProductLabels,
138
+ }
139
+ }