@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,57 @@
1
+ import { MedusaError } from "@medusajs/framework/utils"
2
+
3
+ import type { BarcodeOpsContext } from "./context"
4
+ import type { BarcodeSymbology, RenderBarcodeSvgOptions } from "../types"
5
+ import { generateInternalEan13 } from "../utils/barcode-parser"
6
+ import { renderBarcodeSvg } from "../utils/svg-renderer"
7
+
8
+ /**
9
+ * Generates a valid GS1 in-store EAN-13 barcode (prefix 200-299).
10
+ */
11
+ export async function generateInternalVariantBarcode(
12
+ ctx: BarcodeOpsContext,
13
+ input: {
14
+ seed: string
15
+ sequence?: number
16
+ prefix?: string
17
+ }
18
+ ): Promise<{
19
+ barcode: string
20
+ ean: string
21
+ upc: string
22
+ symbology: BarcodeSymbology
23
+ svg: string
24
+ }> {
25
+ const prefix = input.prefix || ctx.options.internalBarcodePrefix || "200"
26
+ const ean13 = generateInternalEan13(input.seed, prefix, input.sequence)
27
+ const upc = ean13.slice(1) // 12-digit representation
28
+ const svg = renderBarcodeSvg({
29
+ code: ean13,
30
+ symbology: "ean13",
31
+ includeText: true,
32
+ })
33
+
34
+ return {
35
+ barcode: ean13,
36
+ ean: ean13,
37
+ upc,
38
+ symbology: "ean13",
39
+ svg,
40
+ }
41
+ }
42
+
43
+ /**
44
+ * Renders any supported 1D/2D barcode symbology into a standalone SVG string.
45
+ */
46
+ export async function renderSvg(
47
+ ctx: BarcodeOpsContext,
48
+ options: RenderBarcodeSvgOptions
49
+ ): Promise<string> {
50
+ if (!options.code || !String(options.code).trim()) {
51
+ throw new MedusaError(
52
+ MedusaError.Types.INVALID_DATA,
53
+ "Barcode value is required to render SVG"
54
+ )
55
+ }
56
+ return renderBarcodeSvg(options)
57
+ }
@@ -0,0 +1,8 @@
1
+ export * from "./lookup"
2
+ export * from "./generation"
3
+ export * from "./tags"
4
+ export * from "./labels"
5
+ export * from "./stock-count"
6
+ export * from "./maintenance"
7
+ export * from "./context"
8
+ export * from "./data-service"
@@ -0,0 +1,90 @@
1
+ import { MedusaError } from "@medusajs/framework/utils"
2
+
3
+ import type { BarcodeOpsContext } from "./context"
4
+ import type {
5
+ BarcodeSymbology,
6
+ LabelPresetId,
7
+ LabelPrintItem,
8
+ LabelPrintOutput,
9
+ LabelTemplateSpec,
10
+ } from "../types"
11
+ import {
12
+ BUILTIN_LABEL_TEMPLATES,
13
+ renderPrintableLabels,
14
+ } from "../utils/label-printer"
15
+
16
+ /**
17
+ * Lists all built-in + custom label templates.
18
+ */
19
+ export async function listAllLabelTemplates(
20
+ ctx: BarcodeOpsContext
21
+ ): Promise<LabelTemplateSpec[]> {
22
+ const builtinList = Object.values(BUILTIN_LABEL_TEMPLATES)
23
+ try {
24
+ const customRows = await ctx.svc.listBarcodeLabelTemplates(
25
+ {},
26
+ { take: 100 }
27
+ )
28
+ const customMapped: LabelTemplateSpec[] = customRows.map((row) => ({
29
+ id: row.id,
30
+ name: row.name,
31
+ preset_id: (row.preset_id as LabelPresetId) || "custom",
32
+ layout_type: row.layout_type as "thermal_roll" | "a4_sheet",
33
+ width_mm: Number(row.width_mm),
34
+ height_mm: Number(row.height_mm),
35
+ columns: Number(row.columns),
36
+ rows: Number(row.rows),
37
+ margin_top_mm: Number(row.margin_top_mm),
38
+ margin_left_mm: Number(row.margin_left_mm),
39
+ gap_x_mm: Number(row.gap_x_mm),
40
+ gap_y_mm: Number(row.gap_y_mm),
41
+ symbology: (row.symbology as BarcodeSymbology) || "ean13",
42
+ show_title: Boolean(row.show_title),
43
+ show_variant_title: Boolean(row.show_variant_title),
44
+ show_sku: Boolean(row.show_sku),
45
+ show_price: Boolean(row.show_price),
46
+ show_compare_at_price: Boolean(row.show_compare_at_price),
47
+ show_brand: Boolean(row.show_brand),
48
+ show_qr: Boolean(row.show_qr),
49
+ custom_header: row.custom_header ?? null,
50
+ custom_footer: row.custom_footer ?? null,
51
+ dpi: (Number(row.dpi) === 300 ? 300 : 203) as 203 | 300,
52
+ is_default: Boolean(row.is_default),
53
+ }))
54
+ return [...builtinList, ...customMapped]
55
+ } catch {
56
+ return builtinList
57
+ }
58
+ }
59
+
60
+ /**
61
+ * Renders printable HTML+SVG and Zebra ZPL II output for a list of label items.
62
+ */
63
+ export async function renderLabels(
64
+ ctx: BarcodeOpsContext,
65
+ input: {
66
+ items: LabelPrintItem[]
67
+ template_id?: string
68
+ template_override?: Partial<LabelTemplateSpec>
69
+ }
70
+ ): Promise<LabelPrintOutput> {
71
+ if (!Array.isArray(input.items) || input.items.length === 0) {
72
+ throw new MedusaError(
73
+ MedusaError.Types.INVALID_DATA,
74
+ "At least one label item is required for printing"
75
+ )
76
+ }
77
+
78
+ const templates = await listAllLabelTemplates(ctx)
79
+ const baseTemplate =
80
+ templates.find(
81
+ (t) => t.id === input.template_id || t.preset_id === input.template_id
82
+ ) || BUILTIN_LABEL_TEMPLATES.thermal_50x25
83
+
84
+ const mergedTemplate: LabelTemplateSpec = {
85
+ ...baseTemplate,
86
+ ...input.template_override,
87
+ }
88
+
89
+ return renderPrintableLabels(input.items, mergedTemplate)
90
+ }
@@ -0,0 +1,202 @@
1
+ import { MedusaError } from "@medusajs/framework/utils"
2
+
3
+ import type { BarcodeOpsContext } from "./context"
4
+ import { runProviderLookupChain } from "../providers"
5
+ import type {
6
+ BarcodeLookupChainResult,
7
+ EnrichmentStrategy,
8
+ NormalizedBarcodeProduct,
9
+ } from "../types"
10
+ import { parseBarcode } from "../utils/barcode-parser"
11
+
12
+ export async function parseAndValidateBarcode(rawBarcode: string) {
13
+ if (!rawBarcode || !String(rawBarcode).trim()) {
14
+ throw new MedusaError(
15
+ MedusaError.Types.INVALID_DATA,
16
+ "Barcode value is required"
17
+ )
18
+ }
19
+ return parseBarcode(rawBarcode)
20
+ }
21
+
22
+ /**
23
+ * Looks up a barcode across the configured provider chain with caching.
24
+ */
25
+ export async function lookupBarcode(
26
+ ctx: BarcodeOpsContext,
27
+ rawBarcode: string,
28
+ lookupOptions: {
29
+ skipCache?: boolean
30
+ strategy?: EnrichmentStrategy
31
+ providers?: string[]
32
+ } = {}
33
+ ): Promise<BarcodeLookupChainResult> {
34
+ const parsed = await parseAndValidateBarcode(rawBarcode)
35
+ const strategy =
36
+ lookupOptions.strategy || ctx.options.enrichmentStrategy || "first-hit"
37
+
38
+ const useCache =
39
+ ctx.options.cacheEnabled !== false && !lookupOptions.skipCache
40
+
41
+ if (useCache) {
42
+ try {
43
+ const cachedRows = await ctx.svc.listBarcodeCaches(
44
+ { barcode: parsed.normalized },
45
+ { take: 1 }
46
+ )
47
+ const cached = cachedRows[0]
48
+ if (cached && cached.expires_at) {
49
+ const expiresAt = new Date(cached.expires_at)
50
+ if (expiresAt.getTime() > Date.now()) {
51
+ const nextHits = Number(cached.hit_count || 0) + 1
52
+ await ctx.svc.updateBarcodeCaches({
53
+ id: cached.id,
54
+ hit_count: nextHits,
55
+ })
56
+
57
+ const cachedProduct = cached.found
58
+ ? (cached.response_data as unknown as NormalizedBarcodeProduct)
59
+ : null
60
+
61
+ return {
62
+ barcode: parsed.normalized,
63
+ parsed,
64
+ found: Boolean(cached.found && cachedProduct),
65
+ cached: true,
66
+ strategy,
67
+ product: cachedProduct,
68
+ outcomes: [
69
+ {
70
+ provider: cached.provider || "cache",
71
+ found: Boolean(cached.found && cachedProduct),
72
+ durationMs: 0,
73
+ product: cachedProduct,
74
+ },
75
+ ],
76
+ }
77
+ }
78
+ }
79
+ } catch {
80
+ // Fallback to live lookup if cache query fails
81
+ }
82
+ }
83
+
84
+ const result = await runProviderLookupChain(parsed.normalized, ctx.registry, {
85
+ strategy,
86
+ preferredProviders: lookupOptions.providers,
87
+ })
88
+
89
+ if (ctx.options.cacheEnabled !== false) {
90
+ const ttlSeconds = ctx.options.cacheTtlSeconds ?? 86400
91
+ const expiresAt = new Date(Date.now() + ttlSeconds * 1000)
92
+ try {
93
+ const existing = await ctx.svc.listBarcodeCaches(
94
+ { barcode: parsed.normalized },
95
+ { take: 1 }
96
+ )
97
+ const payload = {
98
+ barcode: parsed.normalized,
99
+ barcode_type: parsed.type,
100
+ provider:
101
+ result.product?.provider ||
102
+ result.outcomes.map((o) => o.provider).join(",") ||
103
+ "none",
104
+ found: result.found,
105
+ response_data: (result.product || {}) as unknown as Record<
106
+ string,
107
+ unknown
108
+ >,
109
+ expires_at: expiresAt,
110
+ hit_count: existing[0] ? Number(existing[0].hit_count || 0) + 1 : 1,
111
+ }
112
+
113
+ if (existing[0]) {
114
+ await ctx.svc.updateBarcodeCaches({
115
+ id: existing[0].id,
116
+ ...payload,
117
+ })
118
+ } else {
119
+ await ctx.svc.createBarcodeCaches(payload)
120
+ }
121
+ } catch {
122
+ // Non-fatal cache write failure
123
+ }
124
+ }
125
+
126
+ return result
127
+ }
128
+
129
+ /**
130
+ * Finds an existing `BarcodeProduct` mapping for a normalized barcode.
131
+ */
132
+ export async function findBarcodeProduct(
133
+ ctx: BarcodeOpsContext,
134
+ rawBarcode: string
135
+ ) {
136
+ const parsed = await parseAndValidateBarcode(rawBarcode)
137
+ const rows = await ctx.svc.listBarcodeProducts(
138
+ { barcode: parsed.normalized },
139
+ { take: 1 }
140
+ )
141
+ return rows[0] || null
142
+ }
143
+
144
+ /**
145
+ * Removes `BarcodeProduct` mapping(s) for a normalized barcode.
146
+ */
147
+ export async function removeBarcodeProduct(
148
+ ctx: BarcodeOpsContext,
149
+ rawBarcode: string
150
+ ): Promise<{ deleted_count: number }> {
151
+ const parsed = await parseAndValidateBarcode(rawBarcode)
152
+ const rows = await ctx.svc.listBarcodeProducts(
153
+ { barcode: parsed.normalized },
154
+ { take: 50 }
155
+ )
156
+ const ids = rows.map((r) => r.id)
157
+ if (ids.length > 0) {
158
+ await ctx.svc.deleteBarcodeProducts(ids)
159
+ }
160
+ return { deleted_count: ids.length }
161
+ }
162
+
163
+ /**
164
+ * Creates or updates a `BarcodeProduct` mapping between a GTIN/barcode and a Medusa Product/Variant.
165
+ */
166
+ export async function upsertBarcodeProductLink(
167
+ ctx: BarcodeOpsContext,
168
+ input: {
169
+ barcode: string
170
+ product_id: string
171
+ variant_id?: string | null
172
+ provider: string
173
+ product_data: NormalizedBarcodeProduct
174
+ status?: "created" | "linked" | "updated"
175
+ }
176
+ ) {
177
+ const parsed = parseBarcode(input.barcode)
178
+ const existing = await ctx.svc.listBarcodeProducts(
179
+ { barcode: parsed.normalized },
180
+ { take: 1 }
181
+ )
182
+
183
+ const payload = {
184
+ barcode: parsed.normalized,
185
+ barcode_type: parsed.type,
186
+ product_id: input.product_id,
187
+ variant_id: input.variant_id ?? null,
188
+ provider: input.provider,
189
+ product_data: input.product_data as unknown as Record<string, unknown>,
190
+ last_synced_at: new Date(),
191
+ status: input.status || (existing[0] ? "updated" : "created"),
192
+ }
193
+
194
+ if (existing[0]) {
195
+ return await ctx.svc.updateBarcodeProducts({
196
+ id: existing[0].id,
197
+ ...payload,
198
+ })
199
+ }
200
+
201
+ return await ctx.svc.createBarcodeProducts(payload)
202
+ }
@@ -0,0 +1,53 @@
1
+ import type { BarcodeOpsContext } from "./context"
2
+
3
+ /**
4
+ * Purges expired entries from `BarcodeCache`.
5
+ */
6
+ export async function purgeExpiredCache(
7
+ ctx: BarcodeOpsContext
8
+ ): Promise<{ purged_count: number }> {
9
+ const allCache = await ctx.svc.listBarcodeCaches({}, { take: 1000 })
10
+ const now = Date.now()
11
+ const expiredIds = allCache
12
+ .filter(
13
+ (row) => row.expires_at && new Date(row.expires_at).getTime() <= now
14
+ )
15
+ .map((row) => row.id)
16
+
17
+ if (expiredIds.length > 0) {
18
+ await ctx.svc.deleteBarcodeCaches(expiredIds)
19
+ }
20
+
21
+ return { purged_count: expiredIds.length }
22
+ }
23
+
24
+ /**
25
+ * Returns a dashboard analytics overview across products, tags, cache, and stock-take sessions.
26
+ */
27
+ export async function getAnalyticsOverview(ctx: BarcodeOpsContext) {
28
+ const [products, tags, caches, sessions] = await Promise.all([
29
+ ctx.svc.listBarcodeProducts({}, { take: 1000 }),
30
+ ctx.svc.listBarcodeTags({}, { take: 1000 }),
31
+ ctx.svc.listBarcodeCaches({}, { take: 1000 }),
32
+ ctx.svc.listBarcodeCountSessions({}, { take: 200 }),
33
+ ])
34
+
35
+ const totalTagScans = tags.reduce(
36
+ (sum, t) => sum + Number(t.scan_count || 0),
37
+ 0
38
+ )
39
+ const totalCacheHits = caches.reduce(
40
+ (sum, c) => sum + Number(c.hit_count || 0),
41
+ 0
42
+ )
43
+
44
+ return {
45
+ total_barcode_products: products.length,
46
+ total_barcode_tags: tags.length,
47
+ total_tag_scans: totalTagScans,
48
+ total_cached_lookups: caches.length,
49
+ total_cache_hits: totalCacheHits,
50
+ total_count_sessions: sessions.length,
51
+ active_providers: ctx.registry.getProviderNames(),
52
+ }
53
+ }
@@ -0,0 +1,217 @@
1
+ import { MedusaError } from "@medusajs/framework/utils"
2
+
3
+ import type { BarcodeOpsContext } from "./context"
4
+ import { parseBarcode } from "../utils/barcode-parser"
5
+
6
+ /**
7
+ * Creates a new stock-take inventory count session (`BarcodeCountSession`).
8
+ */
9
+ export async function createStockCountSession(
10
+ ctx: BarcodeOpsContext,
11
+ input: {
12
+ name: string
13
+ location_id?: string | null
14
+ notes?: string | null
15
+ created_by?: string | null
16
+ expected_items?: Array<{
17
+ barcode: string
18
+ variant_id?: string | null
19
+ product_id?: string | null
20
+ title: string
21
+ variant_title?: string | null
22
+ sku?: string | null
23
+ expected_quantity: number
24
+ }>
25
+ }
26
+ ) {
27
+ if (!input.name || !input.name.trim()) {
28
+ throw new MedusaError(
29
+ MedusaError.Types.INVALID_DATA,
30
+ "Session name is required"
31
+ )
32
+ }
33
+
34
+ const expectedItems = input.expected_items || []
35
+ const totalExpected = expectedItems.reduce(
36
+ (sum, item) => sum + Math.max(0, Number(item.expected_quantity || 0)),
37
+ 0
38
+ )
39
+
40
+ const session = await ctx.svc.createBarcodeCountSessions({
41
+ name: input.name.trim(),
42
+ location_id: input.location_id ?? null,
43
+ status: "in_progress",
44
+ notes: input.notes ?? null,
45
+ total_expected: totalExpected,
46
+ total_counted: 0,
47
+ total_variance: -totalExpected,
48
+ total_scans: 0,
49
+ created_by: input.created_by ?? null,
50
+ })
51
+
52
+ const createdItems: Array<
53
+ Awaited<ReturnType<typeof ctx.svc.createBarcodeCountItems>>[number]
54
+ > = []
55
+ for (const item of expectedItems) {
56
+ const parsed = parseBarcode(item.barcode)
57
+ const expectedQty = Math.max(0, Number(item.expected_quantity || 0))
58
+ const created = await ctx.svc.createBarcodeCountItems({
59
+ session_id: session.id,
60
+ barcode: parsed.normalized,
61
+ variant_id: item.variant_id ?? null,
62
+ product_id: item.product_id ?? null,
63
+ title: item.title,
64
+ variant_title: item.variant_title ?? null,
65
+ sku: item.sku ?? null,
66
+ expected_quantity: expectedQty,
67
+ counted_quantity: 0,
68
+ variance: -expectedQty,
69
+ })
70
+ createdItems.push(created)
71
+ }
72
+
73
+ return {
74
+ session,
75
+ items: createdItems,
76
+ }
77
+ }
78
+
79
+ /**
80
+ * Records a barcode scan inside a `BarcodeCountSession` and recalculates session variance totals.
81
+ */
82
+ export async function recordCountSessionScan(
83
+ ctx: BarcodeOpsContext,
84
+ input: {
85
+ session_id: string
86
+ barcode: string
87
+ delta?: number
88
+ set_quantity?: number
89
+ variant_id?: string | null
90
+ product_id?: string | null
91
+ title?: string
92
+ variant_title?: string | null
93
+ sku?: string | null
94
+ expected_quantity?: number
95
+ }
96
+ ) {
97
+ const sessions = await ctx.svc.listBarcodeCountSessions(
98
+ { id: input.session_id },
99
+ { take: 1 }
100
+ )
101
+ const session = sessions[0]
102
+ if (!session) {
103
+ throw new MedusaError(
104
+ MedusaError.Types.NOT_FOUND,
105
+ `Count session ${input.session_id} not found`
106
+ )
107
+ }
108
+ if (session.status !== "in_progress") {
109
+ throw new MedusaError(
110
+ MedusaError.Types.INVALID_DATA,
111
+ `Count session ${input.session_id} is already ${session.status}`
112
+ )
113
+ }
114
+
115
+ const parsed = parseBarcode(input.barcode)
116
+ const existingItems = await ctx.svc.listBarcodeCountItems(
117
+ { session_id: input.session_id, barcode: parsed.normalized },
118
+ { take: 1 }
119
+ )
120
+
121
+ let item = existingItems[0]
122
+ if (item) {
123
+ const nextCounted =
124
+ typeof input.set_quantity === "number"
125
+ ? Math.max(0, input.set_quantity)
126
+ : Math.max(0, Number(item.counted_quantity || 0) + (input.delta ?? 1))
127
+ const expected = Number(item.expected_quantity || 0)
128
+ item = await ctx.svc.updateBarcodeCountItems({
129
+ id: item.id,
130
+ counted_quantity: nextCounted,
131
+ variance: nextCounted - expected,
132
+ last_scanned_at: new Date(),
133
+ })
134
+ } else {
135
+ const expected = Math.max(0, Number(input.expected_quantity || 0))
136
+ const counted =
137
+ typeof input.set_quantity === "number"
138
+ ? Math.max(0, input.set_quantity)
139
+ : Math.max(0, input.delta ?? 1)
140
+ item = await ctx.svc.createBarcodeCountItems({
141
+ session_id: input.session_id,
142
+ barcode: parsed.normalized,
143
+ variant_id: input.variant_id ?? null,
144
+ product_id: input.product_id ?? null,
145
+ title: input.title || `Scanned Item (${parsed.normalized})`,
146
+ variant_title: input.variant_title ?? null,
147
+ sku: input.sku ?? null,
148
+ expected_quantity: expected,
149
+ counted_quantity: counted,
150
+ variance: counted - expected,
151
+ last_scanned_at: new Date(),
152
+ })
153
+ }
154
+
155
+ const allItems = await ctx.svc.listBarcodeCountItems(
156
+ { session_id: input.session_id },
157
+ { take: 1000 }
158
+ )
159
+ const totalExpected = allItems.reduce(
160
+ (sum, row) => sum + Number(row.expected_quantity || 0),
161
+ 0
162
+ )
163
+ const totalCounted = allItems.reduce(
164
+ (sum, row) => sum + Number(row.counted_quantity || 0),
165
+ 0
166
+ )
167
+ const totalVariance = totalCounted - totalExpected
168
+ const updatedSession = await ctx.svc.updateBarcodeCountSessions({
169
+ id: session.id,
170
+ total_expected: totalExpected,
171
+ total_counted: totalCounted,
172
+ total_variance: totalVariance,
173
+ total_scans: Number(session.total_scans || 0) + 1,
174
+ })
175
+
176
+ return {
177
+ session: updatedSession,
178
+ item,
179
+ items: allItems,
180
+ }
181
+ }
182
+
183
+ /**
184
+ * Marks a count session as completed.
185
+ */
186
+ export async function completeCountSession(
187
+ ctx: BarcodeOpsContext,
188
+ sessionId: string
189
+ ) {
190
+ const sessions = await ctx.svc.listBarcodeCountSessions(
191
+ { id: sessionId },
192
+ { take: 1 }
193
+ )
194
+ const session = sessions[0]
195
+ if (!session) {
196
+ throw new MedusaError(
197
+ MedusaError.Types.NOT_FOUND,
198
+ `Count session ${sessionId} not found`
199
+ )
200
+ }
201
+
202
+ const items = await ctx.svc.listBarcodeCountItems(
203
+ { session_id: sessionId },
204
+ { take: 1000 }
205
+ )
206
+
207
+ const updated = await ctx.svc.updateBarcodeCountSessions({
208
+ id: sessionId,
209
+ status: "completed",
210
+ completed_at: new Date(),
211
+ })
212
+
213
+ return {
214
+ session: updated,
215
+ items,
216
+ }
217
+ }