@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,91 @@
1
+ import {
2
+ defineMiddlewares,
3
+ validateAndTransformBody,
4
+ } from "@medusajs/framework/http"
5
+ import {
6
+ ApplyCountSessionBodySchema,
7
+ BatchBarcodeImportBodySchema,
8
+ BulkGenerateBarcodesBodySchema,
9
+ CreateBarcodeTagBodySchema,
10
+ CreateCountSessionBodySchema,
11
+ CreateFromBarcodeBodySchema,
12
+ CreateLabelTemplateBodySchema,
13
+ LookupBarcodeBodySchema,
14
+ PrintLabelsBodySchema,
15
+ QuickScanAdjustBodySchema,
16
+ RecordCountScanBodySchema,
17
+ UpdateBarcodeTagBodySchema,
18
+ VerifyStoreBarcodeBodySchema,
19
+ } from "./validators"
20
+
21
+ export * from "./validators"
22
+
23
+ export default defineMiddlewares({
24
+ routes: [
25
+ {
26
+ matcher: "/admin/barcodes/lookup",
27
+ method: ["POST"],
28
+ middlewares: [validateAndTransformBody(LookupBarcodeBodySchema)],
29
+ },
30
+ {
31
+ matcher: "/admin/barcodes/create-from-barcode",
32
+ method: ["POST"],
33
+ middlewares: [validateAndTransformBody(CreateFromBarcodeBodySchema)],
34
+ },
35
+ {
36
+ matcher: "/admin/barcodes/batch",
37
+ method: ["POST"],
38
+ middlewares: [validateAndTransformBody(BatchBarcodeImportBodySchema)],
39
+ },
40
+ {
41
+ matcher: "/admin/barcodes/bulk-generate",
42
+ method: ["POST"],
43
+ middlewares: [validateAndTransformBody(BulkGenerateBarcodesBodySchema)],
44
+ },
45
+ {
46
+ matcher: "/admin/barcodes/scan",
47
+ method: ["POST"],
48
+ middlewares: [validateAndTransformBody(QuickScanAdjustBodySchema)],
49
+ },
50
+ {
51
+ matcher: "/admin/barcodes/tags",
52
+ method: ["POST"],
53
+ middlewares: [validateAndTransformBody(CreateBarcodeTagBodySchema)],
54
+ },
55
+ {
56
+ matcher: "/admin/barcodes/tags/:id",
57
+ method: ["PATCH"],
58
+ middlewares: [validateAndTransformBody(UpdateBarcodeTagBodySchema)],
59
+ },
60
+ {
61
+ matcher: "/admin/barcodes/templates",
62
+ method: ["POST"],
63
+ middlewares: [validateAndTransformBody(CreateLabelTemplateBodySchema)],
64
+ },
65
+ {
66
+ matcher: "/admin/barcodes/print",
67
+ method: ["POST"],
68
+ middlewares: [validateAndTransformBody(PrintLabelsBodySchema)],
69
+ },
70
+ {
71
+ matcher: "/admin/barcodes/count-sessions",
72
+ method: ["POST"],
73
+ middlewares: [validateAndTransformBody(CreateCountSessionBodySchema)],
74
+ },
75
+ {
76
+ matcher: "/admin/barcodes/count-sessions/:id/scan",
77
+ method: ["POST"],
78
+ middlewares: [validateAndTransformBody(RecordCountScanBodySchema)],
79
+ },
80
+ {
81
+ matcher: "/admin/barcodes/count-sessions/:id/apply",
82
+ method: ["POST"],
83
+ middlewares: [validateAndTransformBody(ApplyCountSessionBodySchema)],
84
+ },
85
+ {
86
+ matcher: "/store/barcodes/:code/verify",
87
+ method: ["POST"],
88
+ middlewares: [validateAndTransformBody(VerifyStoreBarcodeBodySchema)],
89
+ },
90
+ ],
91
+ })
@@ -0,0 +1,43 @@
1
+ import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
2
+
3
+ import type { BarcodeModuleService } from "../../../../modules/barcode/service"
4
+ import {
5
+ BARCODE_MODULE,
6
+ type BarcodeSymbology,
7
+ } from "../../../../modules/barcode/types"
8
+
9
+ export async function GET(req: MedusaRequest, res: MedusaResponse) {
10
+ const barcodeService = req.scope.resolve(
11
+ BARCODE_MODULE
12
+ ) as BarcodeModuleService
13
+ const code = req.params.code || ""
14
+ const formatParam =
15
+ typeof req.query.format === "string" ? req.query.format : "json"
16
+ const symbologyParam =
17
+ typeof req.query.symbology === "string"
18
+ ? (req.query.symbology as BarcodeSymbology)
19
+ : undefined
20
+
21
+ const resolved = await barcodeService.resolveBarcodeScan(code, {
22
+ scope: req.scope,
23
+ hydrateVariant: true,
24
+ })
25
+
26
+ if (formatParam === "svg") {
27
+ const svg =
28
+ resolved.tag?.svg_markup ||
29
+ (await barcodeService.renderSvg({
30
+ code,
31
+ symbology:
32
+ symbologyParam ||
33
+ (resolved.parsed.type === "unknown"
34
+ ? "code128"
35
+ : resolved.parsed.type),
36
+ }))
37
+ res.setHeader("Content-Type", "image/svg+xml; charset=utf-8")
38
+ res.status(200).send(svg)
39
+ return
40
+ }
41
+
42
+ res.json(resolved)
43
+ }
@@ -0,0 +1,35 @@
1
+ import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
2
+
3
+ import type { BarcodeModuleService } from "../../../../../modules/barcode/service"
4
+ import { BARCODE_MODULE } from "../../../../../modules/barcode/types"
5
+ import type { VerifyStoreBarcodeBody } from "../../../../validators"
6
+
7
+ export async function GET(req: MedusaRequest, res: MedusaResponse) {
8
+ const barcodeService = req.scope.resolve(
9
+ BARCODE_MODULE
10
+ ) as BarcodeModuleService
11
+ const code = req.params.code || ""
12
+ const sig =
13
+ typeof req.query.sig === "string"
14
+ ? req.query.sig
15
+ : typeof req.query.signature === "string"
16
+ ? req.query.signature
17
+ : ""
18
+
19
+ const result = await barcodeService.verifyAuthenticityToken(code, sig)
20
+ res.status(result.valid ? 200 : 400).json(result)
21
+ }
22
+
23
+ export async function POST(req: MedusaRequest, res: MedusaResponse) {
24
+ const barcodeService = req.scope.resolve(
25
+ BARCODE_MODULE
26
+ ) as BarcodeModuleService
27
+ const code = req.params.code || ""
28
+ const body = req.validatedBody as VerifyStoreBarcodeBody
29
+
30
+ const result = await barcodeService.verifyAuthenticityToken(
31
+ code,
32
+ body.signature
33
+ )
34
+ res.status(result.valid ? 200 : 400).json(result)
35
+ }
@@ -0,0 +1,5 @@
1
+ import { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
2
+
3
+ export async function GET(req: MedusaRequest, res: MedusaResponse) {
4
+ res.sendStatus(200)
5
+ }
@@ -0,0 +1,36 @@
1
+ import type { MedusaRequest, MedusaResponse } from "@medusajs/framework/http"
2
+
3
+ import type { BarcodeModuleService } from "../../../../../modules/barcode/service"
4
+ import { BARCODE_MODULE } from "../../../../../modules/barcode/types"
5
+
6
+ export async function GET(req: MedusaRequest, res: MedusaResponse) {
7
+ const barcodeService = req.scope.resolve(
8
+ BARCODE_MODULE
9
+ ) as BarcodeModuleService
10
+ const code = req.params.code || ""
11
+
12
+ const resolved = await barcodeService.resolveBarcodeScan(code, {
13
+ scope: req.scope,
14
+ hydrateVariant: true,
15
+ })
16
+
17
+ if (!resolved.found) {
18
+ res.status(404).json({
19
+ message: `No variant or product found for barcode ${code}`,
20
+ code: resolved.code,
21
+ })
22
+ return
23
+ }
24
+
25
+ res.json({
26
+ code: resolved.code,
27
+ parsed: resolved.parsed,
28
+ found: resolved.found,
29
+ variant_id: resolved.variant_id,
30
+ product_id: resolved.product_id,
31
+ variant: resolved.variant,
32
+ product: resolved.product,
33
+ tag: resolved.tag,
34
+ barcode_product: resolved.barcode_product,
35
+ })
36
+ }
@@ -0,0 +1,217 @@
1
+ import { z } from "@medusajs/framework/zod"
2
+
3
+ export const BarcodeSymbologySchema = z.enum([
4
+ "ean13",
5
+ "ean8",
6
+ "upca",
7
+ "upce",
8
+ "gtin14",
9
+ "isbn13",
10
+ "code128",
11
+ "gs1-128",
12
+ "code39",
13
+ "qr",
14
+ "datamatrix",
15
+ "unknown",
16
+ ])
17
+
18
+ export const BarcodeScanActionSchema = z.enum([
19
+ "view",
20
+ "add_to_cart",
21
+ "verify",
22
+ "gs1_digital_link",
23
+ "custom",
24
+ ])
25
+
26
+ export const EnrichmentStrategySchema = z.enum(["first-hit", "deep-merge"])
27
+
28
+ export const LookupBarcodeBodySchema = z.object({
29
+ barcode: z.string().min(1).max(128),
30
+ skipCache: z.boolean().optional(),
31
+ strategy: EnrichmentStrategySchema.optional(),
32
+ providers: z.array(z.string().min(1).max(64)).max(10).optional(),
33
+ })
34
+
35
+ export const VariantPriceInputSchema = z.object({
36
+ amount: z.number().min(0),
37
+ currency_code: z.string().min(1).max(8),
38
+ })
39
+
40
+ export const CreateFromBarcodeBodySchema = z.object({
41
+ barcode: z.string().min(1).max(128),
42
+ status: z.enum(["draft", "published"]).optional(),
43
+ publishImmediately: z.boolean().optional(),
44
+ strategy: EnrichmentStrategySchema.optional(),
45
+ skipCache: z.boolean().optional(),
46
+ skipExistingCheck: z.boolean().optional(),
47
+ downloadImages: z.boolean().optional(),
48
+ overrideTitle: z.string().max(256).optional(),
49
+ overrideDescription: z.string().max(4000).optional(),
50
+ overridePrice: z.number().min(0).optional(),
51
+ currencyCode: z.string().max(8).optional(),
52
+ skuPrefix: z.string().max(32).optional(),
53
+ prices: z.array(VariantPriceInputSchema).max(50).optional(),
54
+ salesChannelIds: z.array(z.string().min(1).max(128)).max(50).optional(),
55
+ categoryIds: z.array(z.string().min(1).max(128)).max(50).optional(),
56
+ collectionId: z.string().max(128).nullable().optional(),
57
+ })
58
+
59
+ export const BatchBarcodeImportBodySchema = z.object({
60
+ barcodes: z.array(z.string().min(1).max(128)).min(1).max(100),
61
+ status: z.enum(["draft", "published"]).optional(),
62
+ publishImmediately: z.boolean().optional(),
63
+ strategy: EnrichmentStrategySchema.optional(),
64
+ createMissingAsDraft: z.boolean().optional(),
65
+ prices: z.array(VariantPriceInputSchema).max(50).optional(),
66
+ salesChannelIds: z.array(z.string().min(1).max(128)).max(50).optional(),
67
+ categoryIds: z.array(z.string().min(1).max(128)).max(50).optional(),
68
+ collectionId: z.string().max(128).nullable().optional(),
69
+ })
70
+
71
+ export const BulkGenerateBarcodesBodySchema = z.object({
72
+ variant_ids: z.array(z.string().min(1).max(128)).max(250).optional(),
73
+ product_ids: z.array(z.string().min(1).max(128)).max(250).optional(),
74
+ prefix: z
75
+ .string()
76
+ .regex(/^2\d{2}$/)
77
+ .optional(),
78
+ overwrite: z.boolean().optional(),
79
+ })
80
+
81
+ export const QuickScanAdjustBodySchema = z.object({
82
+ barcode: z.string().min(1).max(128),
83
+ action: z.enum(["lookup", "increment", "decrement", "set"]).optional(),
84
+ quantity: z.number().int().optional(),
85
+ location_id: z.string().max(128).nullable().optional(),
86
+ })
87
+
88
+ export const CreateBarcodeTagBodySchema = z.object({
89
+ code: z.string().max(128).optional(),
90
+ target_type: z.enum(["product", "variant", "order", "custom"]).optional(),
91
+ target_id: z.string().min(1).max(256),
92
+ product_id: z.string().max(256).nullable().optional(),
93
+ variant_id: z.string().max(256).nullable().optional(),
94
+ label: z.string().max(256).nullable().optional(),
95
+ symbology: BarcodeSymbologySchema.optional(),
96
+ scan_action: BarcodeScanActionSchema.optional(),
97
+ gs1_gtin: z.string().max(64).nullable().optional(),
98
+ batch_lot: z.string().max(64).nullable().optional(),
99
+ serial_number: z.string().max(128).nullable().optional(),
100
+ target_url: z.string().max(1024).nullable().optional(),
101
+ upload_svg_to_file_module: z.boolean().optional(),
102
+ metadata: z.record(z.string(), z.unknown()).nullable().optional(),
103
+ })
104
+
105
+ export const UpdateBarcodeTagBodySchema = CreateBarcodeTagBodySchema.partial()
106
+
107
+ export const CreateLabelTemplateBodySchema = z.object({
108
+ name: z.string().min(1).max(160),
109
+ preset_id: z.string().max(64).optional(),
110
+ layout_type: z.enum(["thermal_roll", "a4_sheet"]).optional(),
111
+ width_mm: z.number().min(10).max(300),
112
+ height_mm: z.number().min(10).max(300),
113
+ columns: z.number().int().min(1).max(10).optional(),
114
+ rows: z.number().int().min(1).max(30).optional(),
115
+ margin_top_mm: z.number().min(0).max(50).optional(),
116
+ margin_left_mm: z.number().min(0).max(50).optional(),
117
+ gap_x_mm: z.number().min(0).max(30).optional(),
118
+ gap_y_mm: z.number().min(0).max(30).optional(),
119
+ symbology: BarcodeSymbologySchema.optional(),
120
+ show_title: z.boolean().optional(),
121
+ show_variant_title: z.boolean().optional(),
122
+ show_sku: z.boolean().optional(),
123
+ show_price: z.boolean().optional(),
124
+ show_compare_at_price: z.boolean().optional(),
125
+ show_brand: z.boolean().optional(),
126
+ show_qr: z.boolean().optional(),
127
+ custom_header: z.string().max(120).nullable().optional(),
128
+ custom_footer: z.string().max(120).nullable().optional(),
129
+ dpi: z.enum(["203", "300"]).or(z.number().int()).optional(),
130
+ is_default: z.boolean().optional(),
131
+ })
132
+
133
+ export const PrintLabelsBodySchema = z.object({
134
+ template_id: z.string().max(128).optional(),
135
+ items: z
136
+ .array(
137
+ z.object({
138
+ barcode: z.string().min(1).max(128),
139
+ symbology: BarcodeSymbologySchema.optional(),
140
+ title: z.string().min(1).max(256),
141
+ variant_title: z.string().max(256).nullable().optional(),
142
+ sku: z.string().max(128).nullable().optional(),
143
+ brand: z.string().max(128).nullable().optional(),
144
+ price: z.number().nullable().optional(),
145
+ compare_at_price: z.number().nullable().optional(),
146
+ currency_code: z.string().max(8).optional(),
147
+ qr_url: z.string().max(1024).nullable().optional(),
148
+ quantity: z.number().int().min(1).max(200).optional(),
149
+ })
150
+ )
151
+ .min(1)
152
+ .max(200),
153
+ })
154
+
155
+ export const CreateCountSessionBodySchema = z.object({
156
+ name: z.string().min(1).max(180),
157
+ location_id: z.string().max(128).nullable().optional(),
158
+ notes: z.string().max(1000).nullable().optional(),
159
+ expected_items: z
160
+ .array(
161
+ z.object({
162
+ barcode: z.string().min(1).max(128),
163
+ variant_id: z.string().max(128).nullable().optional(),
164
+ product_id: z.string().max(128).nullable().optional(),
165
+ title: z.string().min(1).max(256),
166
+ variant_title: z.string().max(256).nullable().optional(),
167
+ sku: z.string().max(128).nullable().optional(),
168
+ expected_quantity: z.number().int().min(0),
169
+ })
170
+ )
171
+ .max(500)
172
+ .optional(),
173
+ })
174
+
175
+ export const RecordCountScanBodySchema = z.object({
176
+ barcode: z.string().min(1).max(128),
177
+ delta: z.number().int().optional(),
178
+ set_quantity: z.number().int().min(0).optional(),
179
+ variant_id: z.string().max(128).nullable().optional(),
180
+ product_id: z.string().max(128).nullable().optional(),
181
+ title: z.string().max(256).optional(),
182
+ variant_title: z.string().max(256).nullable().optional(),
183
+ sku: z.string().max(128).nullable().optional(),
184
+ expected_quantity: z.number().int().min(0).optional(),
185
+ })
186
+
187
+ export const ApplyCountSessionBodySchema = z.object({
188
+ location_id: z.string().max(128).nullable().optional(),
189
+ })
190
+
191
+ export const VerifyStoreBarcodeBodySchema = z.object({
192
+ signature: z.string().min(1).max(256),
193
+ })
194
+
195
+ export type LookupBarcodeBody = z.infer<typeof LookupBarcodeBodySchema>
196
+ export type CreateFromBarcodeBody = z.infer<typeof CreateFromBarcodeBodySchema>
197
+ export type BatchBarcodeImportBody = z.infer<
198
+ typeof BatchBarcodeImportBodySchema
199
+ >
200
+ export type BulkGenerateBarcodesBody = z.infer<
201
+ typeof BulkGenerateBarcodesBodySchema
202
+ >
203
+ export type QuickScanAdjustBody = z.infer<typeof QuickScanAdjustBodySchema>
204
+ export type CreateBarcodeTagBody = z.infer<typeof CreateBarcodeTagBodySchema>
205
+ export type UpdateBarcodeTagBody = z.infer<typeof UpdateBarcodeTagBodySchema>
206
+ export type CreateLabelTemplateBody = z.infer<
207
+ typeof CreateLabelTemplateBodySchema
208
+ >
209
+ export type PrintLabelsBody = z.infer<typeof PrintLabelsBodySchema>
210
+ export type CreateCountSessionBody = z.infer<
211
+ typeof CreateCountSessionBodySchema
212
+ >
213
+ export type RecordCountScanBody = z.infer<typeof RecordCountScanBodySchema>
214
+ export type ApplyCountSessionBody = z.infer<typeof ApplyCountSessionBodySchema>
215
+ export type VerifyStoreBarcodeBody = z.infer<
216
+ typeof VerifyStoreBarcodeBodySchema
217
+ >
@@ -0,0 +1,270 @@
1
+ import { useCallback, useEffect, useRef, useState } from "react"
2
+
3
+ import { createBarcodeSdk, type BarcodeSdkOptions } from "../sdk"
4
+
5
+ export interface UseHidBarcodeScannerOptions {
6
+ enabled?: boolean
7
+ minLength?: number
8
+ maxInterKeyDelayMs?: number
9
+ onScan: (barcode: string) => void
10
+ }
11
+
12
+ /**
13
+ * Listens for high-speed USB / Bluetooth HID keyboard-wedge barcode scanners.
14
+ * Hardware scanners emit keystrokes at < 35ms intervals followed by Enter.
15
+ */
16
+ export function useHidBarcodeScanner({
17
+ enabled = true,
18
+ minLength = 6,
19
+ maxInterKeyDelayMs = 45,
20
+ onScan,
21
+ }: UseHidBarcodeScannerOptions) {
22
+ const bufferRef = useRef<string>("")
23
+ const lastKeyTimeRef = useRef<number>(0)
24
+ const [lastScanned, setLastScanned] = useState<string | null>(null)
25
+
26
+ useEffect(() => {
27
+ if (!enabled || typeof window === "undefined") {
28
+ return
29
+ }
30
+
31
+ const handleKeyDown = (event: KeyboardEvent) => {
32
+ const now = Date.now()
33
+ const elapsed = now - lastKeyTimeRef.current
34
+
35
+ if (event.key === "Enter" || event.key === "Tab") {
36
+ const candidate = bufferRef.current.trim()
37
+ bufferRef.current = ""
38
+ if (
39
+ candidate.length >= minLength &&
40
+ elapsed <= maxInterKeyDelayMs * 3
41
+ ) {
42
+ event.preventDefault()
43
+ setLastScanned(candidate)
44
+ onScan(candidate)
45
+ }
46
+ return
47
+ }
48
+
49
+ if (
50
+ event.key.length === 1 &&
51
+ !event.ctrlKey &&
52
+ !event.metaKey &&
53
+ !event.altKey
54
+ ) {
55
+ if (elapsed > maxInterKeyDelayMs) {
56
+ bufferRef.current = event.key
57
+ } else {
58
+ bufferRef.current += event.key
59
+ }
60
+ lastKeyTimeRef.current = now
61
+ }
62
+ }
63
+
64
+ window.addEventListener("keydown", handleKeyDown)
65
+ return () => {
66
+ window.removeEventListener("keydown", handleKeyDown)
67
+ }
68
+ }, [enabled, minLength, maxInterKeyDelayMs, onScan])
69
+
70
+ return {
71
+ lastScanned,
72
+ clearLastScanned: () => setLastScanned(null),
73
+ }
74
+ }
75
+
76
+ export interface UseCameraBarcodeScannerOptions {
77
+ onScan: (barcode: string) => void
78
+ facingMode?: "environment" | "user"
79
+ }
80
+
81
+ interface NativeBarcodeDetector {
82
+ detect: (
83
+ source: HTMLVideoElement
84
+ ) => Promise<Array<{ rawValue?: string; format?: string }>>
85
+ }
86
+
87
+ /**
88
+ * WebRTC camera barcode & QR scanner hook using native BarcodeDetector when available.
89
+ */
90
+ export function useCameraBarcodeScanner({
91
+ onScan,
92
+ facingMode = "environment",
93
+ }: UseCameraBarcodeScannerOptions) {
94
+ const videoRef = useRef<HTMLVideoElement | null>(null)
95
+ const streamRef = useRef<MediaStream | null>(null)
96
+ const rafRef = useRef<number | null>(null)
97
+ const [isScanning, setIsScanning] = useState(false)
98
+ const [cameraError, setCameraError] = useState<string | null>(null)
99
+
100
+ const stopCamera = useCallback(() => {
101
+ if (rafRef.current !== null && typeof cancelAnimationFrame === "function") {
102
+ cancelAnimationFrame(rafRef.current)
103
+ rafRef.current = null
104
+ }
105
+ if (streamRef.current) {
106
+ for (const track of streamRef.current.getTracks()) {
107
+ track.stop()
108
+ }
109
+ streamRef.current = null
110
+ }
111
+ setIsScanning(false)
112
+ }, [])
113
+
114
+ const startCamera = useCallback(async () => {
115
+ setCameraError(null)
116
+ if (
117
+ typeof navigator === "undefined" ||
118
+ !navigator.mediaDevices ||
119
+ typeof navigator.mediaDevices.getUserMedia !== "function"
120
+ ) {
121
+ setCameraError("Camera API is not available in this browser")
122
+ return
123
+ }
124
+
125
+ try {
126
+ const stream = await navigator.mediaDevices.getUserMedia({
127
+ video: { facingMode },
128
+ audio: false,
129
+ })
130
+ streamRef.current = stream
131
+ if (videoRef.current) {
132
+ videoRef.current.srcObject = stream
133
+ await videoRef.current.play().catch(() => undefined)
134
+ }
135
+ setIsScanning(true)
136
+
137
+ const DetectorCtor = (
138
+ globalThis as unknown as {
139
+ BarcodeDetector?: new (opts?: {
140
+ formats?: string[]
141
+ }) => NativeBarcodeDetector
142
+ }
143
+ ).BarcodeDetector
144
+
145
+ if (DetectorCtor) {
146
+ const detector = new DetectorCtor({
147
+ formats: [
148
+ "ean_13",
149
+ "ean_8",
150
+ "upc_a",
151
+ "upc_e",
152
+ "code_128",
153
+ "code_39",
154
+ "qr_code",
155
+ "data_matrix",
156
+ ],
157
+ })
158
+
159
+ const tick = async () => {
160
+ if (!videoRef.current || !streamRef.current) return
161
+ try {
162
+ const results = await detector.detect(videoRef.current)
163
+ const first = results?.[0]?.rawValue
164
+ if (first) {
165
+ onScan(first)
166
+ stopCamera()
167
+ return
168
+ }
169
+ } catch {
170
+ // continue scanning frame
171
+ }
172
+ rafRef.current = requestAnimationFrame(() => {
173
+ void tick()
174
+ })
175
+ }
176
+
177
+ rafRef.current = requestAnimationFrame(() => {
178
+ void tick()
179
+ })
180
+ }
181
+ } catch (err) {
182
+ setCameraError(
183
+ err instanceof Error ? err.message : "Unable to access camera"
184
+ )
185
+ setIsScanning(false)
186
+ }
187
+ }, [facingMode, onScan, stopCamera])
188
+
189
+ useEffect(() => {
190
+ return () => {
191
+ stopCamera()
192
+ }
193
+ }, [stopCamera])
194
+
195
+ return {
196
+ videoRef,
197
+ isScanning,
198
+ cameraError,
199
+ startCamera,
200
+ stopCamera,
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Storefront hook for resolving scanned barcodes/QR codes and verifying anti-counterfeit HMAC signatures.
206
+ */
207
+ export function useStoreBarcodeResolver(sdkOptions?: BarcodeSdkOptions) {
208
+ const [loading, setLoading] = useState(false)
209
+ const [error, setError] = useState<string | null>(null)
210
+ const [scanResult, setScanResult] = useState<Record<string, unknown> | null>(
211
+ null
212
+ )
213
+ const [verificationResult, setVerificationResult] = useState<{
214
+ valid: boolean
215
+ code: string
216
+ reason: string
217
+ tag: Record<string, unknown> | null
218
+ } | null>(null)
219
+
220
+ const resolveScan = useCallback(
221
+ async (code: string) => {
222
+ setLoading(true)
223
+ setError(null)
224
+ try {
225
+ const sdk = createBarcodeSdk(sdkOptions)
226
+ const res = await sdk.store.resolveScan(code)
227
+ setScanResult(res)
228
+ return res
229
+ } catch (err) {
230
+ const msg =
231
+ err instanceof Error ? err.message : "Failed to resolve scan"
232
+ setError(msg)
233
+ return null
234
+ } finally {
235
+ setLoading(false)
236
+ }
237
+ },
238
+ [sdkOptions]
239
+ )
240
+
241
+ const verifyAuthenticity = useCallback(
242
+ async (code: string, signature: string) => {
243
+ setLoading(true)
244
+ setError(null)
245
+ try {
246
+ const sdk = createBarcodeSdk(sdkOptions)
247
+ const res = await sdk.store.verifyAuthenticity(code, signature)
248
+ setVerificationResult(res)
249
+ return res
250
+ } catch (err) {
251
+ const msg =
252
+ err instanceof Error ? err.message : "Authenticity check failed"
253
+ setError(msg)
254
+ return null
255
+ } finally {
256
+ setLoading(false)
257
+ }
258
+ },
259
+ [sdkOptions]
260
+ )
261
+
262
+ return {
263
+ loading,
264
+ error,
265
+ scanResult,
266
+ verificationResult,
267
+ resolveScan,
268
+ verifyAuthenticity,
269
+ }
270
+ }
package/src/index.ts ADDED
@@ -0,0 +1,4 @@
1
+ export * from "./modules/barcode"
2
+ export * from "./workflows"
3
+ export * from "./sdk"
4
+ export { default } from "./modules/barcode"