@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
package/README.md CHANGED
@@ -1,3 +1,845 @@
1
- # Temporary Holding Version
1
+ # medusa-plugin-barcode
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **The Complete GS1 Barcode, Dynamic QR, Thermal/Sheet Label Printing, 10-Provider GTIN Product Lookup & Warehouse Inventory Stock-Take Suite for Medusa v2.**
4
+
5
+ `medusa-plugin-barcode` unifies and supersedes four separate Medusa ecosystem capabilities—external barcode product enrichment (`@bambiste/medusa-barcode`), dynamic QR & barcode generation (`@bambiste/medusa-qr`), POS/warehouse barcode scanning (`medusa-pos-plugin`), and physical stock-take auditing (`inventory-count`)—into one cohesive, zero-external-runtime-dependency **Medusa v2** plugin.
6
+
7
+ ---
8
+
9
+ ## Table of Contents
10
+
11
+ 1. [Ecosystem Comparison & Why `medusa-plugin-barcode`](#1-ecosystem-comparison--why-medusa-plugin-barcode)
12
+ 2. [Architecture Overview](#2-architecture-overview)
13
+ 3. [Core Capabilities (The 4 Pillars)](#3-core-capabilities-the-4-pillars)
14
+ 4. [Installation & Setup](#4-installation--setup)
15
+ 5. [Full Configuration Reference](#5-full-configuration-reference)
16
+ 6. [10-Provider GTIN & ISBN Lookup Chain](#6-10-provider-gtin--isbn-lookup-chain)
17
+ 7. [GS1 Symbologies, Checksum Math & GS1-128 / Digital Link](#7-gs1-symbologies-checksum-math--gs1-128--digital-link)
18
+ 8. [1D/2D SVG Barcode, Dynamic QR & Anti-Counterfeit HMAC Seals](#8-1d2d-svg-barcode-dynamic-qr--anti-counterfeit-hmac-seals)
19
+ 9. [Thermal Roll & A4 Sheet Price/Barcode Label Printing (HTML + Zebra ZPL II)](#9-thermal-roll--a4-sheet-pricebarcode-label-printing-html--zebra-zpl-ii)
20
+ 10. [Warehouse Stock-Take Count Sessions & Quick Scan Adjustments](#10-warehouse-stock-take-count-sessions--quick-scan-adjustments)
21
+ 11. [Medusa v2 Workflows & Rollback Compensation](#11-medusa-v2-workflows--rollback-compensation)
22
+ 12. [Subscribers & Scheduled Jobs](#12-subscribers--scheduled-jobs)
23
+ 13. [Complete REST API Reference (Admin & Storefront)](#13-complete-rest-api-reference-admin--storefront)
24
+ 14. [Typed SDK Client (`medusa-plugin-barcode/sdk`)](#14-typed-sdk-client-medusa-plugin-barcodesdk)
25
+ 15. [React Hooks: USB HID Keyboard-Wedge & WebRTC Camera Scanners (`medusa-plugin-barcode/hooks`)](#15-react-hooks-usb-hid-keyboard-wedge--webrtc-camera-scanners-medusa-plugin-barcodehooks)
26
+ 16. [Storefront UI Kit (`medusa-plugin-barcode/ui`)](#16-storefront-ui-kit-medusa-plugin-barcodeui)
27
+ 17. [Admin Studio (`/app/barcodes`) & Product Detail Widget](#17-admin-studio-appbarcodes--product-detail-widget)
28
+ 18. [Writing a Custom Lookup Provider](#18-writing-a-custom-lookup-provider)
29
+ 19. [Migration Guide from `@bambiste/medusa-barcode` & `@bambiste/medusa-qr`](#19-migration-guide-from-bambistemedusa-barcode--bambistemedusa-qr)
30
+ 20. [Security Architecture](#20-security-architecture)
31
+ 21. [Testing, Linting & Typechecking](#21-testing-linting--typechecking)
32
+
33
+ ---
34
+
35
+ ## 1. Ecosystem Comparison & Why `medusa-plugin-barcode`
36
+
37
+ | Feature / Capability | `@bambiste/medusa-barcode` (`0.0.2`) | `@bambiste/medusa-qr` (`0.0.2`) | `medusa-pos-plugin` (`0.0.36`) | `inventory-count` (`0.0.6`) | `medusa-plugin-barcode` (`1.0.0`) |
38
+ | :--------------------------------- | :-------------------------------------------------------------------------: | :-----------------------------: | :----------------------------: | :-------------------------: | :----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------: |
39
+ | **Medusa Version** | v2 | v2 | v2 | v2 | **v2 (`>=2.4.0`)** |
40
+ | **GS1 Check Digit Validation** | Buggy left-to-right loop (fails on even-length `UPC-A`, `EAN-8`, `GTIN-14`) | N/A | None | None | **Spec-compliant right-to-left `3,1,3,1` GS1 Modulo-10** across all odd & even lengths |
41
+ | **Supported Symbologies** | `EAN-13`, `UPC-A`, `EAN-8`, `ISBN-13` | `QR` only | `barcode` string | `barcode` string | **`EAN-13`, `EAN-8`, `UPC-A`, `UPC-E`, `GTIN-14`, `ISBN-13`, `Code128`, `GS1-128`, `Code39`, `QR`, `DataMatrix`** |
42
+ | **GS1-128 AI & Digital Link** | No | No | No | No | **Full `(01)` GTIN, `(10)` Batch/Lot, `(11)`/`(15)`/`(17)` Dates, `(21)` Serial, `(30)`/`(37)` Qty, `(310n)` Net Weight + GS1 Digital Link URI** |
43
+ | **External GTIN Providers** | 8 providers (`first-hit` only) | None | None | None | **10 providers** (adds free keyless `OpenLibrary` & `Brocade`) + **`first-hit` & `deep-merge`** strategies + smart ISBN routing |
44
+ | **Batch Import Workflow** | Saves dummy `pending_${barcode}` rows without creating products | N/A | N/A | N/A | **Creates real Medusa Products & Variants** with transaction compensation/rollback |
45
+ | **Auto Variant Barcode Gen** | No | No | No | No | **GS1 In-Store (`200`–`299`) deterministic & sequential EAN-13 generator + `product.created` subscriber** |
46
+ | **1D/2D Barcode & QR Rendering** | None | QR PNG/SVG | None | None | **Zero-dependency crisp SVG renderer** for all 1D & 2D symbologies + optional File Module upload |
47
+ | **Anti-Counterfeit Verification** | None | None | None | None | **Constant-time `HMAC-SHA256` signed tags** + `/store/barcodes/[code]/verify` + `<AuthenticityVerifierBadge />` |
48
+ | **Thermal & Sheet Label Printing** | None | None | None | None | **7 built-in presets** (Thermal `50×25`, `57×32`, `100×50`, `30×15` Jewelry + A4 `24`/`40`/`65`-up), multi-currency MRP/Sale formatting, print-ready **HTML+SVG** & raw **Zebra ZPL II (`^XA...^XZ`)** |
49
+ | **Warehouse Stock-Take** | None | None | Basic POS scan | Separate plugin | **Built-in `BarcodeCountSession` & `BarcodeCountItem`** with live scan variance & 1-click Inventory Module reconciliation |
50
+ | **Admin UI & Scanners** | Empty 431-byte stub | Empty 431-byte stub | External POS | Basic | **5-Tab Admin Studio (`/app/barcodes`)**, Product Detail Widget (`product.details.after`), **USB HID Keyboard-Wedge** & **WebRTC Camera** hooks |
51
+
52
+ ---
53
+
54
+ ## 2. Architecture Overview
55
+
56
+ ```mermaid
57
+ graph TD
58
+ subgraph "Admin & Storefront Clients"
59
+ AdminUI["Admin Studio (/app/barcodes) & Product Widget"]
60
+ StoreUI["Storefront UI Kit (BarcodeImage, Scanner, HMAC Verifier)"]
61
+ HID["USB/Bluetooth HID Keyboard-Wedge Hook"]
62
+ Cam["WebRTC Camera BarcodeDetector Hook"]
63
+ SDK["Typed SDK Client (createBarcodeSdk)"]
64
+ end
65
+
66
+ subgraph "Medusa v2 API Layer (src/api)"
67
+ AdminRoutes["15 Admin Endpoints (/admin/barcodes/*)"]
68
+ StoreRoutes["2 Store Endpoints (/store/barcodes/[code]/*)"]
69
+ Validators["Zod Schemas & Middlewares"]
70
+ end
71
+
72
+ subgraph "Medusa v2 Workflows, Subscribers & Jobs"
73
+ WF1["lookupAndCreateProductWorkflow"]
74
+ WF2["batchBarcodeImportWorkflow"]
75
+ WF3["bulkGenerateVariantBarcodesWorkflow"]
76
+ WF4["generateBarcodeTagWorkflow"]
77
+ WF5["scanInventoryCountWorkflow"]
78
+ WF6["applyInventoryCountWorkflow"]
79
+ Sub["product-created Subscriber"]
80
+ Job["purge-expired-barcode-cache Cron Job"]
81
+ end
82
+
83
+ subgraph "Barcode Module (BARCODE_MODULE = 'barcode')"
84
+ Service["BarcodeModuleService (BarcodeService)"]
85
+ Parser["GS1 Checksum, UPC-E, GS1-128 & Digital Link Parser"]
86
+ SVG["1D/2D Pure SVG Renderer"]
87
+ Printer["Thermal & A4 Label Engine (HTML+SVG & Zebra ZPL II)"]
88
+ Sec["HMAC-SHA256 Signer & SSRF Guard"]
89
+ Chain["10-Provider Lookup Chain (first-hit / deep-merge)"]
90
+ Models[("6 DML Models: Product, Cache, Tag, Template, Session, Item")]
91
+ end
92
+
93
+ AdminUI --> SDK
94
+ StoreUI --> SDK
95
+ HID --> AdminUI
96
+ Cam --> StoreUI
97
+ SDK --> AdminRoutes
98
+ SDK --> StoreRoutes
99
+ AdminRoutes --> Validators
100
+ StoreRoutes --> Validators
101
+ AdminRoutes --> WF1 & WF2 & WF3 & WF4 & WF5 & WF6
102
+ AdminRoutes --> Service
103
+ StoreRoutes --> Service
104
+ Sub --> WF3
105
+ Job --> Service
106
+ WF1 & WF2 & WF3 & WF4 & WF5 & WF6 --> Service
107
+ Service --> Parser & SVG & Printer & Sec & Chain & Models
108
+ ```
109
+
110
+ ---
111
+
112
+ ## 3. Core Capabilities (The 4 Pillars)
113
+
114
+ ### Pillar 1: Multi-Provider GTIN/ISBN Lookup & Auto-Catalog Creation
115
+
116
+ - Queries **10 external barcode databases** (`OpenFoodFacts`, `OpenBeautyFacts`, `OpenPetFoodFacts`, `OpenProductsFacts`, `GoogleBooks`, `OpenLibrary`, `Brocade`, `UpcItemDb`, `EanSearch`, `BarcodeLookup`).
117
+ - **Automatic ISBN-13 (`978`/`979`) Priority Routing**: Promotes `GoogleBooks` and `OpenLibrary` to the front of the chain whenever a book barcode is scanned.
118
+ - **Configurable Enrichment Strategy**:
119
+ - `"first-hit"`: Returns immediately on the highest-priority provider match for minimum latency.
120
+ - `"deep-merge"`: Queries all active providers and merges missing fields (backfilling descriptions, ingredients, dimensions, suggested prices, and deduplicating image/category/author arrays).
121
+ - **Optional SSRF-Safe Image Downloading**: Downloads external product images (validating `https:` public hosts and 8 MB size cap) and uploads them directly to Medusa's File Module (`Modules.FILE`).
122
+
123
+ ### Pillar 2: 1D/2D Barcode & Dynamic QR Generation + Anti-Counterfeit Seals
124
+
125
+ - **Pure SVG Rendering Engine**: Generates crisp, dependency-free vector SVGs for `EAN-13`, `ISBN-13`, `UPC-A`, `UPC-E`, `EAN-8`, `GTIN-14`, `Code128`, `GS1-128`, `Code39`, `QR`, and `DataMatrix`.
126
+ - **GS1 In-Store (`200`–`299`) Auto-Assignment**: Automatically generates valid 13-digit EAN-13 barcodes for new or existing Medusa product variants and syncs `barcode`, `ean`, and `upc` fields.
127
+ - **Dynamic `BarcodeTag` Tokens**: Supports `"view"`, `"add_to_cart"`, `"verify"` (anti-counterfeit), and `"gs1_digital_link"` scan actions with live `scan_count` and `last_scanned_at` analytics.
128
+ - **Constant-Time HMAC-SHA256 Verification**: Protects luxury, pharmaceutical, or limited-edition products against counterfeit tags using `crypto.timingSafeEqual`.
129
+
130
+ ### Pillar 3: Thermal Roll & A4 Sheet Price/Barcode Label Printing Engine
131
+
132
+ - **7 Built-In Industry Presets + Custom Templates**:
133
+ - Thermal Rolls: `thermal_50x25` (`50×25mm`), `thermal_57x32` (`57×32mm`), `thermal_100x50` (`100×50mm` Warehouse Carton), `jewelry_30x15` (`30×15mm` Dumbbell Tag).
134
+ - A4 Laser/Inkjet Sheets: `a4_24up_70x37` (`3×8`), `a4_40up_52x30` (`4×10`), `a4_65up_38x21` (`5×13` Mini).
135
+ - **Multi-Currency Pricing**: Formats Sale Price and strike-through Compare-At / MRP Price via `Intl.NumberFormat`.
136
+ - **Dual Output Formats**:
137
+ 1. **Print-Ready HTML+SVG Document**: Exact millimeter `@page` CSS rules for browser/OS printing.
138
+ 2. **Raw Zebra ZPL II (`^XA...^XZ`)**: Native `203 DPI` / `300 DPI` commands (`^BEN`, `^B8N`, `^BCN`, `^BQN`, `^FO`, `^FD`, `^PQ`) for direct thermal printer streaming.
139
+
140
+ ### Pillar 4: Admin Studio, Hardware/Camera Scanners & Warehouse Stock-Take
141
+
142
+ - **Admin Barcode Studio (`/app/barcodes`)**: 5-tab management center in Medusa Admin.
143
+ - **Product Detail Widget (`product.details.after`)**: Generate variant barcodes and print thermal labels directly on any product page.
144
+ - **Hardware & Camera Scanners**: `useHidBarcodeScanner` (USB/Bluetooth keyboard-wedge) and `useCameraBarcodeScanner` (WebRTC `BarcodeDetector`).
145
+ - **Warehouse Stock-Take Count Sessions**: Create `BarcodeCountSession` audits, scan items rapidly (`+1` / `-1` / `set`), inspect expected vs. counted variance, and apply adjustments directly to Medusa's Inventory Module (`Modules.INVENTORY`).
146
+
147
+ ---
148
+
149
+ ## 4. Installation & Setup
150
+
151
+ ### Step 1: Install the Package
152
+
153
+ ```bash
154
+ npm install medusa-plugin-barcode
155
+ # or
156
+ yarn add medusa-plugin-barcode
157
+ # or
158
+ pnpm add medusa-plugin-barcode
159
+ ```
160
+
161
+ ### Step 2: Register in `medusa-config.ts`
162
+
163
+ ```ts
164
+ import { defineConfig } from "@medusajs/framework/utils"
165
+
166
+ export default defineConfig({
167
+ projectConfig: {
168
+ databaseUrl: process.env.DATABASE_URL,
169
+ },
170
+ plugins: [
171
+ {
172
+ resolve: "medusa-plugin-barcode",
173
+ options: {
174
+ cacheEnabled: true,
175
+ cacheTtlSeconds: 86400,
176
+ enrichmentStrategy: "deep-merge",
177
+ autoGenerateVariantBarcode: true,
178
+ internalBarcodePrefix: "200",
179
+ defaultProductStatus: "draft",
180
+ downloadProductImages: false,
181
+ requestTimeoutMs: 5000,
182
+ storefrontBaseUrl:
183
+ process.env.STOREFRONT_URL || "https://store.example.com",
184
+ hmacSecret: process.env.MEDUSA_BARCODE_HMAC_SECRET,
185
+ providers: {
186
+ openFoodFacts: { enabled: true, priority: 10 },
187
+ googleBooks: {
188
+ enabled: true,
189
+ priority: 15,
190
+ apiKey: process.env.GOOGLE_BOOKS_API_KEY,
191
+ },
192
+ openLibrary: { enabled: true, priority: 18 },
193
+ openBeautyFacts: { enabled: true, priority: 20 },
194
+ openPetFoodFacts: { enabled: true, priority: 25 },
195
+ openProductsFacts: { enabled: true, priority: 30 },
196
+ brocade: { enabled: true, priority: 35 },
197
+ upcItemDb: {
198
+ enabled: true,
199
+ priority: 40,
200
+ apiKey: process.env.UPCITEMDB_API_KEY,
201
+ },
202
+ eanSearch: {
203
+ enabled: Boolean(process.env.EAN_SEARCH_TOKEN),
204
+ priority: 60,
205
+ apiKey: process.env.EAN_SEARCH_TOKEN,
206
+ },
207
+ barcodeLookup: {
208
+ enabled: Boolean(process.env.BARCODE_LOOKUP_KEY),
209
+ priority: 70,
210
+ apiKey: process.env.BARCODE_LOOKUP_KEY,
211
+ },
212
+ },
213
+ },
214
+ },
215
+ ],
216
+ })
217
+ ```
218
+
219
+ ### Step 3: Run Database Migrations
220
+
221
+ ```bash
222
+ npx medusa db:migrate
223
+ ```
224
+
225
+ ---
226
+
227
+ ## 5. Full Configuration Reference
228
+
229
+ | Option | Type | Default | Description |
230
+ | :--------------------------- | :---------------------------- | :--------------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------ |
231
+ | `cacheEnabled` | `boolean` | `true` | Caches external provider lookup responses in `barcode_cache`. |
232
+ | `cacheTtlSeconds` | `number` | `86400` (24h) | Time-to-live in seconds for cached lookup rows before expiration. |
233
+ | `enrichmentStrategy` | `"first-hit" \| "deep-merge"` | `"first-hit"` | `"first-hit"` stops at the first matching provider; `"deep-merge"` queries all active providers and merges non-null fields. |
234
+ | `autoGenerateVariantBarcode` | `boolean` | `true` | When `true`, the `product-created` subscriber auto-assigns a valid GS1 in-store EAN-13 barcode to newly created variants missing a barcode. |
235
+ | `internalBarcodePrefix` | `string` | `"200"` | 3-digit GS1 in-store prefix (`"200"`–`"299"`) used when generating internal EAN-13 barcodes. |
236
+ | `defaultProductStatus` | `"draft" \| "published"` | `"draft"` | Default Medusa product status when creating products from barcode lookups. |
237
+ | `downloadProductImages` | `boolean` | `false` | When `true`, downloads external provider images (SSRF-checked) and uploads them to Medusa's File Module (`Modules.FILE`). |
238
+ | `requestTimeoutMs` | `number` | `5000` | Per-provider HTTP timeout in milliseconds. |
239
+ | `storefrontBaseUrl` | `string` | `process.env.STOREFRONT_URL` | Base URL used when building storefront scan URLs and GS1 Digital Link URIs. |
240
+ | `hmacSecret` | `string` | `process.env.MEDUSA_BARCODE_HMAC_SECRET` | Secret key (minimum 16 chars) for signing and verifying anti-counterfeit `BarcodeTag` HMAC-SHA256 seals. |
241
+ | `providers.<name>` | `ProviderConfig` | See below | Per-provider configuration (`enabled`, `priority`, `timeout`, `apiKey`, `baseUrl`). |
242
+
243
+ ---
244
+
245
+ ## 6. 10-Provider GTIN & ISBN Lookup Chain
246
+
247
+ All 10 built-in providers implement `BaseBarcodeProvider` and normalize external responses into `NormalizedBarcodeProduct`:
248
+
249
+ | # | Provider Key | Class Name | Default Priority | API Key Required? | Domain / Specialty |
250
+ | :-: | :------------------ | :-------------------------- | :--------------------------: | :------------------------------: | :--------------------------------------------------------- |
251
+ | 1 | `openfoodfacts` | `OpenFoodFactsProvider` | `10` | No (Free) | Global food, beverages, groceries, nutrition & ingredients |
252
+ | 2 | `googlebooks` | `GoogleBooksProvider` | `15` (Promoted `#1` on ISBN) | Optional | Books, magazines & media (`978`/`979` ISBN-13) |
253
+ | 3 | `openlibrary` | `OpenLibraryProvider` | `18` (Promoted `#2` on ISBN) | No (Free) | Internet Archive OpenLibrary ISBN & book covers |
254
+ | 4 | `openbeautyfacts` | `OpenBeautyFactsProvider` | `20` | No (Free) | Cosmetics, skincare, fragrances & personal care |
255
+ | 5 | `openpetfoodfacts` | `OpenPetFoodFactsProvider` | `25` | No (Free) | Pet food, treats & animal supplies |
256
+ | 6 | `openproductsfacts` | `OpenProductsFactsProvider` | `30` | No (Free) | Consumer electronics, household & general retail |
257
+ | 7 | `brocade` | `BrocadeProvider` | `35` | No (Free) | Open GTIN catalog (`brocade.io`) for general retail items |
258
+ | 8 | `upcitemdb` | `UpcItemDbProvider` | `40` | Optional (Free Trial / Paid Key) | General retail UPC/EAN catalog + lowest recorded price |
259
+ | 9 | `eansearch` | `EanSearchProvider` | `60` | Yes (`apiKey`) | Commercial global EAN/UPC/ISBN lookup (`ean-search.org`) |
260
+ | 10 | `barcodeLookup` | `BarcodeLookupProvider` | `70` | Yes (`apiKey`) | Commercial 700M+ product catalog (`barcodelookup.com`) |
261
+
262
+ ---
263
+
264
+ ## 7. GS1 Symbologies, Checksum Math & GS1-128 / Digital Link
265
+
266
+ ### Right-to-Left GS1 Modulo-10 Check Digit Math
267
+
268
+ Per official GS1 specifications, the Modulo-10 check digit weights digits **`3, 1, 3, 1...` starting from the rightmost data digit** (immediately to the left of the check digit).
269
+
270
+ - Unlike `@bambiste/medusa-barcode` (which weighted left-to-right and failed on 8-, 12-, and 14-digit codes), `medusa-plugin-barcode` validates both odd-length (`EAN-13`, `ISBN-13`) and even-length (`UPC-A`, `UPC-E`, `EAN-8`, `GTIN-14`) barcodes accurately:
271
+
272
+ ```ts
273
+ import {
274
+ computeGs1CheckDigit,
275
+ validateGs1Checksum,
276
+ parseBarcode,
277
+ parseGs1ApplicationIdentifiers,
278
+ buildGs1DigitalLink,
279
+ } from "medusa-plugin-barcode"
280
+
281
+ validateGs1Checksum("3017620422003") // true (EAN-13)
282
+ validateGs1Checksum("012345678905") // true (UPC-A, 12 digits)
283
+ validateGs1Checksum("96385074") // true (EAN-8, 8 digits)
284
+ validateGs1Checksum("10614141000415") // true (GTIN-14, 14 digits)
285
+
286
+ // Parse GS1-128 Application Identifiers:
287
+ const gs1 = parseBarcode(
288
+ "(01)09506000134352(10)LOT2026(17)261231(21)SN9988(3102)001250"
289
+ )
290
+ // gs1.gs1 => {
291
+ // gtin: "09506000134352",
292
+ // batchLot: "LOT2026",
293
+ // expiryDate: "2026-12-31",
294
+ // serialNumber: "SN9988",
295
+ // netWeightKg: 12.5,
296
+ // rawAis: { "01": "09506000134352", "10": "LOT2026", "17": "261231", "21": "SN9988", "3102": "001250" }
297
+ // }
298
+
299
+ // Build a GS1 Digital Link URI:
300
+ const uri = buildGs1DigitalLink({
301
+ baseUrl: "https://id.mybrand.com",
302
+ gtin: "3017620422003",
303
+ batchLot: "LOT-2026",
304
+ serial: "SN-0042",
305
+ expiry: "261231",
306
+ })
307
+ // => "https://id.mybrand.com/01/03017620422003/10/LOT-2026/21/SN-0042?17=261231"
308
+ ```
309
+
310
+ ---
311
+
312
+ ## 8. 1D/2D SVG Barcode, Dynamic QR & Anti-Counterfeit HMAC Seals
313
+
314
+ ### Rendering Standalone SVGs
315
+
316
+ ```ts
317
+ import { renderBarcodeSvg } from "medusa-plugin-barcode"
318
+
319
+ const ean13Svg = renderBarcodeSvg({
320
+ code: "3017620422003",
321
+ symbology: "ean13",
322
+ title: "Organic Hazelnut Spread",
323
+ includeText: true,
324
+ })
325
+
326
+ const qrSvg = renderBarcodeSvg({
327
+ code: "https://store.example.com/01/03017620422003/21/SN001",
328
+ symbology: "qr",
329
+ width: 200,
330
+ height: 200,
331
+ })
332
+ ```
333
+
334
+ ### Creating & Verifying Anti-Counterfeit HMAC-SHA256 Tags
335
+
336
+ Each `BarcodeTag` automatically receives an `hmac_signature` computed over `code | targetId | serialNumber | batchLot` using `MEDUSA_BARCODE_HMAC_SECRET` and verified via `crypto.timingSafeEqual`:
337
+
338
+ ```ts
339
+ // Create a signed anti-counterfeit QR tag via workflow:
340
+ const { result: tag } = await generateBarcodeTagWorkflow(req.scope).run({
341
+ input: {
342
+ target_type: "product",
343
+ target_id: "prod_01HXYZ",
344
+ product_id: "prod_01HXYZ",
345
+ symbology: "qr",
346
+ scan_action: "verify",
347
+ gs1_gtin: "09506000134352",
348
+ batch_lot: "BATCH-2026-09",
349
+ serial_number: "SN-884920",
350
+ },
351
+ })
352
+
353
+ // Verify authenticity on the storefront:
354
+ // GET /store/barcodes/mpb_AbCdEf12/verify?sig=<64-char-hex-hmac>
355
+ ```
356
+
357
+ ---
358
+
359
+ ## 9. Thermal Roll & A4 Sheet Price/Barcode Label Printing (HTML + Zebra ZPL II)
360
+
361
+ ### Built-In Label Presets (`BUILTIN_LABEL_TEMPLATES`)
362
+
363
+ | Preset ID | Layout Type | Dimensions (mm) | Grid (`cols × rows`) | Default Symbology | DPI | Typical Hardware / Use Case |
364
+ | :--------------- | :------------- | :--------------: | :------------------: | :---------------: | :---: | :--------------------------------------------------------- |
365
+ | `thermal_50x25` | `thermal_roll` | `50 × 25 mm` | `1 × 1` | `ean13` | `203` | Zebra ZD410 / ZD421 / Rollo retail price & barcode sticker |
366
+ | `thermal_57x32` | `thermal_roll` | `57 × 32 mm` | `1 × 1` | `ean13` | `203` | Dymo 30334 / Zebra apparel & shelf hang-tag with QR |
367
+ | `thermal_100x50` | `thermal_roll` | `100 × 50 mm` | `1 × 1` | `code128` | `203` | Warehouse master carton / bin label with QR |
368
+ | `jewelry_30x15` | `thermal_roll` | `30 × 15 mm` | `1 × 1` | `code128` | `300` | High-density 300 DPI jewelry / eyewear dumbbell tag |
369
+ | `a4_24up_70x37` | `a4_sheet` | `70 × 37 mm` | `3 × 8` (24/page) | `ean13` | `300` | Avery L7163 / standard A4 24-up laser/inkjet sheet |
370
+ | `a4_40up_52x30` | `a4_sheet` | `52.5 × 29.7 mm` | `4 × 10` (40/page) | `ean13` | `300` | Standard A4 40-up retail barcode sticker sheet |
371
+ | `a4_65up_38x21` | `a4_sheet` | `38.1 × 21.2 mm` | `5 × 13` (65/page) | `ean13` | `300` | Avery L7651 / A4 65-up mini price/EAN sticker sheet |
372
+
373
+ ### Rendering Labels Programmatically
374
+
375
+ ```ts
376
+ import { renderPrintableLabels } from "medusa-plugin-barcode"
377
+
378
+ const output = renderPrintableLabels(
379
+ [
380
+ {
381
+ barcode: "3017620422003",
382
+ title: "Organic Espresso Beans",
383
+ variant_title: "250g Whole Bean",
384
+ sku: "ESP-250-WB",
385
+ brand: "Medusa Roasters",
386
+ price: 14.5,
387
+ compare_at_price: 18.0,
388
+ currency_code: "USD",
389
+ quantity: 2,
390
+ },
391
+ ],
392
+ "thermal_50x25"
393
+ )
394
+
395
+ // output.html => Complete <!DOCTYPE html> document with @page CSS & inline SVGs
396
+ // output.zpl => Raw Zebra ZPL II commands (^XA ... ^BEN ... ^XZ)
397
+ ```
398
+
399
+ Example generated **Zebra ZPL II** output:
400
+
401
+ ```zpl
402
+ ^XA
403
+ ^CI28
404
+ ^PW400
405
+ ^LL200
406
+ ^LH0,0
407
+ ^FO16,12^A0N,22,22^FDOrganic Espresso Beans^FS
408
+ ^FO16,36^A0N,18,18^FD250g Whole Bean^FS
409
+ ^FO16,56^A0N,16,16^FDSKU: ESP-250-WB^FS
410
+ ^FO16,74^A0N,26,26^FD$14.50 (MRP $18.00)^FS
411
+ ^FO16,104^BY2^BEN,68,Y,N^FD301762042200^FS
412
+ ^PQ1,0,1,Y
413
+ ^XZ
414
+ ```
415
+
416
+ ---
417
+
418
+ ## 10. Warehouse Stock-Take Count Sessions & Quick Scan Adjustments
419
+
420
+ `medusa-plugin-barcode` supports two warehouse inventory scanning workflows:
421
+
422
+ 1. **Instant Scan-to-Lookup / Quick Adjust (`POST /admin/barcodes/scan`)**:
423
+ - Scan any barcode with a USB/Bluetooth HID scanner or camera to resolve its `product_id` and `variant_id`, and optionally trigger `"increment"`, `"decrement"`, or `"set"` actions.
424
+ 2. **Full Stock-Take Audit Sessions (`BarcodeCountSession` & `BarcodeCountItem`)**:
425
+ - Create a named count session scoped to a `location_id` with optional `expected_items`.
426
+ - Rapidly scan items via `POST /admin/barcodes/count-sessions/[id]/scan` (`delta: 1`, `delta: -1`, or `set_quantity`).
427
+ - Live calculation of `expected_quantity`, `counted_quantity`, and `variance` per item and across the session.
428
+ - Reconcile and push counted quantities to Medusa's Inventory Module (`Modules.INVENTORY`) via `POST /admin/barcodes/count-sessions/[id]/apply`.
429
+
430
+ ---
431
+
432
+ ## 11. Medusa v2 Workflows & Rollback Compensation
433
+
434
+ All 6 workflows are exported from `medusa-plugin-barcode` and `medusa-plugin-barcode/workflows`:
435
+
436
+ | Workflow | Step / Workflow ID | Description & Rollback Behavior |
437
+ | :------------------------------------ | :--------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
438
+ | `lookupAndCreateProductWorkflow` | `"lookup-and-create-product"` | Looks up a barcode across the provider chain, optionally uploads external images to `Modules.FILE`, creates a Medusa Product + Variant in `Modules.PRODUCT`, and links `BarcodeProduct`. **Compensates** by deleting both `BarcodeProduct` and the created Medusa Product on failure. |
439
+ | `batchBarcodeImportWorkflow` | `"batch-barcode-import"` | Batch-imports up to 100 barcodes, creating real Medusa Products + Variants and `BarcodeProduct` mappings. **Compensates** by rolling back all created products and mappings. |
440
+ | `bulkGenerateVariantBarcodesWorkflow` | `"bulk-generate-variant-barcodes"` | Generates GS1 in-store (`200`–`299`) EAN-13 barcodes for variants missing barcodes, updates `barcode`/`ean`/`upc` in `Modules.PRODUCT`, and creates `BarcodeTag` rows. **Compensates** by restoring previous variant barcode fields and deleting created tags. |
441
+ | `generateBarcodeTagWorkflow` | `"generate-barcode-tag"` | Creates/updates a dynamic 1D/2D `BarcodeTag` with SVG markup, HMAC-SHA256 signature, and optional `Modules.FILE` SVG upload. **Compensates** by deleting the created tag. |
442
+ | `scanInventoryCountWorkflow` | `"scan-inventory-count"` | Records a barcode scan inside an active `BarcodeCountSession` and updates item and session variance totals. |
443
+ | `applyInventoryCountWorkflow` | `"apply-inventory-count"` | Marks a `BarcodeCountSession` as `"completed"` and applies counted quantities to `Modules.INVENTORY`. **Compensates** by reverting the session status back to `"in_progress"`. |
444
+
445
+ ---
446
+
447
+ ## 12. Subscribers & Scheduled Jobs
448
+
449
+ - **Subscriber (`src/subscribers/product-created.ts`)**:
450
+ - Listens to `product.created` and `product-variant.created`.
451
+ - When `autoGenerateVariantBarcode !== false`, invokes `bulkGenerateVariantBarcodesWorkflow` so every new variant automatically receives a valid GS1 in-store EAN-13 barcode and `BarcodeTag`.
452
+ - **Scheduled Job (`src/jobs/purge-expired-barcode-cache.ts`)**:
453
+ - Runs on cron schedule `0 */6 * * *` (every 6 hours) and purges expired rows from `barcode_cache`.
454
+
455
+ ---
456
+
457
+ ## 13. Complete REST API Reference (Admin & Storefront)
458
+
459
+ ### Admin Endpoints
460
+
461
+ #### `GET /admin/barcodes`
462
+
463
+ Lists linked `BarcodeProduct` mappings (filterable by `?product_id=...`) and studio analytics overview.
464
+
465
+ #### `POST /admin/barcodes/lookup`
466
+
467
+ Looks up a barcode across the 10-provider chain without creating a product.
468
+
469
+ ```json
470
+ {
471
+ "barcode": "3017620422003",
472
+ "strategy": "deep-merge",
473
+ "skipCache": false
474
+ }
475
+ ```
476
+
477
+ #### `POST /admin/barcodes/create-from-barcode`
478
+
479
+ Looks up a barcode and creates a Medusa Product + Variant via `lookupAndCreateProductWorkflow`.
480
+
481
+ ```json
482
+ {
483
+ "barcode": "3017620422003",
484
+ "status": "draft",
485
+ "strategy": "deep-merge",
486
+ "downloadImages": false,
487
+ "overridePrice": 6.99,
488
+ "currencyCode": "USD"
489
+ }
490
+ ```
491
+
492
+ #### `POST /admin/barcodes/batch`
493
+
494
+ Batch imports up to 100 barcodes via `batchBarcodeImportWorkflow`.
495
+
496
+ ```json
497
+ {
498
+ "barcodes": ["3017620422003", "9780140328721"],
499
+ "status": "draft",
500
+ "strategy": "first-hit",
501
+ "createMissingAsDraft": true
502
+ }
503
+ ```
504
+
505
+ #### `POST /admin/barcodes/bulk-generate`
506
+
507
+ Auto-generates GS1 in-store (`200`–`299`) EAN-13 barcodes for variants.
508
+
509
+ ```json
510
+ {
511
+ "variant_ids": ["variant_01HXYZ"],
512
+ "prefix": "200",
513
+ "overwrite": false
514
+ }
515
+ ```
516
+
517
+ #### `POST /admin/barcodes/scan`
518
+
519
+ Resolves a barcode scan and performs an optional quick inventory action (`lookup`, `increment`, `decrement`, `set`).
520
+
521
+ ```json
522
+ {
523
+ "barcode": "3017620422003",
524
+ "action": "increment",
525
+ "quantity": 1,
526
+ "location_id": "sloc_01"
527
+ }
528
+ ```
529
+
530
+ #### `GET /admin/barcodes/cache` & `DELETE /admin/barcodes/cache`
531
+
532
+ Lists cached provider responses or purges expired entries (pass `?all=true` to clear all cache entries).
533
+
534
+ #### `GET /admin/barcodes/[barcode]` & `DELETE /admin/barcodes/[barcode]`
535
+
536
+ Retrieves a specific barcode's parsed metadata, `BarcodeProduct` link, `BarcodeTag`, and rendered SVG, or deletes its mapping and cache entry.
537
+
538
+ #### `GET /admin/barcodes/tags` & `POST /admin/barcodes/tags`
539
+
540
+ Lists `BarcodeTag` rows (filterable by `?product_id=...` or `?target_id=...`) or creates a signed 1D/2D `BarcodeTag`.
541
+
542
+ #### `GET /admin/barcodes/tags/[id]`, `PATCH /admin/barcodes/tags/[id]`, `DELETE /admin/barcodes/tags/[id]`
543
+
544
+ Retrieves, updates, or deletes a `BarcodeTag` by ID.
545
+
546
+ #### `GET /admin/barcodes/templates` & `POST /admin/barcodes/templates`
547
+
548
+ Lists all 7 built-in presets + custom database templates, or saves a new custom `BarcodeLabelTemplate`.
549
+
550
+ #### `POST /admin/barcodes/print`
551
+
552
+ Renders print-ready HTML+SVG sheets and raw Zebra ZPL II thermal commands.
553
+
554
+ ```json
555
+ {
556
+ "template_id": "thermal_50x25",
557
+ "items": [
558
+ {
559
+ "barcode": "3017620422003",
560
+ "title": "Organic Espresso Beans",
561
+ "variant_title": "250g Whole Bean",
562
+ "sku": "ESP-250-WB",
563
+ "brand": "Medusa Roasters",
564
+ "price": 14.5,
565
+ "compare_at_price": 18.0,
566
+ "currency_code": "USD",
567
+ "quantity": 4
568
+ }
569
+ ]
570
+ }
571
+ ```
572
+
573
+ #### `GET /admin/barcodes/count-sessions` & `POST /admin/barcodes/count-sessions`
574
+
575
+ Lists all warehouse stock-take sessions with their line items, or starts a new `BarcodeCountSession`.
576
+
577
+ #### `POST /admin/barcodes/count-sessions/[id]/scan`
578
+
579
+ Records a barcode scan (`delta` or `set_quantity`) inside an active count session.
580
+
581
+ #### `POST /admin/barcodes/count-sessions/[id]/apply`
582
+
583
+ Completes a stock-take session and pushes variances to Medusa's Inventory Module.
584
+
585
+ ---
586
+
587
+ ### Storefront Endpoints
588
+
589
+ #### `GET /store/barcodes/[code]`
590
+
591
+ - Default (`?format=json`): Resolves a scanned barcode or QR code, increments `scan_count`, and returns `{ code, parsed, found, action, target_url, product_id, variant_id, tag, barcode_product }`.
592
+ - Image mode (`?format=svg&symbology=ean13`): Returns `Content-Type: image/svg+xml` directly for `<img src="/store/barcodes/3017620422003?format=svg" />`.
593
+
594
+ #### `GET /store/barcodes/[code]/verify?sig=...` & `POST /store/barcodes/[code]/verify`
595
+
596
+ Verifies an anti-counterfeit `HMAC-SHA256` signature in constant time and returns `{ valid, code, reason, tag }`.
597
+
598
+ ---
599
+
600
+ ## 14. Typed SDK Client (`medusa-plugin-barcode/sdk`)
601
+
602
+ ```ts
603
+ import { createBarcodeSdk } from "medusa-plugin-barcode/sdk"
604
+
605
+ const barcodeSdk = createBarcodeSdk({
606
+ baseUrl:
607
+ process.env.NEXT_PUBLIC_MEDUSA_BACKEND_URL || "http://localhost:9000",
608
+ publishableApiKey: process.env.NEXT_PUBLIC_MEDUSA_PUBLISHABLE_KEY,
609
+ })
610
+
611
+ // Admin calls:
612
+ const lookup = await barcodeSdk.admin.lookup({
613
+ barcode: "3017620422003",
614
+ strategy: "deep-merge",
615
+ })
616
+ const labels = await barcodeSdk.admin.printLabels({
617
+ template_id: "thermal_57x32",
618
+ items: [
619
+ {
620
+ barcode: "3017620422003",
621
+ title: "Nutella 400g",
622
+ price: 5.99,
623
+ quantity: 2,
624
+ },
625
+ ],
626
+ })
627
+
628
+ // Storefront calls:
629
+ const resolved = await barcodeSdk.store.resolveScan("3017620422003")
630
+ const verified = await barcodeSdk.store.verifyAuthenticity(
631
+ "MPB-001",
632
+ hmacSignature
633
+ )
634
+ const svgUrl = barcodeSdk.store.getSvgUrl("3017620422003", "ean13")
635
+ ```
636
+
637
+ ---
638
+
639
+ ## 15. React Hooks: USB HID Keyboard-Wedge & WebRTC Camera Scanners (`medusa-plugin-barcode/hooks`)
640
+
641
+ ```tsx
642
+ import {
643
+ useHidBarcodeScanner,
644
+ useCameraBarcodeScanner,
645
+ useStoreBarcodeResolver,
646
+ } from "medusa-plugin-barcode/hooks"
647
+
648
+ export function WarehouseScannerView() {
649
+ // 1. Hardware USB / Bluetooth HID Keyboard-Wedge Scanner (< 45ms keystroke intervals)
650
+ const { lastScanned } = useHidBarcodeScanner({
651
+ enabled: true,
652
+ minLength: 6,
653
+ maxInterKeyDelayMs: 45,
654
+ onScan: (barcode) => {
655
+ console.log("Hardware HID scanner read:", barcode)
656
+ },
657
+ })
658
+
659
+ // 2. WebRTC Camera BarcodeDetector Scanner
660
+ const { videoRef, isScanning, startCamera, stopCamera } =
661
+ useCameraBarcodeScanner({
662
+ facingMode: "environment",
663
+ onScan: (barcode) => {
664
+ console.log("Camera scanner read:", barcode)
665
+ },
666
+ })
667
+
668
+ // 3. Storefront scan & HMAC authenticity resolver
669
+ const { resolveScan, verifyAuthenticity } = useStoreBarcodeResolver()
670
+
671
+ return (
672
+ <div>
673
+ <button onClick={() => (isScanning ? stopCamera() : void startCamera())}>
674
+ {isScanning ? "Stop Camera" : "Start Camera"}
675
+ </button>
676
+ {isScanning && <video ref={videoRef} muted playsInline />}
677
+ {lastScanned && <p>Last HID Scan: {lastScanned}</p>}
678
+ </div>
679
+ )
680
+ }
681
+ ```
682
+
683
+ ---
684
+
685
+ ## 16. Storefront UI Kit (`medusa-plugin-barcode/ui`)
686
+
687
+ Drop-in React components with zero `dangerouslySetInnerHTML` usage:
688
+
689
+ ```tsx
690
+ import {
691
+ BarcodeImage,
692
+ AuthenticityVerifierBadge,
693
+ StorefrontBarcodeScanner,
694
+ } from "medusa-plugin-barcode/ui"
695
+
696
+ export function ProductPageBarcodeSection({
697
+ code,
698
+ hmacSignature,
699
+ }: {
700
+ code: string
701
+ hmacSignature: string
702
+ }) {
703
+ return (
704
+ <div style={{ display: "grid", gap: 16 }}>
705
+ {/* Crisp SVG Barcode or QR via safe data-URI / endpoint */}
706
+ <BarcodeImage
707
+ code={code}
708
+ symbology="ean13"
709
+ baseUrl="http://localhost:9000"
710
+ width={220}
711
+ height={88}
712
+ />
713
+
714
+ {/* Interactive Anti-Counterfeit HMAC Seal Verifier */}
715
+ <AuthenticityVerifierBadge
716
+ code={code}
717
+ signature={hmacSignature}
718
+ sdkOptions={{ baseUrl: "http://localhost:9000" }}
719
+ />
720
+
721
+ {/* Customer Camera + USB HID Scanner Modal/Card */}
722
+ <StorefrontBarcodeScanner
723
+ sdkOptions={{ baseUrl: "http://localhost:9000" }}
724
+ onResolved={(res) => {
725
+ if (res.target_url) window.location.href = String(res.target_url)
726
+ }}
727
+ />
728
+ </div>
729
+ )
730
+ }
731
+ ```
732
+
733
+ ---
734
+
735
+ ## 17. Admin Studio (`/app/barcodes`) & Product Detail Widget
736
+
737
+ - **Admin Barcode Studio (`src/admin/routes/barcodes/`)**:
738
+ - Automatically mounts at `/app/barcodes` ("Barcode & Label Studio") with a `SINGLE_COLUMN` overview dashboard, `TWO_COLUMN` feature sub-routes (`LayoutComposer`), `RouteDrawer` modal creation flows, 10-locale `react-i18next` support (`en`, `es`, `fr`, `de`, `it`, `pt`, `nl`, `pl`, `tr`, and RTL `ar`), and a global USB HID scanner listener active across all routes:
739
+ 1. **Overview Dashboard (`/app/barcodes` — `routes/barcodes/page.tsx`)**: KPI summary cards and navigation cards into each studio workflow.
740
+ 2. **GTIN Lookup & Batch Importer (`/app/barcodes/lookup` — `routes/barcodes/lookup/page.tsx`)**: Live single lookup, 1-click Medusa product creation, and multi-line batch GTIN/ISBN importer.
741
+ 3. **Dynamic 1D/2D & HMAC QR Tags (`/app/barcodes/tags` & `/app/barcodes/tags/create` — `routes/barcodes/tags/page.tsx` & `tags/@create/page.tsx`)**: Create signed product/variant/order tags with GS1 GTIN, Batch/Lot, Serial Number, and scan action via inline form or `RouteDrawer` (`KeyboundForm` + `Form`).
742
+ 4. **Thermal & Sheet Label Print Center (`/app/barcodes/print` — `routes/barcodes/print/page.tsx`)**: Choose any of the 7 thermal/A4 presets, configure multi-currency MRP & Sale price, and export print-ready HTML+SVG or raw Zebra ZPL II (`^XA...^XZ`).
743
+ 5. **Warehouse Stock-Take (`/app/barcodes/stock-take` — `routes/barcodes/stock-take/page.tsx`)**: Start count sessions, scan items (`+1` / `-1`), inspect variance, and apply counts to the Inventory Module.
744
+ 6. **Providers & Cache (`/app/barcodes/providers` — `routes/barcodes/providers/page.tsx`)**: Inspect active lookup providers and purge expired/all cached lookups.
745
+ - **Product Detail Widget (`src/admin/widgets/product-barcode-widget.tsx`)**:
746
+ - Injected into `product.details.after` on every Medusa Admin product page for 1-click GS1 EAN-13 generation and thermal label printing.
747
+
748
+ ---
749
+
750
+ ## 18. Writing a Custom Lookup Provider
751
+
752
+ You can register your own proprietary ERP, PIM, or regional GTIN database provider in `ProviderRegistry`:
753
+
754
+ ```ts
755
+ import {
756
+ BaseBarcodeProvider,
757
+ type BarcodeSymbology,
758
+ type NormalizedBarcodeProduct,
759
+ } from "medusa-plugin-barcode"
760
+
761
+ export class MyErpBarcodeProvider extends BaseBarcodeProvider {
762
+ readonly name = "my_erp"
763
+
764
+ constructor() {
765
+ super({ priority: 5, timeout: 4000 })
766
+ }
767
+
768
+ async lookup(
769
+ barcode: string,
770
+ format: BarcodeSymbology
771
+ ): Promise<NormalizedBarcodeProduct | null> {
772
+ const data = await this.fetchJson<{
773
+ title?: string
774
+ brand?: string
775
+ price?: number
776
+ }>(`https://erp.example.com/api/gtin/${encodeURIComponent(barcode)}`)
777
+ if (!data?.title) return null
778
+
779
+ return {
780
+ barcode,
781
+ barcode_type: format,
782
+ name: data.title,
783
+ description: null,
784
+ brand: data.brand ?? null,
785
+ manufacturer: data.brand ?? null,
786
+ categories: ["ERP Catalog"],
787
+ images: [],
788
+ weight: null,
789
+ weight_unit: null,
790
+ dimensions: null,
791
+ quantity_label: null,
792
+ ingredients: null,
793
+ nutrition: null,
794
+ country_of_origin: null,
795
+ suggested_price: data.price ?? null,
796
+ currency_code: "USD",
797
+ isbn: null,
798
+ authors: [],
799
+ publisher: null,
800
+ published_date: null,
801
+ page_count: null,
802
+ provider: this.name,
803
+ raw_data: data,
804
+ }
805
+ }
806
+ }
807
+
808
+ // Register at runtime:
809
+ const barcodeService = container.resolve("barcode")
810
+ const registry = await barcodeService.getProviderRegistry()
811
+ registry.register(new MyErpBarcodeProvider())
812
+ ```
813
+
814
+ ---
815
+
816
+ ## 19. Migration Guide from `@bambiste/medusa-barcode` & `@bambiste/medusa-qr`
817
+
818
+ `medusa-plugin-barcode` maintains full export compatibility with `@bambiste/medusa-barcode`:
819
+
820
+ - `BARCODE_MODULE`, `BarcodeService` (alias for `BarcodeModuleService`), `BaseBarcodeProvider`, `ProviderRegistry`, all 8 original provider classes, `parseBarcode`, `computeEan13CheckDigit`, `upcToEan13`, `lookupAndCreateProductWorkflow`, and `batchBarcodeImportWorkflow` are all exported directly from the root package.
821
+ - Simply replace `@bambiste/medusa-barcode` and `@bambiste/medusa-qr` in `medusa-config.ts` with `medusa-plugin-barcode` and run `npx medusa db:migrate`.
822
+
823
+ ---
824
+
825
+ ## 20. Security Architecture
826
+
827
+ - **Zero DOM XSS (`escapeHtml` & Safe SVG Data-URIs)**: All product titles, SKUs, brands, and custom headers/footers interpolated into SVG or printable HTML sheets are escaped via `escapeHtml`. React components render SVGs via URL-encoded `data:image/svg+xml;utf8,...` `<img />` elements—never `dangerouslySetInnerHTML` or `innerHTML`.
828
+ - **SSRF Prevention (`validateExternalImageUrl`)**: External image URLs returned by third-party barcode APIs are validated before fetching: only `https:` is permitted, and loopback/private/link-local addresses (`localhost`, `127.0.0.0/8`, `10.0.0.0/8`, `172.16.0.0/12`, `192.168.0.0/16`, `169.254.169.254` cloud metadata, IPv6 loopback/unique-local) are strictly blocked.
829
+ - **Constant-Time Anti-Counterfeit HMAC (`verifyAuthenticityHmac`)**: Uses `HMAC-SHA256` with `crypto.timingSafeEqual` to prevent timing side-channel signature forgery.
830
+ - **Strict Zod Input Validation (`src/api/validators.ts`)**: Every Admin and Store `POST`/`PATCH` endpoint enforces bounded string lengths, array sizes (e.g. max 100 batch barcodes, max 200 print items), and enum allowlists via `validateAndTransformBody`.
831
+
832
+ ---
833
+
834
+ ## 21. Testing, Linting & Typechecking
835
+
836
+ ```bash
837
+ # Run TypeScript compiler typecheck (0 errors)
838
+ npm run typecheck
839
+
840
+ # Run strict @medusajs/eslint-plugin linter (--max-warnings=0)
841
+ npm run lint
842
+
843
+ # Run unit, provider, SVG/ZPL label printer, workflow compensation & security test suite
844
+ npm test
845
+ ```