Add barcode scanning to manage products

This commit is contained in:
beatz174-bit committed 2025-11-21 18:17:01 +10:00
1 parent e361af2a1c
commit b81ac51242
6 files changed
+100 -34

No files matched your search

+6 -3
View File
@@ -1,3 +1,4 @@
import { useEffect } from 'react';
import { Alert, Card, CardContent, Typography } from '@mui/material'; import { Alert, Card, CardContent, Typography } from '@mui/material';
import { useBarcodeScanner } from '../hooks/useBarcodeScanner'; import { useBarcodeScanner } from '../hooks/useBarcodeScanner';
@@ -8,9 +9,11 @@ interface BarcodeScannerViewProps {
export const BarcodeScannerView = ({ onDetected }: BarcodeScannerViewProps) => { export const BarcodeScannerView = ({ onDetected }: BarcodeScannerViewProps) => {
const { videoRef, result } = useBarcodeScanner(); const { videoRef, result } = useBarcodeScanner();
if (result.code && onDetected) { useEffect(() => {
onDetected(result.code); if (result.code && onDetected) {
} onDetected(result.code);
}
}, [onDetected, result.code]);
return ( return (
<Card variant="outlined"> <Card variant="outlined">
+43 -14
View File
@@ -2,18 +2,23 @@ import {
Card, Card,
CardActions, CardActions,
CardContent, CardContent,
Dialog,
DialogContent,
DialogTitle,
IconButton, IconButton,
MenuItem, MenuItem,
Stack, Stack,
TextField, TextField,
Typography, Typography,
Button,
} from '@mui/material'; } from '@mui/material';
import DeleteIcon from '@mui/icons-material/Delete'; import DeleteIcon from '@mui/icons-material/Delete';
import EditIcon from '@mui/icons-material/Edit'; import EditIcon from '@mui/icons-material/Edit';
import CheckIcon from '@mui/icons-material/Check'; import CheckIcon from '@mui/icons-material/Check';
import CloseIcon from '@mui/icons-material/Close'; import CloseIcon from '@mui/icons-material/Close';
import { ChangeEvent, useEffect, useState } from 'react'; import { ChangeEvent, useEffect, useState } from 'react';
import { DEFAULT_BULK_NAME, DEFAULT_UNIT_TYPE, Product } from '../models/Product'; import { DEFAULT_UNIT_TYPE, Product } from '../models/Product';
import { BarcodeScannerView } from './BarcodeScannerView';
interface ProductRowProps { interface ProductRowProps {
product: Product; product: Product;
@@ -23,7 +28,7 @@ interface ProductRowProps {
updates: { updates: {
name: string; name: string;
category: string; category: string;
units_per_bulk?: number; barcode?: string;
}, },
) => Promise<void> | void; ) => Promise<void> | void;
onDelete: (productId: string) => Promise<void> | void; onDelete: (productId: string) => Promise<void> | void;
@@ -32,18 +37,19 @@ interface ProductRowProps {
interface ProductFormState { interface ProductFormState {
name: string; name: string;
category: string; category: string;
unitsPerBulk: string; barcode: string;
} }
const getInitialFormState = (product: Product): ProductFormState => ({ const getInitialFormState = (product: Product): ProductFormState => ({
name: product.name, name: product.name,
category: product.category, category: product.category,
unitsPerBulk: product.units_per_bulk?.toString() ?? '', barcode: product.barcode ?? '',
}); });
export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRowProps) => { export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRowProps) => {
const [isEditing, setIsEditing] = useState(false); const [isEditing, setIsEditing] = useState(false);
const [formState, setFormState] = useState<ProductFormState>(() => getInitialFormState(product)); const [formState, setFormState] = useState<ProductFormState>(() => getInitialFormState(product));
const [isScannerOpen, setIsScannerOpen] = useState(false);
useEffect(() => { useEffect(() => {
setFormState(getInitialFormState(product)); setFormState(getInitialFormState(product));
@@ -58,7 +64,7 @@ export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRow
await onSave(product.id, { await onSave(product.id, {
name: formState.name, name: formState.name,
category: formState.category, category: formState.category,
units_per_bulk: formState.unitsPerBulk ? Number(formState.unitsPerBulk) : undefined, barcode: formState.barcode || undefined,
}); });
setIsEditing(false); setIsEditing(false);
}; };
@@ -87,13 +93,25 @@ export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRow
</MenuItem> </MenuItem>
))} ))}
</TextField> </TextField>
<TextField {formState.barcode ? (
label="Units per Bulk" <TextField
type="number" label="Barcode"
value={formState.unitsPerBulk} value={formState.barcode}
onChange={handleChange('unitsPerBulk')} onChange={handleChange('barcode')}
size="small" size="small"
/> InputProps={{
endAdornment: (
<Button size="small" onClick={() => setFormState((prev) => ({ ...prev, barcode: '' }))}>
Clear
</Button>
),
}}
/>
) : (
<Button variant="outlined" onClick={() => setIsScannerOpen(true)}>
Scan Barcode
</Button>
)}
</Stack> </Stack>
) : ( ) : (
<Stack direction="row" justifyContent="space-between" alignItems="center"> <Stack direction="row" justifyContent="space-between" alignItems="center">
@@ -103,9 +121,9 @@ export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRow
{product.category} • {product.unit_type || DEFAULT_UNIT_TYPE} {product.category} • {product.unit_type || DEFAULT_UNIT_TYPE}
</Typography> </Typography>
</div> </div>
{product.units_per_bulk ? ( {product.barcode ? (
<Typography variant="caption" color="text.secondary"> <Typography variant="caption" color="text.secondary">
{product.units_per_bulk} per {product.bulk_name || DEFAULT_BULK_NAME} Barcode: {product.barcode}
</Typography> </Typography>
) : null} ) : null}
</Stack> </Stack>
@@ -132,6 +150,17 @@ export const ProductRow = ({ product, categories, onSave, onDelete }: ProductRow
</> </>
)} )}
</CardActions> </CardActions>
<Dialog open={isScannerOpen} onClose={() => setIsScannerOpen(false)} fullWidth>
<DialogTitle>Scan Barcode</DialogTitle>
<DialogContent>
<BarcodeScannerView
onDetected={(code) => {
setFormState((prev) => ({ ...prev, barcode: code }));
setIsScannerOpen(false);
}}
/>
</DialogContent>
</Dialog>
</Card> </Card>
); );
}; };
-3
View File
@@ -33,7 +33,6 @@ export const seedDatabase = async (db: StockFillDB) => {
category: 'Drinks', category: 'Drinks',
unit_type: DEFAULT_UNIT_TYPE, unit_type: DEFAULT_UNIT_TYPE,
bulk_name: DEFAULT_BULK_NAME, bulk_name: DEFAULT_BULK_NAME,
units_per_bulk: 12,
archived: false, archived: false,
created_at: now(), created_at: now(),
updated_at: now(), updated_at: now(),
@@ -44,7 +43,6 @@ export const seedDatabase = async (db: StockFillDB) => {
category: 'Snacks', category: 'Snacks',
unit_type: DEFAULT_UNIT_TYPE, unit_type: DEFAULT_UNIT_TYPE,
bulk_name: DEFAULT_BULK_NAME, bulk_name: DEFAULT_BULK_NAME,
units_per_bulk: 24,
archived: false, archived: false,
created_at: now(), created_at: now(),
updated_at: now(), updated_at: now(),
@@ -55,7 +53,6 @@ export const seedDatabase = async (db: StockFillDB) => {
category: 'Confectionery', category: 'Confectionery',
unit_type: DEFAULT_UNIT_TYPE, unit_type: DEFAULT_UNIT_TYPE,
bulk_name: DEFAULT_BULK_NAME, bulk_name: DEFAULT_BULK_NAME,
units_per_bulk: 32,
archived: false, archived: false,
created_at: now(), created_at: now(),
updated_at: now(), updated_at: now(),
+13 -4
View File
@@ -1,6 +1,9 @@
import { useEffect, useRef, useState } from 'react'; import { useEffect, useRef, useState } from 'react';
import { BrowserMultiFormatReader } from '@zxing/browser'; import { BrowserMultiFormatReader } from '@zxing/browser';
type BarcodeDetection = { rawValue: string };
type BarcodeDetectorClass = new () => { detect: (source: ImageBitmapSource) => Promise<BarcodeDetection[]> };
export interface BarcodeResult { export interface BarcodeResult {
code?: string; code?: string;
error?: string; error?: string;
@@ -14,15 +17,20 @@ export const useBarcodeScanner = () => {
const reader = new BrowserMultiFormatReader(); const reader = new BrowserMultiFormatReader();
let active = true; let active = true;
let stop: (() => void) | undefined; let stop: (() => void) | undefined;
let currentVideoElement: HTMLVideoElement | null = null;
const start = async () => { const start = async () => {
try { try {
if ('BarcodeDetector' in window) { const detectorClass = (
const detector = new (window as typeof window & { BarcodeDetector: any }).BarcodeDetector(); window as typeof window & { BarcodeDetector?: BarcodeDetectorClass }
).BarcodeDetector;
if (detectorClass) {
const detector = new detectorClass();
const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } }); const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment' } });
if (videoRef.current) { if (videoRef.current) {
videoRef.current.srcObject = stream; videoRef.current.srcObject = stream;
await videoRef.current.play(); await videoRef.current.play();
currentVideoElement = videoRef.current;
} }
const scan = async () => { const scan = async () => {
if (!active || !videoRef.current) return; if (!active || !videoRef.current) return;
@@ -58,8 +66,9 @@ export const useBarcodeScanner = () => {
return () => { return () => {
active = false; active = false;
stop?.(); stop?.();
if (videoRef.current?.srcObject) { const stream = currentVideoElement?.srcObject as MediaStream | null;
(videoRef.current.srcObject as MediaStream).getTracks().forEach((track) => track.stop()); if (stream) {
stream.getTracks().forEach((track) => track.stop());
} }
}; };
}, []); }, []);
-1
View File
@@ -4,7 +4,6 @@ export interface Product {
category: string; category: string;
unit_type: string; unit_type: string;
bulk_name?: string; bulk_name?: string;
units_per_bulk?: number;
barcode?: string; barcode?: string;
archived: boolean; archived: boolean;
created_at: number; created_at: number;
+38 -9
View File
@@ -6,6 +6,9 @@ import {
TextField, TextField,
Typography, Typography,
InputAdornment, InputAdornment,
Dialog,
DialogTitle,
DialogContent,
} from '@mui/material'; } from '@mui/material';
import SearchIcon from '@mui/icons-material/Search'; import SearchIcon from '@mui/icons-material/Search';
import { Link as RouterLink } from 'react-router-dom'; import { Link as RouterLink } from 'react-router-dom';
@@ -15,6 +18,7 @@ import { ProductRow } from '../components/ProductRow';
import { useCategories, useProducts } from '../hooks/dataHooks'; import { useCategories, useProducts } from '../hooks/dataHooks';
import { useDatabase } from '../context/DBProvider'; import { useDatabase } from '../context/DBProvider';
import { DEFAULT_BULK_NAME, DEFAULT_UNIT_TYPE } from '../models/Product'; import { DEFAULT_BULK_NAME, DEFAULT_UNIT_TYPE } from '../models/Product';
import { BarcodeScannerView } from '../components/BarcodeScannerView';
export const ManageProductsScreen = () => { export const ManageProductsScreen = () => {
const db = useDatabase(); const db = useDatabase();
@@ -23,7 +27,8 @@ export const ManageProductsScreen = () => {
const [search, setSearch] = useState(''); const [search, setSearch] = useState('');
const [name, setName] = useState(''); const [name, setName] = useState('');
const [category, setCategory] = useState(''); const [category, setCategory] = useState('');
const [unitsPerBulk, setUnitsPerBulk] = useState(6); const [barcode, setBarcode] = useState('');
const [scannerOpen, setScannerOpen] = useState(false);
const categoryOptions = useMemo(() => { const categoryOptions = useMemo(() => {
const categoryNames = categories.map((item) => item.name); const categoryNames = categories.map((item) => item.name);
@@ -54,12 +59,13 @@ export const ManageProductsScreen = () => {
category, category,
unit_type: DEFAULT_UNIT_TYPE, unit_type: DEFAULT_UNIT_TYPE,
bulk_name: DEFAULT_BULK_NAME, bulk_name: DEFAULT_BULK_NAME,
units_per_bulk: unitsPerBulk, barcode: barcode || undefined,
archived: false, archived: false,
created_at: Date.now(), created_at: Date.now(),
updated_at: Date.now(), updated_at: Date.now(),
}); });
setName(''); setName('');
setBarcode('');
}; };
const updateProduct = async ( const updateProduct = async (
@@ -67,7 +73,7 @@ export const ManageProductsScreen = () => {
updates: { updates: {
name: string; name: string;
category: string; category: string;
units_per_bulk?: number; barcode?: string;
}, },
) => { ) => {
await db.products.update(productId, { await db.products.update(productId, {
@@ -113,12 +119,24 @@ export const ManageProductsScreen = () => {
</MenuItem> </MenuItem>
))} ))}
</TextField> </TextField>
<TextField {barcode ? (
label="Units per Bulk" <TextField
type="number" label="Barcode"
value={unitsPerBulk} value={barcode}
onChange={(event) => setUnitsPerBulk(Number(event.target.value))} onChange={(event) => setBarcode(event.target.value)}
/> InputProps={{
endAdornment: (
<Button onClick={() => setBarcode('')} size="small">
Clear
</Button>
),
}}
/>
) : (
<Button variant="outlined" onClick={() => setScannerOpen(true)}>
Scan Barcode
</Button>
)}
<Button variant="contained" onClick={addProduct} disabled={!name || !category}> <Button variant="contained" onClick={addProduct} disabled={!name || !category}>
Save Product Save Product
</Button> </Button>
@@ -133,6 +151,17 @@ export const ManageProductsScreen = () => {
/> />
))} ))}
</Stack> </Stack>
<Dialog open={scannerOpen} onClose={() => setScannerOpen(false)} fullWidth>
<DialogTitle>Scan Barcode</DialogTitle>
<DialogContent>
<BarcodeScannerView
onDetected={(code) => {
setBarcode(code);
setScannerOpen(false);
}}
/>
</DialogContent>
</Dialog>
</Container> </Container>
); );
}; };