inventory: barcode scanner in Add-item dialog

Add a camera barcode/QR scanner (components/scan/barcode-scanner.tsx,
@zxing/browser lazy-loaded) and a Barcode/NDC field to the pharmacy
Add-item dialog. Scanning a GS1 DataMatrix auto-fills expiry (AI 17) and
lot (AI 10 -> notes), with the GTIN (AI 01) as the barcode; plain 1D
barcodes drop straight into the field. Persists a nullable inventory
barcode column (migration 0036) through the type/validation/service, and
surfaces it on the item detail. i18n added to all locales.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
Khalid Abdi
2026-07-18 23:32:45 +03:00
parent bac3e7a1d0
commit 0754ce96a4
19 changed files with 5067 additions and 2 deletions
@@ -0,0 +1 @@
ALTER TABLE "inventory" ADD COLUMN "barcode" text;
File diff suppressed because it is too large Load Diff
+7
View File
@@ -253,6 +253,13 @@
"when": 1783530491321,
"tag": "0035_slippery_retro_girl",
"breakpoints": true
},
{
"idx": 36,
"version": "7",
"when": 1784406410448,
"tag": "0036_aspiring_expediter",
"breakpoints": true
}
]
}
+2
View File
@@ -29,6 +29,8 @@ export const inventory = pgTable(
stockQuantity: integer("stock_quantity").notNull().default(0),
reorderThreshold: integer("reorder_threshold").notNull().default(0),
location: text("location").notNull().default(""),
// Scanned medication barcode / NDC (GTIN when read from a GS1 DataMatrix).
barcode: text("barcode"),
expiresAt: date("expires_at"),
notes: text("notes"),
createdBy: text("created_by").references(() => user.id, {
+1
View File
@@ -13,6 +13,7 @@ export const inventoryInputSchema = z.object({
stockQuantity: z.number().int().min(0).max(1_000_000).default(0),
reorderThreshold: z.number().int().min(0).max(1_000_000).default(0),
location: z.string().trim().max(200).default(""),
barcode: z.string().trim().max(120).nullish(),
expiresAt: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/, "Date must be YYYY-MM-DD.")
+2
View File
@@ -21,6 +21,7 @@ function toInventoryItem(row: InventoryRow): InventoryItem {
stockQuantity: row.stockQuantity,
reorderThreshold: row.reorderThreshold,
location: row.location,
barcode: row.barcode,
expiresAt: row.expiresAt,
notes: row.notes,
createdAt: row.createdAt.toISOString(),
@@ -38,6 +39,7 @@ function columns(orgId: string, input: InventoryInput, createdBy?: string) {
stockQuantity: input.stockQuantity,
reorderThreshold: input.reorderThreshold,
location: input.location,
barcode: input.barcode ?? null,
expiresAt: input.expiresAt ?? null,
notes: input.notes ?? null,
...(createdBy ? { createdBy } : {}),
+1
View File
@@ -11,6 +11,7 @@ export type InventoryItem = {
stockQuantity: number;
reorderThreshold: number;
location: string;
barcode: string | null;
expiresAt: string | null; // YYYY-MM-DD
notes: string | null;
createdAt: string;
@@ -1,8 +1,10 @@
"use client";
import { ScanLine } from "lucide-react";
import { type FormEvent, type ReactNode, useState } from "react";
import { useTranslation } from "react-i18next";
import { BarcodeScanner } from "@/components/scan/barcode-scanner";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -15,6 +17,7 @@ import {
DialogTitle,
} from "@/components/ui/dialog";
import { Input } from "@/components/ui/input";
import { parseGs1 } from "@/lib/gs1";
import type { InventoryInput } from "@/lib/inventory";
import { notify } from "@/lib/toast";
@@ -48,7 +51,12 @@ export function AddInventoryDialog({
const [stockQuantity, setStockQuantity] = useState("0");
const [reorderThreshold, setReorderThreshold] = useState("0");
const [location, setLocation] = useState("");
const [barcode, setBarcode] = useState("");
const [expiresAt, setExpiresAt] = useState("");
// Lot/batch parsed from a GS1 scan. No dedicated field, so it rides along in
// notes (surfaced on the item detail).
const [notes, setNotes] = useState("");
const [scannerOpen, setScannerOpen] = useState(false);
const reset = () => {
setName("");
@@ -58,7 +66,24 @@ export function AddInventoryDialog({
setStockQuantity("0");
setReorderThreshold("0");
setLocation("");
setBarcode("");
setExpiresAt("");
setNotes("");
};
// A scanned medication barcode: store the code, and when it's a GS1
// DataMatrix, auto-fill expiry (AI 17) and lot (AI 10, -> notes).
const handleScan = (raw: string) => {
setScannerOpen(false);
const gs1 = parseGs1(raw);
if (gs1) {
setBarcode(gs1.gtin ?? raw);
if (gs1.expiry) setExpiresAt(gs1.expiry);
if (gs1.lot) setNotes((n) => n || `Lot: ${gs1.lot}`);
} else {
setBarcode(raw.trim());
}
notify.success(t("inventory.dialog.scannedTitle"), gs1?.gtin ?? raw.trim());
};
const submit = (event: FormEvent) => {
@@ -79,7 +104,9 @@ export function AddInventoryDialog({
stockQuantity: Number.parseInt(stockQuantity, 10) || 0,
reorderThreshold: Number.parseInt(reorderThreshold, 10) || 0,
location: location.trim(),
barcode: barcode.trim() || null,
expiresAt: expiresAt || null,
notes: notes.trim() || null,
});
notify.success(t("inventory.dialog.addedTitle"), trimmed);
reset();
@@ -87,6 +114,7 @@ export function AddInventoryDialog({
};
return (
<>
<Dialog
onOpenChange={(o) => {
onOpenChange(o);
@@ -174,6 +202,26 @@ export function AddInventoryDialog({
/>
</Field>
</div>
<Field label={t("inventory.dialog.barcode")}>
<div className="flex items-center gap-2">
<Input
inputMode="numeric"
onChange={(event) => setBarcode(event.target.value)}
placeholder={t("inventory.dialog.barcodePlaceholder")}
value={barcode}
/>
<Button
aria-label={t("inventory.dialog.scan")}
onClick={() => setScannerOpen(true)}
size="icon"
type="button"
variant="outline"
>
<ScanLine className="size-4" />
</Button>
</div>
</Field>
</DialogPanel>
<DialogFooter>
@@ -187,5 +235,11 @@ export function AddInventoryDialog({
</form>
</DialogPopup>
</Dialog>
<BarcodeScanner
onDetected={handleScan}
onOpenChange={setScannerOpen}
open={scannerOpen}
/>
</>
);
}
@@ -109,6 +109,10 @@ export function InventoryDetailDialog({
label={t("inventory.dialog.expires")}
value={item.expiresAt || "—"}
/>
<Row
label={t("inventory.dialog.barcode")}
value={item.barcode || "—"}
/>
{item.notes ? (
<div className="flex flex-col gap-1 py-2">
<span className="text-muted-foreground text-sm">
@@ -0,0 +1,118 @@
"use client";
import { useEffect, useRef, useState } from "react";
import { useTranslation } from "react-i18next";
import { Button } from "@/components/ui/button";
import {
Dialog,
DialogClose,
DialogDescription,
DialogFooter,
DialogHeader,
DialogPanel,
DialogPopup,
DialogTitle,
} from "@/components/ui/dialog";
// Camera barcode/QR scanner in a dialog. Decoding uses @zxing/browser
// (lazy-loaded so it stays out of the initial bundle), which reads 1D barcodes
// (EAN/UPC/Code128) and 2D codes (QR, GS1 DataMatrix, PDF417) — the mix found
// on medication packaging and patient wallet codes. Emits the decoded string
// once, then the caller closes the dialog.
export function BarcodeScanner({
open,
onOpenChange,
onDetected,
title,
description,
}: {
open: boolean;
onOpenChange: (open: boolean) => void;
onDetected: (value: string) => void;
title?: string;
description?: string;
}) {
const { t } = useTranslation();
const videoRef = useRef<HTMLVideoElement>(null);
// Keep the latest onDetected without restarting the camera on every render.
const onDetectedRef = useRef(onDetected);
onDetectedRef.current = onDetected;
const [error, setError] = useState<string | null>(null);
useEffect(() => {
if (!open) return;
let stopped = false;
let controls: { stop: () => void } | null = null;
setError(null);
(async () => {
const video = videoRef.current;
if (!video) return;
try {
const { BrowserMultiFormatReader } = await import("@zxing/browser");
const reader = new BrowserMultiFormatReader();
controls = await reader.decodeFromConstraints(
{ video: { facingMode: "environment" } },
video,
(result) => {
if (result && !stopped) {
stopped = true;
controls?.stop();
onDetectedRef.current(result.getText());
}
},
);
// The dialog may have closed while getUserMedia was resolving.
if (stopped) controls.stop();
} catch (err) {
setError(
err instanceof DOMException && err.name === "NotAllowedError"
? t("scan.permissionDenied")
: t("scan.unavailable"),
);
}
})();
return () => {
stopped = true;
controls?.stop();
};
}, [open, t]);
return (
<Dialog onOpenChange={onOpenChange} open={open}>
<DialogPopup className="sm:max-w-md">
<DialogHeader>
<DialogTitle>{title ?? t("scan.title")}</DialogTitle>
<DialogDescription>
{description ?? t("scan.description")}
</DialogDescription>
</DialogHeader>
<DialogPanel>
{error ? (
<p className="text-sm text-destructive">{error}</p>
) : (
<div className="relative aspect-video overflow-hidden rounded-2xl border bg-black">
{/* biome-ignore lint/a11y/useMediaCaption: live camera preview */}
<video
className="size-full object-cover"
muted
playsInline
ref={videoRef}
/>
<div className="pointer-events-none absolute inset-6 rounded-xl border-2 border-white/70" />
</div>
)}
</DialogPanel>
<DialogFooter>
<DialogClose render={<Button type="button" variant="outline" />}>
{t("scan.cancel")}
</DialogClose>
</DialogFooter>
</DialogPopup>
</Dialog>
);
}
+85
View File
@@ -0,0 +1,85 @@
// Minimal GS1 Application Identifier parser for medication barcodes (the GS1
// DataMatrix printed on drug packaging). We only care about the AIs a pharmacy
// add-item flow can use: 01 GTIN, 17 expiry, 10 lot/batch, 21 serial. Variable
// -length fields are terminated by the FNC1/GS separator (ASCII 29); the AIs
// below have fixed lengths per the GS1 General Specifications.
export type Gs1Fields = {
gtin?: string;
/** AI 17 normalised to YYYY-MM-DD. */
expiry?: string;
lot?: string;
serial?: string;
};
const GS = "\x1d";
// value length (excluding the 2-digit AI) for the fixed-length AIs we handle.
const FIXED_LEN: Record<string, number> = {
"00": 18,
"01": 14,
"02": 14,
"11": 6,
"12": 6,
"13": 6,
"15": 6,
"16": 6,
"17": 6,
"20": 2,
};
function yymmddToIso(v: string): string | undefined {
if (!/^\d{6}$/.test(v)) return undefined;
const year = 2000 + Number(v.slice(0, 2));
const month = Number(v.slice(2, 4));
let day = Number(v.slice(4, 6));
if (month < 1 || month > 12) return undefined;
// GS1 allows DD=00 to mean "end of the month".
if (day === 0) day = new Date(year, month, 0).getDate();
const pad = (n: number) => String(n).padStart(2, "0");
return `${year}-${pad(month)}-${pad(day)}`;
}
// Parse a scanned string as GS1. Returns null when it isn't GS1-structured (a
// plain EAN-13 / Code128 barcode), so callers can fall back to the raw value.
export function parseGs1(raw: string): Gs1Fields | null {
if (!raw) return null;
let s = raw;
// Strip a leading symbology identifier (e.g. "]d2", "]C1", "]e0").
if (s.startsWith("]")) s = s.slice(3);
if (s.startsWith(GS)) s = s.slice(1);
// GS1 medication codes lead with (01) GTIN; bail early otherwise so a plain
// numeric barcode isn't mis-parsed.
if (!s.startsWith("01")) return null;
const out: Gs1Fields = {};
let i = 0;
let matched = false;
while (i + 2 <= s.length) {
const ai = s.slice(i, i + 2);
i += 2;
const fixed = FIXED_LEN[ai];
let value: string;
if (fixed != null) {
value = s.slice(i, i + fixed);
i += fixed;
} else {
const gsIdx = s.indexOf(GS, i);
if (gsIdx === -1) {
value = s.slice(i);
i = s.length;
} else {
value = s.slice(i, gsIdx);
i = gsIdx + 1;
}
}
if (s[i] === GS) i += 1; // consume a separator trailing a fixed field
if (!value) break;
matched = true;
if (ai === "01") out.gtin = value;
else if (ai === "17") out.expiry = yymmddToIso(value);
else if (ai === "10") out.lot = value;
else if (ai === "21") out.serial = value;
}
return matched ? out : null;
}
@@ -1,4 +1,11 @@
{
"scan": {
"title": "مسح رمز",
"description": "وجّه الكاميرا نحو باركود أو رمز QR.",
"cancel": "إلغاء",
"permissionDenied": "تم رفض الوصول إلى الكاميرا. فعّله للمسح.",
"unavailable": "المسح غير متاح على هذا الجهاز."
},
"scribe": {
"recordVisit": "تسجيل الزيارة",
"title": "كاتب الزيارة",
@@ -702,6 +709,10 @@
"location": "الموقع",
"locationPlaceholder": "مثال: A3",
"expires": "تنتهي الصلاحية",
"barcode": "الباركود / NDC",
"barcodePlaceholder": "امسح أو اكتب رمزًا",
"scan": "مسح الباركود",
"scannedTitle": "تم مسح الباركود",
"cancel": "إلغاء",
"submit": "إضافة عنصر",
"nameRequiredTitle": "اسم الدواء مطلوب",
@@ -1,4 +1,11 @@
{
"scan": {
"title": "Code scannen",
"description": "Richte die Kamera auf einen Barcode oder QR-Code.",
"cancel": "Abbrechen",
"permissionDenied": "Kamerazugriff verweigert. Aktiviere ihn zum Scannen.",
"unavailable": "Scannen ist auf diesem Gerät nicht verfügbar."
},
"scribe": {
"recordVisit": "Besuch aufnehmen",
"title": "Besuchs-Schreiber",
@@ -686,6 +693,10 @@
"location": "Standort",
"locationPlaceholder": "z. B. A3",
"expires": "Verfällt",
"barcode": "Barcode / NDC",
"barcodePlaceholder": "Code scannen oder eingeben",
"scan": "Barcode scannen",
"scannedTitle": "Barcode gescannt",
"cancel": "Abbrechen",
"submit": "Artikel hinzufügen",
"nameRequiredTitle": "Medikamentenname erforderlich",
@@ -1,4 +1,11 @@
{
"scan": {
"title": "Scan a code",
"description": "Point the camera at a barcode or QR code.",
"cancel": "Cancel",
"permissionDenied": "Camera access was denied. Enable it to scan.",
"unavailable": "Scanning isn't available on this device."
},
"scribe": {
"recordVisit": "Record visit",
"title": "Visit scribe",
@@ -686,6 +693,10 @@
"location": "Location",
"locationPlaceholder": "e.g. A3",
"expires": "Expires",
"barcode": "Barcode / NDC",
"barcodePlaceholder": "Scan or type a code",
"scan": "Scan barcode",
"scannedTitle": "Barcode scanned",
"cancel": "Cancel",
"submit": "Add item",
"nameRequiredTitle": "Medication name required",
@@ -1,4 +1,11 @@
{
"scan": {
"title": "Scanner un code",
"description": "Dirigez la caméra vers un code-barres ou un QR code.",
"cancel": "Annuler",
"permissionDenied": "Accès à la caméra refusé. Activez-le pour scanner.",
"unavailable": "Le scan n'est pas disponible sur cet appareil."
},
"scribe": {
"recordVisit": "Enregistrer la visite",
"title": "Scribe de visite",
@@ -686,6 +693,10 @@
"location": "Emplacement",
"locationPlaceholder": "ex. A3",
"expires": "Expire le",
"barcode": "Code-barres / NDC",
"barcodePlaceholder": "Scanner ou saisir un code",
"scan": "Scanner le code-barres",
"scannedTitle": "Code-barres scanné",
"cancel": "Annuler",
"submit": "Ajouter l'article",
"nameRequiredTitle": "Nom du médicament requis",
@@ -1,4 +1,11 @@
{
"scan": {
"title": "Iskaan garee koodh",
"description": "U jeedi kamarada barcode ama koodh QR.",
"cancel": "Jooji",
"permissionDenied": "Gelitaanka kamarada waa la diiday. Daar si aad u iskaan gariso.",
"unavailable": "Iskaanku kuma shaqeeyo qalabkan."
},
"scribe": {
"recordVisit": "Duub booqasho",
"title": "Qoraaga booqashada",
@@ -686,6 +693,10 @@
"location": "Goobta",
"locationPlaceholder": "tusaale A3",
"expires": "Dhacaya",
"barcode": "Barcode / NDC",
"barcodePlaceholder": "Iskaan garee ama qor koodh",
"scan": "Iskaan garee barcode",
"scannedTitle": "Barcode la iskaan gareeyay",
"cancel": "Jooji",
"submit": "Ku dar shay",
"nameRequiredTitle": "Magaca daawada ayaa loo baahan yahay",
+2
View File
@@ -11,6 +11,7 @@ export type InventoryItem = {
stockQuantity: number;
reorderThreshold: number;
location: string;
barcode: string | null;
expiresAt: string | null;
notes: string | null;
createdAt: string;
@@ -26,6 +27,7 @@ export type InventoryInput = {
stockQuantity?: number;
reorderThreshold?: number;
location?: string;
barcode?: string | null;
expiresAt?: string | null;
notes?: string | null;
};
+48 -2
View File
@@ -1,12 +1,12 @@
{
"name": "frontend",
"version": "0.12.0",
"version": "0.15.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "frontend",
"version": "0.12.0",
"version": "0.15.1",
"dependencies": {
"@ai-sdk/react": "^3.0.206",
"@base-ui/react": "^1.5.0",
@@ -32,6 +32,7 @@
"@visx/scale": "^4.0.1-alpha.0",
"@visx/shape": "^4.0.1-alpha.0",
"@xyflow/react": "^12.10.2",
"@zxing/browser": "^0.2.1",
"ai": "^6.0.193",
"ansi-to-react": "^6.2.6",
"better-auth": "^1.6.13",
@@ -6255,6 +6256,41 @@
"d3-zoom": "^3.0.0"
}
},
"node_modules/@zxing/browser": {
"version": "0.2.1",
"resolved": "https://registry.npmjs.org/@zxing/browser/-/browser-0.2.1.tgz",
"integrity": "sha512-92pVfVDUXbc15xu9vIEmhNyqIEASMEkDF92CwT6T+7sg2EHXJRktH9CQKoQSXe51UtbNsj+Fm09H/JBWHMs/Sw==",
"license": "MIT",
"optionalDependencies": {
"@zxing/text-encoding": "^0.9.0"
},
"peerDependencies": {
"@zxing/library": "^0.23.0"
}
},
"node_modules/@zxing/library": {
"version": "0.23.0",
"resolved": "https://registry.npmjs.org/@zxing/library/-/library-0.23.0.tgz",
"integrity": "sha512-6fkkoFwP8CHxl6ugnPsj74PLJgX2iRv5zczGAyt5OBzQgxFhuhF0NCEc4t4OvSr8xAv2MRLlI0Iu9ZGDZQ2urA==",
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"ts-custom-error": "^3.3.1"
},
"engines": {
"node": ">= 24.0.0"
},
"optionalDependencies": {
"@zxing/text-encoding": "~0.9.0"
}
},
"node_modules/@zxing/text-encoding": {
"version": "0.9.0",
"resolved": "https://registry.npmjs.org/@zxing/text-encoding/-/text-encoding-0.9.0.tgz",
"integrity": "sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==",
"license": "(Unlicense OR Apache-2.0)",
"optional": true
},
"node_modules/accepts": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-2.0.0.tgz",
@@ -16002,6 +16038,16 @@
"typescript": ">=4.8.4"
}
},
"node_modules/ts-custom-error": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/ts-custom-error/-/ts-custom-error-3.3.1.tgz",
"integrity": "sha512-5OX1tzOjxWEgsr/YEUWSuPrQ00deKLh6D7OTWcvNHm12/7QPyRh8SYpyWvA4IZv8H/+GQWQEh/kwo95Q9OVW1A==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/ts-dedent": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/ts-dedent/-/ts-dedent-2.2.0.tgz",
+1
View File
@@ -34,6 +34,7 @@
"@visx/scale": "^4.0.1-alpha.0",
"@visx/shape": "^4.0.1-alpha.0",
"@xyflow/react": "^12.10.2",
"@zxing/browser": "^0.2.1",
"ai": "^6.0.193",
"ansi-to-react": "^6.2.6",
"better-auth": "^1.6.13",