refactor: extract useStockAdjustment hook from page.tsx

This commit is contained in:
2026-04-19 12:23:06 +03:00
parent 5b8c6039ef
commit f5441a7ca7
2 changed files with 103 additions and 46 deletions

View File

@@ -5,6 +5,7 @@ import { db, Item } from '@/lib/db';
import { inventoryApi } from '@/lib/api';
import { fetchAndCacheItems, syncOfflineOperations } from '@/lib/sync';
import { useScanner } from '@/hooks/useScanner';
import { useStockAdjustment } from '@/hooks/useStockAdjustment';
import Scanner from '@/components/Scanner';
import AIOnboarding from '@/components/AIOnboarding';
import PageShell from '@/components/PageShell';
@@ -53,8 +54,6 @@ export default function Home() {
const [boxMatches, setBoxMatches] = useState<Item[]>([]);
const [isEditing, setIsEditing] = 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 [syncing, setSyncing] = useState(false);
const [currentUser, setCurrentUser] = useState<any | null>(null);
@@ -91,6 +90,22 @@ export default function Home() {
}
});
const {
adjustQty,
setAdjustQty,
adjustType,
setAdjustType,
handleAdjustStock
} = useStockAdjustment({
selectedItem,
isOnline,
currentUser,
onAdjustmentComplete: () => {
setSelectedItem(null);
},
onInventoryUpdate: setInventory
});
useEffect(() => {
if (!localStorage.getItem('inventory_token')) {
window.location.href = '/login';
@@ -291,50 +306,6 @@ export default function Home() {
}
};
const handleAdjustStock = async () => {
if (!selectedItem) return;
const toastId = toast.loading("Processing...");
try {
const finalAdjustQty = adjustQty;
const newQty = selectedItem.quantity + (adjustType === 'ADD' ? adjustQty : -adjustQty);
// 1. Create a unique ID for this operation to prevent double-counting on server
const operationId = crypto.randomUUID();
// 2. Queue local operation
const opType = adjustType === 'ADD' ? 'CHECK_IN' : (adjustType === 'TRASH' ? 'TRASH' : 'CHECK_OUT');
await db.pendingOperations.add({
type: opType as any,
barcode: selectedItem.barcode,
quantity: finalAdjustQty,
timestamp: Date.now(),
synced: 0,
// We add this to our DB even if it doesn't have it yet, Dexie handles it
uuid: operationId
} as any);
// 3. Update local UI & DB
await db.items.update(selectedItem.id!, { quantity: newQty });
setInventory(prev => prev.map(i => i.id === selectedItem.id ? { ...i, quantity: newQty } : i));
// 4. Trigger Sync
if (isOnline) {
await handleSync();
toast.success("Inventory updated & synced", { id: toastId });
} else {
toast.success("Saved locally (Offline)", { id: toastId });
}
setSelectedItem(null);
setAdjustQty(1);
} catch (error: any) {
console.error("Adjustment failure:", error);
toast.error("Error saving operation", { id: toastId });
}
};
const [searchQuery, setSearchQuery] = useState('');