Build [v.1.3.6]

This commit is contained in:
Daniel Bedeleanu
2026-04-11 17:14:22 +03:00
parent 775808506f
commit 704934165f
27 changed files with 738 additions and 685 deletions

View File

@@ -157,8 +157,8 @@ export default function AdminPage() {
};
const handleLogout = () => {
localStorage.removeItem('inventory_user');
window.location.href = '/';
import('@/lib/auth').then(m => m.clearAuth());
window.location.href = '/login';
};
return (

View File

@@ -78,7 +78,7 @@ export default function InventoryPage() {
setInventory(res);
// Sync local DB
await db.items.clear();
await db.items.bulkAdd(res);
await db.items.bulkPut(res);
} catch (err) {
console.error("Failed to load backend data", err);
}
@@ -189,11 +189,17 @@ export default function InventoryPage() {
inventory.some(i => i.category === c && i.name.toLowerCase().includes(searchQuery.toLowerCase()))
);
// Extract unique item types for suggestions
const existingTypes = Array.from(new Set(inventory.map(i => i.type).filter(Boolean))).sort() as string[];
if (!mounted) return null;
return (
<PageShell>
<div className="p-3 md:p-8 max-w-4xl mx-auto space-y-6">
<datalist id="existing-types">
{existingTypes.map(t => <option key={t} value={t} />)}
</datalist>
<header className="max-w-4xl mx-auto w-full mb-8">
<h1 className="text-2xl font-black flex items-center gap-3">
@@ -402,6 +408,7 @@ export default function InventoryPage() {
<label className="text-xs font-black text-slate-500 ml-1">Item Type</label>
<input
type="text"
list="existing-types"
value={editedItem.type || ''}
onChange={e => setEditedItem({...editedItem, type: e.target.value})}
className="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 px-4 text-sm outline-none text-slate-100"

View File

@@ -1,6 +1,6 @@
'use client';
import { useState, useEffect, useRef, memo } from 'react';
import { useState, useEffect, useRef } from 'react';
import { User, Shield, X, Lock, ChevronRight } from 'lucide-react';
import { inventoryApi } from '@/lib/api';
import { saveToken } from '@/lib/auth';
@@ -56,15 +56,8 @@ export default function LoginPage() {
password
});
console.log('[LoginPage] Login response received:', {
access_token: tokenResponse.access_token?.substring(0, 20),
user_id: tokenResponse.user_id,
username: tokenResponse.username
});
// Save JWT token and user info
saveToken(tokenResponse);
console.log('[LoginPage] saveToken called. Checking localStorage:', localStorage.getItem('inventory_token')?.substring(0, 20));
toast.success(`Welcome back, ${tokenResponse.username}`);
// Delay slightly to show toast then redirect

View File

@@ -13,6 +13,8 @@ export default function LogsPage() {
const [inventory, setInventory] = useState<Item[]>([]);
const [loading, setLoading] = useState(true);
const [searchQuery, setSearchQuery] = useState('');
const [filterAction, setFilterAction] = useState('ALL');
const [selectedLog, setSelectedLog] = useState<any | null>(null);
useEffect(() => {
loadData();
@@ -26,7 +28,7 @@ export default function LogsPage() {
setInventory(cached);
// Fetch fresh logs
const logs = await inventoryApi.getAuditLogs(50);
const logs = await inventoryApi.getAuditLogs(100);
setAuditLogs(logs);
} catch (err) {
console.error(err);
@@ -37,101 +39,242 @@ export default function LogsPage() {
const filteredLogs = auditLogs.filter(log => {
const itemName = inventory.find(i => i.id === log.target_item_id)?.name || '';
return (
itemName.toLowerCase().includes(searchQuery.toLowerCase()) ||
log.action.toLowerCase().includes(searchQuery.toLowerCase()) ||
(log.username || '').toLowerCase().includes(searchQuery.toLowerCase())
);
const matchesSearch = itemName.toLowerCase().includes(searchQuery.toLowerCase()) ||
log.action.toLowerCase().includes(searchQuery.toLowerCase()) ||
(log.username || '').toLowerCase().includes(searchQuery.toLowerCase());
const matchesAction = filterAction === 'ALL' || log.action.includes(filterAction);
return matchesSearch && matchesAction;
});
// Calculate stats
const totalCount = auditLogs.length;
const inCount = auditLogs.filter(l => l.action.includes('IN')).length;
const outCount = auditLogs.filter(l => l.action.includes('OUT') || l.action.includes('TRASH')).length;
const mostActiveUser = auditLogs.length > 0 ?
Object.entries(auditLogs.reduce((acc: any, curr) => {
acc[curr.username] = (acc[curr.username] || 0) + 1;
return acc;
}, {})).sort((a: any, b: any) => b[1] - a[1])[0]?.[0] : 'N/A';
return (
<PageShell>
<main className="p-4 md:p-8 max-w-4xl mx-auto space-y-8">
<header className="flex flex-col gap-4">
<div className="flex items-center gap-3">
<div className="p-3 bg-primary/10 rounded-2xl text-primary border border-primary/20">
<History size={24} />
<main className="p-4 md:p-8 max-w-5xl mx-auto space-y-12">
<header className="space-y-8">
<div className="flex flex-col sm:flex-row sm:items-center justify-between gap-6">
<div className="flex items-center gap-4">
<div className="p-4 bg-primary/10 rounded-[2rem] text-primary border border-primary/20 shadow-xl shadow-primary/5">
<History size={32} />
</div>
<div>
<h1 className="text-3xl font-black tracking-tight text-white italic">Audit Dashboard</h1>
<p className="text-xs text-slate-500 font-bold tracking-widest uppercase mt-1">Real-time Intervention Tracking</p>
</div>
</div>
<div>
<h1 className="text-2xl font-black tracking-tight text-white">Audit History</h1>
<p className="text-xs text-slate-500 font-bold">Centralized Transaction Logs</p>
<div className="flex gap-2">
<button
onClick={loadData}
className="px-4 py-2 bg-slate-900 border border-slate-800 text-slate-400 hover:text-white rounded-xl text-xs font-black transition-all active:scale-95"
>
Refresh
</button>
</div>
</div>
<div className="relative group">
<Search className="absolute left-4 top-1/2 -translate-y-1/2 text-slate-500 group-focus-within:text-primary transition-colors" size={18} />
<input
type="text"
placeholder="Search logs by item, action or user..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full bg-slate-900/50 border border-slate-800 focus:border-primary/50 rounded-2xl py-4 pl-12 pr-4 text-sm text-white placeholder:text-slate-600 outline-none transition-all shadow-inner"
/>
{/* Stats Grid */}
<div className="grid grid-cols-2 md:grid-cols-4 gap-4">
<div className="bg-slate-900/40 border border-slate-800/50 p-6 rounded-[2rem] space-y-2">
<p className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Total Events</p>
<p className="text-3xl font-black text-white tabular-nums">{totalCount}</p>
</div>
<div className="bg-slate-900/40 border border-slate-800/50 p-6 rounded-[2rem] space-y-2">
<p className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Flow In</p>
<p className="text-3xl font-black text-green-500 tabular-nums">{inCount}</p>
</div>
<div className="bg-slate-900/40 border border-slate-800/50 p-6 rounded-[2rem] space-y-2">
<p className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Flow Out</p>
<p className="text-3xl font-black text-rose-500 tabular-nums">{outCount}</p>
</div>
<div className="bg-slate-900/40 border border-slate-800/50 p-6 rounded-[2rem] space-y-2">
<p className="text-[10px] font-black text-slate-500 uppercase tracking-widest">Top Operator</p>
<p className="text-xl font-black text-primary truncate" title={mostActiveUser}>{mostActiveUser}</p>
</div>
</div>
<div className="flex flex-col md:flex-row gap-4">
<div className="relative group flex-1">
<Search className="absolute left-5 top-1/2 -translate-y-1/2 text-slate-500 group-focus-within:text-primary transition-colors" size={20} />
<input
type="text"
placeholder="Search logs by item name, user, or action details..."
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="w-full bg-slate-950/50 border border-slate-900 focus:border-primary/50 rounded-3xl py-5 pl-14 pr-6 text-sm text-white placeholder:text-slate-700 outline-none transition-all shadow-2xl"
/>
</div>
<div className="flex items-center gap-1.5 p-1.5 bg-slate-900/50 border border-slate-900 rounded-[1.5rem] overflow-x-auto no-scrollbar">
{['ALL', 'CHECK_IN', 'CHECK_OUT', 'TRASH', 'CREATE'].map(action => (
<button
key={action}
onClick={() => setFilterAction(action)}
className={cn(
"px-4 py-2.5 rounded-xl text-[10px] font-black transition-all whitespace-nowrap",
filterAction === action
? "bg-primary text-white shadow-lg shadow-primary/20"
: "text-slate-500 hover:text-slate-300 hover:bg-slate-800"
)}
>
{action.replace('_', ' ')}
</button>
))}
</div>
</div>
</header>
<section className="space-y-4">
{loading ? (
<div className="flex flex-col items-center justify-center p-20 text-slate-500 animate-pulse">
<History size={48} className="opacity-20 mb-4" />
<p className="text-xs font-black">Retrieving Logs From Cloud...</p>
<div className="flex flex-col items-center justify-center py-32 text-slate-600 gap-4 animate-pulse">
<div className="w-12 h-12 border-4 border-primary/20 border-t-primary rounded-full animate-spin" />
<p className="text-[10px] uppercase font-black tracking-widest">Securing Audit Stream...</p>
</div>
) : filteredLogs.length === 0 ? (
<div className="bg-slate-900/30 border border-slate-800 border-dashed rounded-[2.5rem] p-16 flex flex-col items-center justify-center text-center gap-4">
<div className="w-16 h-16 bg-slate-800 rounded-full flex items-center justify-center text-slate-600">
<Search size={32} />
<div className="bg-slate-900/20 border border-slate-800/50 border-dashed rounded-[3rem] py-24 flex flex-col items-center justify-center text-center gap-6">
<div className="w-20 h-20 bg-slate-900 rounded-[2rem] flex items-center justify-center text-slate-700 border border-slate-800 shadow-inner">
<Search size={40} />
</div>
<div>
<p className="text-lg font-bold text-slate-300">No transactions found</p>
<p className="text-sm text-slate-500">Try a different search term or check back later</p>
<p className="text-xl font-black text-slate-300">No interventions found</p>
<p className="text-xs text-slate-600 font-bold mt-2">Try adjusting your filters or search query</p>
</div>
</div>
) : (
<div className="grid gap-3">
<div className="grid gap-4">
{filteredLogs.map((log) => (
<div key={log.id} className="bg-slate-900/40 border border-slate-800/50 p-5 rounded-3xl flex items-center justify-between gap-4 hover:bg-slate-900/60 transition-colors group">
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2 mb-2">
<button
key={log.id}
onClick={() => setSelectedLog(log)}
className="w-full text-left bg-slate-900/30 border border-slate-800/40 p-6 rounded-[2.5rem] flex flex-col sm:flex-row sm:items-center justify-between gap-6 hover:bg-slate-900/60 hover:border-slate-700/50 transition-all group active:scale-[0.99] relative overflow-hidden"
>
<div className="flex-1 min-w-0 z-10">
<div className="flex items-center gap-3 mb-3">
<div className={cn(
"text-xs font-black px-2 py-0.5 rounded-md",
log.action.includes('CHECK_IN') ? "bg-green-500/10 text-green-500" :
(log.action.includes('TRASH') ? "bg-rose-500/10 text-rose-500" : "bg-amber-500/10 text-amber-500")
"text-[10px] font-black px-3 py-1 rounded-full border shadow-sm",
log.action.includes('CHECK_IN') ? "bg-green-500/5 text-green-500 border-green-500/20" :
(log.action.includes('TRASH') ? "bg-rose-500/5 text-rose-500 border-rose-500/20" :
(log.action.includes('CREATE') ? "bg-indigo-500/5 text-indigo-400 border-indigo-500/20" : "bg-amber-500/5 text-amber-500 border-amber-500/20"))
)}>
{log.action}
{log.action.replace('_', ' ')}
</div>
<div className="flex items-center gap-2">
<div className="w-1 h-1 rounded-full bg-slate-700" />
<span className="text-[10px] font-black text-slate-500 uppercase tracking-tight">{log.username || 'System'}</span>
</div>
<span className="text-xs font-bold text-slate-600">by</span>
<span className="text-xs font-black text-slate-400">{log.username || 'System'}</span>
</div>
<div className="flex items-center gap-2">
<span className="text-base font-bold text-slate-100 group-hover:text-primary transition-colors">
{inventory.find(i => i.id === log.target_item_id)?.name || `Item #${log.target_item_id}`}
</span>
</div>
<div className="flex items-center gap-4 mt-3">
<div className="text-xs text-slate-600 font-mono flex items-center gap-1.5">
<div className="w-1 h-1 rounded-full bg-slate-700" />
{new Date(log.timestamp).toLocaleString()}
<h3 className="text-lg font-black text-white group-hover:text-primary transition-colors truncate">
{inventory.find(i => i.id === log.target_item_id)?.name || `Item #${log.target_item_id}`}
</h3>
<div className="flex flex-wrap items-center gap-4 mt-4">
<div className="text-[10px] text-slate-500 font-mono flex items-center gap-2 bg-slate-950/50 px-3 py-1.5 rounded-xl border border-slate-800/50">
<div className="w-1.5 h-1.5 rounded-full bg-primary/40" />
{new Date(log.timestamp).toLocaleDateString()} · {new Date(log.timestamp).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })}
</div>
{log.details && (
<span className="text-xs bg-slate-800/50 text-slate-500 px-3 py-1 rounded-full border border-slate-700/50 font-mono">
{log.details}
</span>
<div className="text-[10px] font-bold text-slate-400 truncate max-w-[200px] italic opacity-60">
"{log.details}"
</div>
)}
</div>
</div>
<div className="text-right">
<p className={cn(
"text-2xl font-black tabular-nums group-hover:scale-110 transition-transform",
log.quantity_change > 0 ? "text-green-400" : "text-rose-400"
<div className="shrink-0 text-right z-10">
<div className={cn(
"text-4xl font-black tabular-nums group-hover:scale-110 transition-transform flex items-center justify-end gap-1",
log.quantity_change > 0 ? "text-green-500" : (log.quantity_change < 0 ? "text-rose-500" : "text-indigo-400")
)}>
{log.quantity_change > 0 ? '+' : ''}{log.quantity_change}
</p>
{log.quantity_change > 0 ? '+' : ''}{log.quantity_change === 0 ? '±' : log.quantity_change}
</div>
<p className="text-[10px] font-black text-slate-600 uppercase tracking-widest mt-1">Quantity</p>
</div>
</div>
{/* Glass background effect */}
<div className="absolute inset-x-0 bottom-0 h-1 bg-gradient-to-r from-transparent via-primary/5 to-transparent opacity-0 group-hover:opacity-100 transition-opacity" />
</button>
))}
</div>
)}
</section>
{/* Selected Log Modal */}
{selectedLog && (
<div className="fixed inset-0 z-[100] flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-xl animate-in fade-in duration-300">
<div className="bg-slate-900 border border-slate-800 rounded-[3rem] p-10 max-w-lg w-full shadow-2xl space-y-8 animate-in zoom-in-95 duration-300">
<div className="flex justify-between items-start">
<div className="space-y-1">
<div className={cn(
"text-[10px] font-black px-4 py-1.5 rounded-full border inline-block",
selectedLog.action.includes('CHECK_IN') ? "bg-green-500/10 text-green-500 border-green-500/30" :
(selectedLog.action.includes('TRASH') ? "bg-rose-500/10 text-rose-500 border-rose-500/30" : "bg-amber-500/10 text-amber-500 border-amber-500/30")
)}>
{selectedLog.action}
</div>
<h2 className="text-3xl font-black text-white tracking-tight leading-tight pt-2">
{inventory.find(i => i.id === selectedLog.target_item_id)?.name || `Item #${selectedLog.target_item_id}`}
</h2>
</div>
<button onClick={() => setSelectedLog(null)} className="p-3 hover:bg-slate-800 rounded-2xl text-slate-500 transition-colors border border-slate-800">
<X size={24} />
</button>
</div>
<div className="grid grid-cols-2 gap-6">
<div className="space-y-1 bg-slate-950/50 p-4 rounded-2xl border border-slate-800">
<p className="text-[10px] font-black text-slate-600 uppercase">Operator</p>
<p className="text-sm font-black text-white">{selectedLog.username || 'System Profile'}</p>
</div>
<div className="space-y-1 bg-slate-950/50 p-4 rounded-2xl border border-slate-800">
<p className="text-[10px] font-black text-slate-600 uppercase">Delta</p>
<p className={cn(
"text-xl font-black",
selectedLog.quantity_change > 0 ? "text-green-500" : "text-rose-500"
)}>
{selectedLog.quantity_change > 0 ? '+' : ''}{selectedLog.quantity_change} Units
</p>
</div>
</div>
<div className="space-y-4">
<div className="space-y-1">
<p className="text-[10px] font-black text-slate-600 uppercase">Timestamp</p>
<p className="text-sm font-bold text-slate-300 bg-slate-800/30 p-4 rounded-2xl border border-slate-800/50">
{new Date(selectedLog.timestamp).toLocaleString(undefined, { dateStyle: 'full', timeStyle: 'medium' })}
</p>
</div>
{selectedLog.details && (
<div className="space-y-1">
<p className="text-[10px] font-black text-slate-600 uppercase">Intervention Details</p>
<div className="bg-primary/5 text-primary/80 p-6 rounded-[2rem] border border-primary/10 text-sm font-bold leading-relaxed italic">
"{selectedLog.details}"
</div>
</div>
)}
</div>
<button
onClick={() => setSelectedLog(null)}
className="w-full bg-slate-800 hover:bg-slate-700 text-white font-black py-5 rounded-[2rem] transition-all active:scale-95 border border-slate-700"
>
Close Insights
</button>
</div>
</div>
)}
</main>
</PageShell>
);

View File

@@ -71,17 +71,25 @@ export default function Home() {
const [categories, setCategories] = useState<any[]>([]);
useEffect(() => {
if (!localStorage.getItem('inventory_token')) {
window.location.href = '/login';
return;
}
setMounted(true);
const savedUser = localStorage.getItem('inventory_user');
if (savedUser) {
setCurrentUser(JSON.parse(savedUser));
}
// Initial categories fetch
inventoryApi.getCategories().then(c => setCategories(c)).catch(() => {});
}, []);
useEffect(() => {
if (!localStorage.getItem('inventory_token')) {
window.location.href = '/login';
return;
}
setMounted(true);
setIsOnline(navigator.onLine);
const handleOnline = () => {
@@ -366,11 +374,18 @@ export default function Home() {
);
});
// Extract unique item types for suggestions
const existingTypes = Array.from(new Set(inventory.map(i => i.type).filter(Boolean))).sort() as string[];
if (!mounted) return null;
return (
<PageShell>
<div className="p-3 md:p-8 overflow-x-hidden w-full">
{/* Search datalist for types */}
<datalist id="existing-types">
{existingTypes.map(t => <option key={t} value={t} />)}
</datalist>
{/* Header */}
<header className="flex flex-col sm:flex-row justify-between sm:items-center gap-4 mb-6 w-full max-w-4xl mx-auto px-1">
@@ -487,7 +502,7 @@ export default function Home() {
className="w-full h-16 rounded-[1.5rem] bg-slate-900/50 border border-slate-800 flex items-center justify-center gap-3 group hover:border-primary/40 transition-all font-bold"
>
<Sparkles size={18} className="text-primary group-hover:scale-110 transition-transform" />
<span className="text-sm">Add New Item (AI Onboarding)</span>
<span className="text-sm">Add NEW Item<br />(AI Onboarding)</span>
</button>
</div>
)}
@@ -498,6 +513,7 @@ export default function Home() {
{showOnboarding && (
<AIOnboarding
categories={categories}
inventory={inventory}
onCancel={() => setShowOnboarding(false)}
onComplete={handleOnboardingComplete}
/>
@@ -587,6 +603,7 @@ export default function Home() {
<label className="text-xs font-black text-slate-500 ml-1">Item Type (e.g. SFP, Patch Cord)</label>
<input
type="text"
list="existing-types"
value={editedItem.type || ''}
onChange={e => setEditedItem({...editedItem, type: e.target.value})}
className="w-full bg-slate-950 border border-slate-800 rounded-xl py-3 px-4 text-sm outline-none text-slate-100"

View File

@@ -9,12 +9,16 @@ interface AIOnboardingProps {
onCancel: () => void;
onComplete: (itemData: any) => void;
categories: any[];
inventory: any[];
}
export default function AIOnboarding({ onCancel, onComplete, categories }: AIOnboardingProps) {
export default function AIOnboarding({ onCancel, onComplete, categories, inventory }: AIOnboardingProps) {
const [image, setImage] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
const [extractedData, setExtractedData] = useState<any>(null);
// Extract unique item types for suggestions
const existingTypes = Array.from(new Set(inventory.map(i => i.type).filter(Boolean))).sort() as string[];
const cameraInputRef = useRef<HTMLInputElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
@@ -201,10 +205,14 @@ export default function AIOnboarding({ onCancel, onComplete, categories }: AIOnb
</div>
<input
value={extractedData.type || ''}
list="onboarding-types"
onChange={(e) => setExtractedData({...extractedData, type: e.target.value})}
className="bg-transparent w-full font-bold outline-none text-slate-200"
placeholder="e.g. SFP+"
/>
<datalist id="onboarding-types">
{existingTypes.map(t => <option key={t} value={t} />)}
</datalist>
</div>
</div>

View File

@@ -161,8 +161,8 @@ export default function AdminOverlay({
<p className="text-xs text-slate-500">Exit current session and return to identity check.</p>
<button
onClick={() => {
localStorage.removeItem('inventory_user');
window.location.reload();
import('@/lib/auth').then(m => m.clearAuth());
window.location.href = '/login';
}}
className="w-full bg-rose-500/10 hover:bg-rose-500/20 text-rose-500 border border-rose-500/20 font-black py-3 rounded-xl transition-all flex items-center justify-center gap-2"
>

View File

@@ -68,7 +68,7 @@ export default function BottomNav({
{/* Logout */}
<button
onClick={() => {
localStorage.removeItem('inventory_user');
import('@/lib/auth').then(m => m.clearAuth());
window.location.href = '/login';
}}
className="flex flex-col items-center gap-1 hover:text-rose-500 transition-colors"

View File

@@ -2,7 +2,7 @@
import { useEffect, useRef, useState } from 'react';
import { Html5Qrcode, Html5QrcodeSupportedFormats } from 'html5-qrcode';
import { Camera, RefreshCw, XCircle, Type, Search } from 'lucide-react';
import { RefreshCw, XCircle, Search } from 'lucide-react';
import { createWorker } from 'tesseract.js';
import { toast } from 'react-hot-toast';
@@ -16,8 +16,8 @@ export default function Scanner({ onScanSuccess, onOCRMatch, paused }: ScannerPr
const html5QrCodeRef = useRef<Html5Qrcode | null>(null);
const [isStarted, setIsStarted] = useState(false);
const [error, setError] = useState<string | null>(null);
const [isOCRMode, setIsOCRMode] = useState(false);
const [ocrProcessing, setOcrProcessing] = useState(false);
const [countdown, setCountdown] = useState(4);
const [zoom, setZoom] = useState(1);
const [maxZoom, setMaxZoom] = useState(1);
const [hasZoom, setHasZoom] = useState(false);
@@ -41,8 +41,8 @@ export default function Scanner({ onScanSuccess, onOCRMatch, paused }: ScannerPr
}
const config = {
fps: 15, // Lower FPS for stability
qrbox: { width: 280, height: 280 },
fps: 15,
qrbox: { width: 320, height: 320 },
aspectRatio: 1.0,
formatsToSupport: [
Html5QrcodeSupportedFormats.QR_CODE,
@@ -52,7 +52,6 @@ export default function Scanner({ onScanSuccess, onOCRMatch, paused }: ScannerPr
Html5QrcodeSupportedFormats.UPC_A,
Html5QrcodeSupportedFormats.DATAMATRIX
],
// Simplified constraints for maximum compatibility
videoConstraints: {
facingMode: "environment"
}
@@ -67,7 +66,6 @@ export default function Scanner({ onScanSuccess, onOCRMatch, paused }: ScannerPr
() => {} // Ignore frame errors
);
// Check for zoom capability via video track
const video = document.querySelector(`#${scannerId} video`) as HTMLVideoElement;
const track = (video?.srcObject as MediaStream)?.getVideoTracks()[0];
const caps = track?.getCapabilities() as any;
@@ -103,20 +101,26 @@ export default function Scanner({ onScanSuccess, onOCRMatch, paused }: ScannerPr
.catch(e => console.error("Stop failed", e));
}
};
}, [paused, onScanSuccess]); // Minimal deps
}, [paused, onScanSuccess]);
// Separate effect for OCR interval to avoid restarting scanner
// Automated OCR Countdown Timer
useEffect(() => {
let intervalId: any;
if (isOCRMode && isStarted && !paused) {
intervalId = setInterval(() => {
handleOCR();
}, 5000); // 5 seconds is safer
if (!isStarted || paused || isSelecting || ocrProcessing) {
return;
}
return () => {
if (intervalId) clearInterval(intervalId);
};
}, [isOCRMode, isStarted, paused]);
const timer = setInterval(() => {
setCountdown(prev => {
if (prev <= 1) {
handleOCR();
return 4; // Reset to 4
}
return prev - 1;
});
}, 1000);
return () => clearInterval(timer);
}, [isStarted, paused, isSelecting, ocrProcessing]);
const handleOCR = async () => {
if (ocrProcessing) return;
@@ -126,11 +130,9 @@ export default function Scanner({ onScanSuccess, onOCRMatch, paused }: ScannerPr
if (!video) return;
const canvas = document.createElement('canvas');
const vWidth = video.videoWidth || 1280;
const vHeight = video.videoHeight || 720;
// Digital Zoom/Crop: 60% of center
const cropFactor = 0.6;
const sw = vWidth * cropFactor;
const sh = vHeight * cropFactor;
@@ -140,48 +142,36 @@ export default function Scanner({ onScanSuccess, onOCRMatch, paused }: ScannerPr
canvas.width = 1200;
canvas.height = (sh / sw) * 1200;
console.log(`OCR Capture: ${vWidth}x${vHeight} -> ${canvas.width}x${canvas.height}`);
const ctx = canvas.getContext('2d');
if (ctx) {
// More balanced filter for both paper and metal labels
ctx.filter = 'grayscale(100%) contrast(180%) brightness(105%)';
ctx.drawImage(video, sx, sy, sw, sh, 0, 0, canvas.width, canvas.height);
}
// Timeout protection for worker initialization (especially when offline for first run)
const workerPromise = createWorker('eng');
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("OCR Engine timeout - check internet for first run")), 8000));
const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(new Error("OCR Engine timeout")), 8000));
const worker = await Promise.race([workerPromise, timeoutPromise]) as any;
const dataUrl = canvas.toDataURL('image/jpeg', 0.85);
// DIAGNOSTIC: Set captured image early so user can see what was sent to AI
setCapturedImage(dataUrl);
const result = await worker.recognize(dataUrl);
console.log("OCR Result Size:", result.data?.text?.length);
const data = result.data;
// FALLBACK: If we have text but no word coordinates
if (data && data.text && (!data.words || data.words.length === 0)) {
console.log("Fallback to direct match");
onOCRMatch(data.text);
onOCRMatch?.(data.text);
await worker.terminate();
setCapturedImage(null);
return;
}
if (!data || !data.words || data.words.length === 0) {
console.warn("OCR produced no text or words.");
toast.error("Label not readable. Try better light or zoom.");
await worker.terminate();
setCapturedImage(null);
return;
}
// Store words with their bounding boxes
const words = data.words.map((w: any) => ({
text: w.text,
bbox: w.bbox
@@ -192,155 +182,156 @@ export default function Scanner({ onScanSuccess, onOCRMatch, paused }: ScannerPr
await worker.terminate();
} catch (err) {
console.error("OCR failed", err);
toast.error("OCR selection failed");
} finally {
setOcrProcessing(false);
}
};
const handleWordSelect = (text: string) => {
onOCRMatch(text);
// Reset selection state
onOCRMatch?.(text);
setIsSelecting(false);
setCapturedImage(null);
setDetectedWords([]);
setCountdown(4); // Restart countdown
};
const cn = (...classes: any[]) => classes.filter(Boolean).join(' ');
return (
<div className="relative w-full max-w-[340px] mx-auto overflow-hidden rounded-[2.5rem] shadow-2xl bg-black border-[3px] border-slate-800 shadow-blue-500/10">
<div className="absolute inset-0 z-10 pointer-events-none flex items-center justify-center">
<div className="w-[280px] h-[280px] border-2 border-primary/50 rounded-3xl relative">
<div className="absolute top-0 left-0 w-8 h-8 border-t-4 border-l-4 border-primary rounded-tl-xl" />
<div className="absolute top-0 right-0 w-8 h-8 border-t-4 border-r-4 border-primary rounded-tr-xl" />
<div className="absolute bottom-0 left-0 w-8 h-8 border-b-4 border-l-4 border-primary rounded-bl-xl" />
<div className="absolute bottom-0 right-0 w-8 h-8 border-b-4 border-r-4 border-primary rounded-br-xl" />
<div className="absolute top-0 left-0 right-0 h-0.5 bg-primary/50 shadow-[0_0_15px_rgba(59,130,246,0.8)] animate-scan-fast" />
</div>
</div>
<div id={scannerId} className="w-full aspect-square bg-slate-900" />
<div className="absolute top-4 right-4 z-30 flex gap-2">
<button
onClick={() => setIsOCRMode(!isOCRMode)}
className={cn(
"p-2 rounded-xl border backdrop-blur-md transition-all",
isOCRMode ? "bg-primary border-primary text-white shadow-lg" : "bg-slate-900/50 border-slate-700 text-slate-300"
)}
>
<Type size={18} />
</button>
</div>
{/* Selection UI */}
{isSelecting && capturedImage && (
<div className="absolute inset-0 z-50 bg-slate-950 flex flex-col">
<div className="relative flex-1 bg-black flex items-center justify-center overflow-hidden">
<img src={capturedImage} className="max-w-full max-h-full object-contain" id="ocr-canvas-preview" />
{/* Render Bounding Boxes */}
<div className="absolute inset-0 flex items-center justify-center">
<div className="relative" style={{ width: '100%', height: '100%' }}>
{detectedWords.map((w, i) => (
<button
key={i}
onClick={() => handleWordSelect(w.text)}
className="absolute border border-primary bg-primary/20 rounded-sm active:bg-primary/50 transition-colors pointer-events-auto"
style={{
left: `${(w.bbox.x0 / 1600) * 100}%`,
top: `${(w.bbox.y0 / (1600 * (9/16))) * 100}%`, // Assuming 16:9 ratio, this may need adjustment based on real canvas aspect
width: `${((w.bbox.x1 - w.bbox.x0) / 1600) * 100}%`,
height: `${((w.bbox.y1 - w.bbox.y0) / (1600 * (9/16))) * 100}%`,
}}
/>
))}
</div>
</div>
</div>
<div className="p-6 bg-slate-900 border-t border-slate-800 flex flex-col gap-4">
<p className="text-sm font-bold text-center text-primary">Tap the correct text on the label</p>
<button
onClick={() => { setIsSelecting(false); setCapturedImage(null); }}
className="w-full py-4 bg-slate-800 text-white rounded-2xl font-bold text-xs"
>
Cancel & Rescan
</button>
<div className="w-full max-w-md mx-auto flex flex-col gap-6">
{/* Video Viewport Area */}
<div className="relative w-full aspect-square overflow-hidden rounded-[2.5rem] shadow-2xl bg-black border-[3px] border-slate-800 shadow-blue-500/10">
<div className="absolute inset-0 z-10 pointer-events-none flex items-center justify-center">
<div className="w-[320px] h-[320px] border-2 border-primary/50 rounded-3xl relative">
<div className="absolute top-0 left-0 w-8 h-8 border-t-4 border-l-4 border-primary rounded-tl-xl" />
<div className="absolute top-0 right-0 w-8 h-8 border-t-4 border-r-4 border-primary rounded-tr-xl" />
<div className="absolute bottom-0 left-0 w-8 h-8 border-b-4 border-l-4 border-primary rounded-bl-xl" />
<div className="absolute bottom-0 right-0 w-8 h-8 border-b-4 border-r-4 border-primary rounded-br-xl" />
{isStarted && !paused && !isSelecting && (
<div className="absolute top-0 left-0 right-0 h-0.5 bg-primary/50 shadow-[0_0_15px_rgba(59,130,246,0.8)] animate-scan-fast" />
)}
</div>
</div>
)}
{isOCRMode && (
<div className="absolute inset-0 z-20 pointer-events-none border-2 border-primary/30 rounded-[2rem] animate-pulse" />
)}
<div id={scannerId} className="w-full aspect-square bg-slate-900" />
{!isStarted && !error && (
<div className="absolute inset-0 z-20 flex flex-col items-center justify-center bg-slate-900 text-slate-300 gap-4">
<RefreshCw className="w-8 h-8 animate-spin text-primary" />
<p className="text-sm font-medium">Initializing camera...</p>
</div>
)}
{error && (
<div className="absolute inset-0 z-20 flex flex-col items-center justify-center bg-slate-900 text-slate-300 px-8 text-center gap-4">
<XCircle className="w-10 h-10 text-red-500" />
<div>
<p className="font-bold text-white">Camera Error</p>
<p className="text-xs text-slate-400 mt-1">{error}</p>
</div>
<button
onClick={() => window.location.reload()}
className="mt-4 px-6 py-2 bg-slate-800 rounded-full text-sm font-bold hover:bg-slate-700 transition-colors"
>
Try Again
</button>
</div>
)}
<div className="absolute bottom-6 left-0 right-0 z-30 flex flex-col items-center gap-4 px-6">
{hasZoom && (
<button
onClick={async () => {
// Cycle through: 1x -> 2x -> Max/2 -> Max
let nextZoom = 1;
if (zoom === 1) nextZoom = Math.min(2, maxZoom);
else if (zoom < maxZoom / 2) nextZoom = Math.floor(maxZoom / 2);
else if (zoom < maxZoom) nextZoom = maxZoom;
else nextZoom = 1;
const video = document.querySelector(`#${scannerId} video`) as HTMLVideoElement;
const track = (video?.srcObject as MediaStream)?.getVideoTracks()[0];
if (track) {
await track.applyConstraints({ advanced: [{ zoom: nextZoom }] as any });
setZoom(nextZoom);
}
}}
className="bg-slate-900/90 backdrop-blur-md border border-slate-700 text-white w-14 h-14 rounded-full flex flex-col items-center justify-center shadow-2xl active:scale-95 transition-transform"
>
<span className="text-xs font-black">{zoom.toFixed(1)}x</span>
<span className="text-xs text-primary font-bold">Zoom</span>
</button>
)}
{isOCRMode ? (
<button
onClick={handleOCR}
disabled={ocrProcessing}
className={cn(
"w-full py-4 rounded-2xl font-bold text-sm flex items-center justify-center gap-3 shadow-2xl transition-all active:scale-95 border border-white/10",
ocrProcessing ? "bg-slate-800 text-slate-500" : "bg-primary text-white"
)}
>
{ocrProcessing ? <RefreshCw className="animate-spin" size={18} /> : <Search size={18} />}
{ocrProcessing ? "Analyzing..." : "Find by Label (OCR)"}
</button>
) : (
<div className="bg-black/40 backdrop-blur-sm py-2 px-6 rounded-full border border-white/5">
<p className="text-xs text-center text-slate-300 font-bold">
Center barcode for auto-scan
</p>
{/* Selection UI */}
{isSelecting && capturedImage && (
<div className="absolute inset-0 z-50 bg-slate-950 flex flex-col">
<div className="relative flex-1 bg-black flex items-center justify-center overflow-hidden">
<img src={capturedImage} className="max-w-full max-h-full object-contain" id="ocr-canvas-preview" />
<div className="absolute inset-0 flex items-center justify-center">
<div className="relative" style={{ width: '100%', height: '100%' }}>
{detectedWords.map((w, i) => (
<button
key={i}
onClick={() => handleWordSelect(w.text)}
className="absolute border border-primary bg-primary/20 rounded-sm active:bg-primary/50 transition-colors pointer-events-auto"
style={{
left: `${(w.bbox.x0 / 1600) * 100}%`,
top: `${(w.bbox.y0 / (1600 * (9/16))) * 100}%`,
width: `${((w.bbox.x1 - w.bbox.x0) / 1600) * 100}%`,
height: `${((w.bbox.y1 - w.bbox.y0) / (1600 * (9/16))) * 100}%`,
}}
/>
))}
</div>
</div>
</div>
<div className="p-6 bg-slate-900 border-t border-slate-800 flex flex-col gap-4">
<p className="text-sm font-bold text-center text-primary">Tap the correct text on the label</p>
<button
onClick={() => { setIsSelecting(false); setCapturedImage(null); setCountdown(4); }}
className="w-full py-4 bg-slate-800 text-white rounded-2xl font-bold text-xs"
>
Cancel & rescans
</button>
</div>
</div>
)}
{!isStarted && !error && (
<div className="absolute inset-0 z-20 flex flex-col items-center justify-center bg-slate-900 text-slate-300 gap-4">
<RefreshCw className="w-8 h-8 animate-spin text-primary" />
<p className="text-sm font-medium">Initializing camera...</p>
</div>
)}
{error && (
<div className="absolute inset-0 z-20 flex flex-col items-center justify-center bg-slate-900 text-slate-300 px-8 text-center gap-4">
<XCircle className="w-10 h-10 text-red-500" />
<div>
<p className="font-bold text-white">Camera Error</p>
<p className="text-xs text-slate-400 mt-1">{error}</p>
</div>
<button
onClick={() => window.location.reload()}
className="mt-4 px-6 py-2 bg-slate-800 rounded-full text-sm font-bold hover:bg-slate-700 transition-colors"
>
Try Again
</button>
</div>
)}
</div>
{/* External Controls Area */}
<div className="flex flex-col gap-4 bg-slate-900/40 p-6 rounded-[2rem] border border-slate-800/50">
<div className="flex items-center gap-4 w-full">
{hasZoom && (
<button
onClick={async () => {
let nextZoom = 1;
if (zoom === 1) nextZoom = Math.min(2, maxZoom);
else if (zoom < maxZoom / 2) nextZoom = Math.floor(maxZoom / 2);
else if (zoom < maxZoom) nextZoom = maxZoom;
else nextZoom = 1;
const video = document.querySelector(`#${scannerId} video`) as HTMLVideoElement;
const track = (video?.srcObject as MediaStream)?.getVideoTracks()[0];
if (track) {
await track.applyConstraints({ advanced: [{ zoom: nextZoom }] as any });
setZoom(nextZoom);
}
}}
className="h-16 px-6 bg-slate-800 hover:bg-slate-700 border border-slate-700 text-white rounded-2xl flex flex-col items-center justify-center shadow-lg transition-all active:scale-95"
>
<span className="text-xs font-black">{zoom.toFixed(1)}x</span>
<span className="text-[10px] text-primary font-bold uppercase">Zoom</span>
</button>
)}
<div className="flex-1 h-16 bg-slate-800/50 border border-slate-700 rounded-2xl flex items-center justify-center gap-3 px-4 relative overflow-hidden">
{ocrProcessing ? (
<>
<RefreshCw className="animate-spin text-primary" size={20} />
<span className="text-sm font-bold text-slate-200">Analyzing labels...</span>
</>
) : (
<>
<Search className={cn("text-slate-500", !isStarted && "opacity-20")} size={20} />
<div className="flex flex-col">
<span className="text-[10px] text-slate-500 font-bold leading-none uppercase">Label Scanning</span>
<span className="text-sm font-black text-primary leading-tight">
{countdown === 0 ? "Scanning..." : `Next scan in ${countdown}s`}
</span>
</div>
</>
)}
{/* Visual Progress Bar */}
<div
className="absolute bottom-0 left-0 h-1 bg-primary/30 transition-all duration-1000 ease-linear"
style={{ width: `${((4 - countdown) / 4) * 100}%` }}
/>
</div>
</div>
<div className="w-full flex justify-center items-center gap-2">
<div className="w-1.5 h-1.5 rounded-full bg-green-500 animate-pulse" />
<p className="text-[10px] text-slate-500 font-bold">
Barcode auto-scan active
</p>
</div>
</div>
</div>
);

View File

@@ -21,18 +21,15 @@ export const getBackendUrl = () => {
* [C-01] Axios instance cu JWT Bearer token în header
* și interceptor pentru 401 Unauthorized (token expired)
*/
const axiosInstance = axios.create({
baseURL: getBackendUrl()
});
const axiosInstance = axios.create({});
axiosInstance.interceptors.request.use((config) => {
if (!config.baseURL) {
config.baseURL = getBackendUrl(); // called at request time — always correct
}
const token = getToken();
console.log('[API] Request interceptor - token exists:', !!token, 'URL:', config.url);
if (token) {
config.headers.Authorization = `Bearer ${token}`;
console.log('[API] Authorization header set');
} else {
console.warn('[API] No token found in localStorage');
}
return config;
}, (error) => Promise.reject(error));
@@ -43,7 +40,7 @@ axiosInstance.interceptors.response.use(
// [L-01] Handle 401 Unauthorized — token expired
if (error.response?.status === 401) {
clearAuth();
if (typeof window !== 'undefined') {
if (typeof window !== 'undefined' && !window.location.pathname.includes('/login')) {
window.location.href = '/login';
}
}

View File

@@ -24,19 +24,12 @@ export interface AuthUser {
* Save JWT token to localStorage
*/
export const saveToken = (token: AuthToken): void => {
console.log('[Auth] saveToken called with token:', {
access_token: token.access_token?.substring(0, 20) + '...',
user_id: token.user_id,
username: token.username,
role: token.role
});
localStorage.setItem(TOKEN_KEY, token.access_token);
localStorage.setItem(USER_KEY, JSON.stringify({
id: token.user_id,
username: token.username,
role: token.role
}));
console.log('[Auth] Token saved to localStorage. TOKEN_KEY:', TOKEN_KEY);
};
/**

View File

@@ -12,6 +12,8 @@ export interface Item {
min_quantity: number;
image_url?: string;
labels_data?: string;
serial_number?: string;
type?: string;
}
export interface PendingOperation {

View File

@@ -53,7 +53,7 @@ export const fetchAndCacheItems = async () => {
const items = await inventoryApi.getItems();
// Update local cache
await db.items.clear();
await db.items.bulkAdd(items);
await db.items.bulkPut(items);
return items;
} catch (error) {
console.error('Failed to fetch items, using cache:', error);