refactor: extract useScanner hook from page.tsx
This commit is contained in:
@@ -64,7 +64,9 @@
|
||||
"Bash(curl -v http://localhost:8906/users)",
|
||||
"Bash(NEXT_PUBLIC_API_URL=http://localhost:8916 npm run dev -- --port 8917)",
|
||||
"Bash(curl -sf http://localhost:8917)",
|
||||
"Bash(xargs sed *)"
|
||||
"Bash(xargs sed *)",
|
||||
"Bash(sed -i -e 's/\\\\btext-slate-100\\\\b/text-secondary/g' -e s/placeholder:text-slate-700/placeholder:text-muted/g -e s/hover:text-slate-300/hover:text-secondary/g app/page.tsx)",
|
||||
"Bash(sed -i 's/\\\\btext-slate-300\\\\b/text-secondary/g' app/page.tsx)"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { useState, useEffect, useCallback } from 'react';
|
||||
import { db, Item } from '@/lib/db';
|
||||
import { inventoryApi } from '@/lib/api';
|
||||
import { fetchAndCacheItems, syncOfflineOperations } from '@/lib/sync';
|
||||
import { useScanner } from '@/hooks/useScanner';
|
||||
import Scanner from '@/components/Scanner';
|
||||
import AIOnboarding from '@/components/AIOnboarding';
|
||||
import PageShell from '@/components/PageShell';
|
||||
@@ -42,58 +43,54 @@ function cn(...inputs: ClassValue[]) {
|
||||
return twMerge(clsx(inputs));
|
||||
}
|
||||
|
||||
// Fuzzy string matching with Levenshtein distance
|
||||
// Returns true if strings are similar enough (allowing 1-2 character differences)
|
||||
function fuzzyMatch(str1: string, str2: string, maxDistance: number = 2): boolean {
|
||||
const s1 = str1.toLowerCase().replace(/\s+/g, '');
|
||||
const s2 = str2.toLowerCase().replace(/\s+/g, '');
|
||||
|
||||
if (s1 === s2) return true;
|
||||
if (Math.abs(s1.length - s2.length) > maxDistance) return false;
|
||||
|
||||
// Levenshtein distance
|
||||
const matrix: number[][] = Array(s2.length + 1).fill(null).map(() => Array(s1.length + 1).fill(0));
|
||||
for (let i = 0; i <= s1.length; i++) matrix[0][i] = i;
|
||||
for (let j = 0; j <= s2.length; j++) matrix[j][0] = j;
|
||||
|
||||
for (let j = 1; j <= s2.length; j++) {
|
||||
for (let i = 1; i <= s1.length; i++) {
|
||||
const indicator = s1[i - 1] === s2[j - 1] ? 0 : 1;
|
||||
matrix[j][i] = Math.min(
|
||||
matrix[j][i - 1] + 1,
|
||||
matrix[j - 1][i] + 1,
|
||||
matrix[j - 1][i - 1] + indicator
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return matrix[s2.length][s1.length] <= maxDistance;
|
||||
}
|
||||
|
||||
export default function Home() {
|
||||
const [mounted, setMounted] = useState(false);
|
||||
const [isOnline, setIsOnline] = useState(true);
|
||||
const [mode, setMode] = useState<'CHECK_IN' | 'CHECK_OUT' | 'TRASH'>('CHECK_OUT');
|
||||
const [showScanner, setShowScanner] = useState(false);
|
||||
const [inventory, setInventory] = useState<Item[]>([]);
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
const [selectedBoxLabel, setSelectedBoxLabel] = useState<string | null>(null);
|
||||
const [selectedItem, setSelectedItem] = useState<Item | null>(null);
|
||||
const [boxMatches, setBoxMatches] = useState<Item[]>([]);
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [isScannerReady, setIsScannerReady] = useState(false);
|
||||
const [editedItem, setEditedItem] = useState<Partial<Item>>({});
|
||||
const [adjustQty, setAdjustQty] = useState<number>(1);
|
||||
const [adjustType, setAdjustType] = useState<'ADD' | 'REMOVE' | 'TRASH'>('ADD');
|
||||
const [trashReason, setTrashReason] = useState('Damaged');
|
||||
const [lastScanned, setLastScanned] = useState<string | null>(null);
|
||||
const [inventory, setInventory] = useState<Item[]>([]);
|
||||
const [syncing, setSyncing] = useState(false);
|
||||
const [currentUser, setCurrentUser] = useState<any | null>(null);
|
||||
const [categories, setCategories] = useState<any[]>([]);
|
||||
const [fieldScanning, setFieldScanning] = useState<{ active: boolean, field: string } | null>(null);
|
||||
const [comparisonModal, setComparisonModal] = useState<{ show: boolean, newItem: any, existingItem: any, existingId: number | null }>({ show: false, newItem: null, existingItem: null, existingId: null });
|
||||
const [comparisonLoading, setComparisonLoading] = useState(false);
|
||||
|
||||
const {
|
||||
mode,
|
||||
setMode,
|
||||
showScanner,
|
||||
setShowScanner,
|
||||
lastScanned,
|
||||
isScannerReady,
|
||||
fieldScanning,
|
||||
setFieldScanning,
|
||||
onScanSuccess,
|
||||
onOCRMatch,
|
||||
} = useScanner({
|
||||
inventory,
|
||||
isOnline,
|
||||
onSync: handleSync,
|
||||
onMatchFound: (item, adjustType) => {
|
||||
setSelectedItem(item);
|
||||
setAdjustType(adjustType);
|
||||
},
|
||||
onMultipleMatches: (items) => {
|
||||
setBoxMatches(items);
|
||||
},
|
||||
onFieldCapture: (field, value) => {
|
||||
if (field === 'box_label') {
|
||||
setEditedItem(prev => ({ ...prev, box_label: value }));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (!localStorage.getItem('inventory_token')) {
|
||||
window.location.href = '/login';
|
||||
@@ -111,11 +108,9 @@ export default function Home() {
|
||||
// Initial data fetch
|
||||
inventoryApi.getCategories().then(c => setCategories(c)).catch(() => { });
|
||||
loadInventory();
|
||||
preloadOCR();
|
||||
|
||||
const handleOnline = () => {
|
||||
setIsOnline(true);
|
||||
handleSync(); // Auto-sync pending ops when back online
|
||||
};
|
||||
const handleOffline = () => setIsOnline(false);
|
||||
|
||||
@@ -147,17 +142,21 @@ export default function Home() {
|
||||
}
|
||||
};
|
||||
|
||||
const preloadOCR = async () => {
|
||||
const handleSync = useCallback(async () => {
|
||||
if (!isOnline || !currentUser) return;
|
||||
setSyncing(true);
|
||||
try {
|
||||
// Import the library only when needed to keep bundle small
|
||||
const { createWorker } = await import('tesseract.js');
|
||||
const worker = await createWorker('eng');
|
||||
await worker.terminate();
|
||||
setIsScannerReady(true);
|
||||
} catch (e) {
|
||||
console.warn("OCR Preload failed - will retry on demand", e);
|
||||
const result = await syncOfflineOperations(currentUser.id);
|
||||
if (result.success > 0) {
|
||||
toast.success(`Synced ${result.success} operations!`);
|
||||
}
|
||||
await loadInventory();
|
||||
} catch (error) {
|
||||
console.error("Sync failed", error);
|
||||
} finally {
|
||||
setSyncing(false);
|
||||
}
|
||||
};
|
||||
}, [isOnline, currentUser]);
|
||||
|
||||
const handleOnboardingComplete = async (itemData: any) => {
|
||||
try {
|
||||
@@ -250,171 +249,6 @@ export default function Home() {
|
||||
}
|
||||
}, [isOnline, currentUser]);
|
||||
|
||||
const onScanSuccess = useCallback(async (barcode: string) => {
|
||||
setLastScanned(barcode);
|
||||
setShowScanner(false);
|
||||
|
||||
const normalizedBarcode = barcode.toLowerCase();
|
||||
const item = await db.items.where('barcode').equals(barcode)
|
||||
.or('part_number').equals(normalizedBarcode).first();
|
||||
|
||||
if (!item) {
|
||||
toast.error(`Item ${barcode} not found in catalog.`);
|
||||
return;
|
||||
}
|
||||
|
||||
await db.pendingOperations.add({
|
||||
type: mode,
|
||||
barcode: item.barcode,
|
||||
quantity: 1,
|
||||
timestamp: Date.now(),
|
||||
synced: 0,
|
||||
uuid: crypto.randomUUID()
|
||||
});
|
||||
|
||||
const newQty = mode === 'CHECK_IN' ? item.quantity + 1 : item.quantity - 1;
|
||||
await db.items.update(item.id!, { quantity: newQty });
|
||||
|
||||
setInventory(prev => prev.map(i => i.id === item.id ? { ...i, quantity: newQty } : i));
|
||||
|
||||
toast.success(`${mode === 'CHECK_IN' ? 'Checked in' : 'Checked out'} ${item.name}`);
|
||||
|
||||
if (isOnline) {
|
||||
handleSync();
|
||||
}
|
||||
}, [mode, isOnline, handleSync]);
|
||||
|
||||
const onOCRMatch = useCallback(async (text: string) => {
|
||||
// 1. Clean and normalize
|
||||
const cleanText = text.toLowerCase().replace(/[^a-z0-9\s/+-]/g, ' ');
|
||||
|
||||
// Garbage Filter: Ignore noisy strings (measurements like 0.11, dates like 2024-07-25)
|
||||
// We only keep tokens that are at least 3 chars AND not just decimals
|
||||
const tokens = cleanText.split(/[\s\n,]+/)
|
||||
.filter(t => t.length >= 3)
|
||||
.filter(t => !/^\d+\.\d+$/.test(t)) // Filter out decimals like 0.11 or 0.12
|
||||
.filter(t => !/^\d{2,4}-\d{2}-\d{2}$/.test(t)); // Filter out dates
|
||||
|
||||
if (tokens.length === 0) return;
|
||||
|
||||
// [NEW] Targeted Field Scan Logic
|
||||
if (fieldScanning?.active) {
|
||||
if (fieldScanning.field === 'box_label') {
|
||||
const potentialLabel = tokens[0] || cleanText;
|
||||
setEditedItem(prev => ({ ...prev, box_label: potentialLabel }));
|
||||
setFieldScanning(null);
|
||||
toast.success(`Captured: ${potentialLabel}`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// Toast only potentially useful scans
|
||||
toast(`Scanning: ${cleanText.substring(0, 30)}...`, { icon: '🔍', duration: 1500, id: 'ocr-scan' });
|
||||
|
||||
// [BOX SCANNING LOGIC] Prioritize checking if this is a known box
|
||||
const possibleBoxItems = inventory.filter(item => {
|
||||
if (!item.box_label) return false;
|
||||
const boxText = item.box_label.toLowerCase().replace(/[^a-z0-9\s/+-]/g, ' ');
|
||||
// Exact or Partial include match for box label
|
||||
if (cleanText.includes(boxText)) return true;
|
||||
// Strong token matching (for words >= 4 chars)
|
||||
const boxTokens = boxText.split(/[\s/+-]/).filter(t => t.length >= 4);
|
||||
const matchedTokens = boxTokens.filter(bt => tokens.includes(bt));
|
||||
return matchedTokens.length >= 2 || (boxTokens.length === 1 && matchedTokens.length === 1);
|
||||
});
|
||||
|
||||
if (possibleBoxItems.length === 1) {
|
||||
toast.success(`Box identified: 1 item found`, { duration: 3000, id: 'ocr-success' });
|
||||
setSelectedItem(possibleBoxItems[0]);
|
||||
setAdjustType(mode === 'CHECK_IN' ? 'ADD' : 'REMOVE');
|
||||
setShowScanner(false);
|
||||
return;
|
||||
} else if (possibleBoxItems.length > 1) {
|
||||
toast.success(`Box identified: ${possibleBoxItems.length} items found`, { duration: 3000, id: 'ocr-success' });
|
||||
setBoxMatches(possibleBoxItems);
|
||||
setShowScanner(false);
|
||||
return;
|
||||
}
|
||||
|
||||
// [INDIVIDUAL ITEM MATCHING] Fallback to classic specific identification
|
||||
let bestMatch = null;
|
||||
let maxMatchScore = 0;
|
||||
|
||||
for (const item of inventory) {
|
||||
let score = 0;
|
||||
const pn = (item.part_number || '').toLowerCase();
|
||||
const sn = (item.serial_number || '').toLowerCase();
|
||||
const name = item.name.toLowerCase();
|
||||
const category = item.category.toLowerCase();
|
||||
const ocrKey = (item.ocr_text || '').toLowerCase().replace(/[^a-z0-9\s/+-]/g, ' ');
|
||||
|
||||
// Priority 0: OCR Key match (Heuristic provided by AI) with fuzzy tolerance
|
||||
if (ocrKey) {
|
||||
if (cleanText.includes(ocrKey)) {
|
||||
score += 1000; // Exact match
|
||||
} else {
|
||||
// Fuzzy match for OCR keys (allows 2-char differences for robustness)
|
||||
const ocrTokens = ocrKey.split(/[\s/+-]+/).filter(t => t.length >= 2);
|
||||
const matchedTokens = ocrTokens.filter(token => {
|
||||
return tokens.some(t => fuzzyMatch(t, token, 2));
|
||||
});
|
||||
if (matchedTokens.length >= Math.ceil(ocrTokens.length * 0.7)) {
|
||||
score += 800; // Fuzzy match (70%+ token coverage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 1: Serial Number (Absolute match)
|
||||
if (sn && cleanText.includes(sn)) score += 500;
|
||||
|
||||
// Priority 2: Part Number (High confidence, with fuzzy tolerance)
|
||||
if (pn) {
|
||||
if (cleanText.includes(pn)) {
|
||||
score += 200; // Exact match
|
||||
} else {
|
||||
// Fuzzy match for part numbers (allows 1-char differences)
|
||||
const pnTokens = pn.split(/[\s/+-]/).filter(t => t.length >= 2);
|
||||
const matchedPnTokens = pnTokens.filter(pnToken =>
|
||||
tokens.some(t => fuzzyMatch(t, pnToken, 1))
|
||||
);
|
||||
if (matchedPnTokens.length >= Math.max(2, Math.ceil(pnTokens.length * 0.6))) {
|
||||
score += 150; // Fuzzy match (60%+ token coverage)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Priority 3: Token based matching for PN (LC/UPC etc)
|
||||
if (pn) {
|
||||
const pnTokens = pn.split(/[\s/+-]/).filter(t => t.length >= 3);
|
||||
pnTokens.forEach(t => {
|
||||
if (cleanText.includes(t)) {
|
||||
score += 50;
|
||||
} else if (tokens.some(scanToken => fuzzyMatch(scanToken, t, 1))) {
|
||||
score += 30; // Fuzzy token match
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Priority 4: Name & Category
|
||||
const nameTokens = name.split(/[\s/+-]/).filter(t => t.length >= 3);
|
||||
nameTokens.forEach(t => { if (cleanText.includes(t)) score += 10; });
|
||||
|
||||
if (category && cleanText.includes(category)) score += 20;
|
||||
|
||||
if (score > maxMatchScore) {
|
||||
maxMatchScore = score;
|
||||
bestMatch = item;
|
||||
}
|
||||
}
|
||||
|
||||
// Threshold: Need a significant score to match automatically
|
||||
if (bestMatch && maxMatchScore >= 40) {
|
||||
toast.success(`Matched: ${bestMatch.name}`, { duration: 3000, id: 'ocr-success' });
|
||||
setSelectedItem(bestMatch);
|
||||
setAdjustType(mode === 'CHECK_IN' ? 'ADD' : 'REMOVE');
|
||||
setShowScanner(false);
|
||||
}
|
||||
}, [mode, inventory]);
|
||||
|
||||
const handleUpdateItem = async () => {
|
||||
if (!selectedItem) return;
|
||||
|
||||
236
frontend/hooks/useScanner.ts
Normal file
236
frontend/hooks/useScanner.ts
Normal file
@@ -0,0 +1,236 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { db, Item } from '@/lib/db';
|
||||
import { toast } from 'react-hot-toast';
|
||||
|
||||
interface UseScannerOptions {
|
||||
inventory: Item[];
|
||||
isOnline: boolean;
|
||||
onSync: () => Promise<void>;
|
||||
onMatchFound?: (item: Item, adjustType: 'ADD' | 'REMOVE') => void;
|
||||
onMultipleMatches?: (items: Item[]) => void;
|
||||
onFieldCapture?: (field: string, value: string) => void;
|
||||
}
|
||||
|
||||
// Fuzzy string matching with Levenshtein distance
|
||||
// Returns true if strings are similar enough (allowing 1-2 character differences)
|
||||
function fuzzyMatch(str1: string, str2: string, maxDistance: number = 2): boolean {
|
||||
const s1 = str1.toLowerCase().replace(/\s+/g, '');
|
||||
const s2 = str2.toLowerCase().replace(/\s+/g, '');
|
||||
|
||||
if (s1 === s2) return true;
|
||||
if (Math.abs(s1.length - s2.length) > maxDistance) return false;
|
||||
|
||||
// Levenshtein distance
|
||||
const matrix: number[][] = Array(s2.length + 1).fill(null).map(() => Array(s1.length + 1).fill(0));
|
||||
for (let i = 0; i <= s1.length; i++) matrix[0][i] = i;
|
||||
for (let j = 0; j <= s2.length; j++) matrix[j][0] = j;
|
||||
|
||||
for (let j = 1; j <= s2.length; j++) {
|
||||
for (let i = 1; i <= s1.length; i++) {
|
||||
const indicator = s1[i - 1] === s2[j - 1] ? 0 : 1;
|
||||
matrix[j][i] = Math.min(
|
||||
matrix[j][i - 1] + 1,
|
||||
matrix[j - 1][i] + 1,
|
||||
matrix[j - 1][i - 1] + indicator
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
return matrix[s2.length][s1.length] <= maxDistance;
|
||||
}
|
||||
|
||||
export function useScanner(options: UseScannerOptions) {
|
||||
const { inventory, isOnline, onSync, onMatchFound, onMultipleMatches, onFieldCapture } = options;
|
||||
const [mode, setMode] = useState<'CHECK_IN' | 'CHECK_OUT' | 'TRASH'>('CHECK_OUT');
|
||||
const [showScanner, setShowScanner] = useState(false);
|
||||
const [lastScanned, setLastScanned] = useState<string | null>(null);
|
||||
const [isScannerReady, setIsScannerReady] = useState(false);
|
||||
const [fieldScanning, setFieldScanning] = useState<{ active: boolean, field: string } | null>(null);
|
||||
|
||||
const preloadOCR = useCallback(async () => {
|
||||
try {
|
||||
const { createWorker } = await import('tesseract.js');
|
||||
const worker = await createWorker('eng');
|
||||
await worker.terminate();
|
||||
setIsScannerReady(true);
|
||||
} catch (e) {
|
||||
console.warn("OCR Preload failed - will retry on demand", e);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
preloadOCR();
|
||||
}, [preloadOCR]);
|
||||
|
||||
const onScanSuccess = useCallback(async (barcode: string) => {
|
||||
setLastScanned(barcode);
|
||||
setShowScanner(false);
|
||||
|
||||
const normalizedBarcode = barcode.toLowerCase();
|
||||
const item = await db.items.where('barcode').equals(barcode)
|
||||
.or('part_number').equals(normalizedBarcode).first();
|
||||
|
||||
if (!item) {
|
||||
toast.error(`Item ${barcode} not found in catalog.`);
|
||||
return;
|
||||
}
|
||||
|
||||
await db.pendingOperations.add({
|
||||
type: mode,
|
||||
barcode: item.barcode,
|
||||
quantity: 1,
|
||||
timestamp: Date.now(),
|
||||
synced: 0,
|
||||
uuid: crypto.randomUUID()
|
||||
});
|
||||
|
||||
const newQty = mode === 'CHECK_IN' ? item.quantity + 1 : item.quantity - 1;
|
||||
await db.items.update(item.id!, { quantity: newQty });
|
||||
|
||||
toast.success(`${mode === 'CHECK_IN' ? 'Checked in' : 'Checked out'} ${item.name}`);
|
||||
|
||||
if (isOnline) {
|
||||
await onSync();
|
||||
}
|
||||
}, [mode, isOnline, onSync]);
|
||||
|
||||
const onOCRMatch = useCallback(async (text: string) => {
|
||||
const cleanText = text.toLowerCase().replace(/[^a-z0-9\s/+-]/g, ' ');
|
||||
|
||||
// Garbage Filter: Ignore noisy strings
|
||||
const tokens = cleanText.split(/[\s\n,]+/)
|
||||
.filter(t => t.length >= 3)
|
||||
.filter(t => !/^\d+\.\d+$/.test(t))
|
||||
.filter(t => !/^\d{2,4}-\d{2}-\d{2}$/.test(t));
|
||||
|
||||
if (tokens.length === 0) return;
|
||||
|
||||
// Targeted Field Scan Logic
|
||||
if (fieldScanning?.active) {
|
||||
if (fieldScanning.field === 'box_label') {
|
||||
const potentialLabel = tokens[0] || cleanText;
|
||||
toast.success(`Captured: ${potentialLabel}`);
|
||||
setFieldScanning(null);
|
||||
if (onFieldCapture) {
|
||||
onFieldCapture('box_label', potentialLabel);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
toast(`Scanning: ${cleanText.substring(0, 30)}...`, { icon: '🔍', duration: 1500, id: 'ocr-scan' });
|
||||
|
||||
// BOX SCANNING LOGIC
|
||||
const possibleBoxItems = inventory.filter(item => {
|
||||
if (!item.box_label) return false;
|
||||
const boxText = item.box_label.toLowerCase().replace(/[^a-z0-9\s/+-]/g, ' ');
|
||||
if (cleanText.includes(boxText)) return true;
|
||||
const boxTokens = boxText.split(/[\s/+-]/).filter(t => t.length >= 4);
|
||||
const matchedTokens = boxTokens.filter(bt => tokens.includes(bt));
|
||||
return matchedTokens.length >= 2 || (boxTokens.length === 1 && matchedTokens.length === 1);
|
||||
});
|
||||
|
||||
if (possibleBoxItems.length === 1) {
|
||||
toast.success(`Box identified: 1 item found`, { duration: 3000, id: 'ocr-success' });
|
||||
setShowScanner(false);
|
||||
if (onMatchFound) {
|
||||
onMatchFound(possibleBoxItems[0], mode === 'CHECK_IN' ? 'ADD' : 'REMOVE');
|
||||
}
|
||||
return;
|
||||
} else if (possibleBoxItems.length > 1) {
|
||||
toast.success(`Box identified: ${possibleBoxItems.length} items found`, { duration: 3000, id: 'ocr-success' });
|
||||
setShowScanner(false);
|
||||
if (onMultipleMatches) {
|
||||
onMultipleMatches(possibleBoxItems);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
// INDIVIDUAL ITEM MATCHING
|
||||
let bestMatch = null;
|
||||
let maxMatchScore = 0;
|
||||
|
||||
for (const item of inventory) {
|
||||
let score = 0;
|
||||
const pn = (item.part_number || '').toLowerCase();
|
||||
const sn = (item.serial_number || '').toLowerCase();
|
||||
const name = item.name.toLowerCase();
|
||||
const category = item.category.toLowerCase();
|
||||
const ocrKey = (item.ocr_text || '').toLowerCase().replace(/[^a-z0-9\s/+-]/g, ' ');
|
||||
|
||||
if (ocrKey) {
|
||||
if (cleanText.includes(ocrKey)) {
|
||||
score += 1000;
|
||||
} else {
|
||||
const ocrTokens = ocrKey.split(/[\s/+-]+/).filter(t => t.length >= 2);
|
||||
const matchedTokens = ocrTokens.filter(token => {
|
||||
return tokens.some(t => fuzzyMatch(t, token, 2));
|
||||
});
|
||||
if (matchedTokens.length >= Math.ceil(ocrTokens.length * 0.7)) {
|
||||
score += 800;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sn && cleanText.includes(sn)) score += 500;
|
||||
|
||||
if (pn) {
|
||||
if (cleanText.includes(pn)) {
|
||||
score += 200;
|
||||
} else {
|
||||
const pnTokens = pn.split(/[\s/+-]/).filter(t => t.length >= 2);
|
||||
const matchedPnTokens = pnTokens.filter(pnToken =>
|
||||
tokens.some(t => fuzzyMatch(t, pnToken, 1))
|
||||
);
|
||||
if (matchedPnTokens.length >= Math.max(2, Math.ceil(pnTokens.length * 0.6))) {
|
||||
score += 150;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (pn) {
|
||||
const pnTokens = pn.split(/[\s/+-]/).filter(t => t.length >= 3);
|
||||
pnTokens.forEach(t => {
|
||||
if (cleanText.includes(t)) {
|
||||
score += 50;
|
||||
} else if (tokens.some(scanToken => fuzzyMatch(scanToken, t, 1))) {
|
||||
score += 30;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const nameTokens = name.split(/[\s/+-]/).filter(t => t.length >= 3);
|
||||
nameTokens.forEach(t => { if (cleanText.includes(t)) score += 10; });
|
||||
|
||||
if (category && cleanText.includes(category)) score += 20;
|
||||
|
||||
if (score > maxMatchScore) {
|
||||
maxMatchScore = score;
|
||||
bestMatch = item;
|
||||
}
|
||||
}
|
||||
|
||||
if (bestMatch && maxMatchScore >= 40) {
|
||||
toast.success(`Matched: ${bestMatch.name}`, { duration: 3000, id: 'ocr-success' });
|
||||
setShowScanner(false);
|
||||
if (onMatchFound) {
|
||||
onMatchFound(bestMatch, mode === 'CHECK_IN' ? 'ADD' : 'REMOVE');
|
||||
}
|
||||
}
|
||||
}, [mode, inventory, fieldScanning, isOnline, onMatchFound, onMultipleMatches, onFieldCapture]);
|
||||
|
||||
return {
|
||||
mode,
|
||||
setMode,
|
||||
showScanner,
|
||||
setShowScanner,
|
||||
lastScanned,
|
||||
setLastScanned,
|
||||
isScannerReady,
|
||||
fieldScanning,
|
||||
setFieldScanning,
|
||||
onScanSuccess,
|
||||
onOCRMatch,
|
||||
preloadOCR
|
||||
};
|
||||
}
|
||||
1
frontend/package-lock.json
generated
1
frontend/package-lock.json
generated
@@ -9070,7 +9070,6 @@
|
||||
"version": "2.3.2",
|
||||
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
|
||||
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
|
||||
"dev": true,
|
||||
"hasInstallScript": true,
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user