import { useState, useEffect } from "react"; import { Card, CardContent, CardHeader, CardTitle } from "./ui/card"; import { toast } from "sonner"; import { Button } from "./ui/button"; import { Badge } from "./ui/badge"; import { Input } from "./ui/input"; import { Progress } from "./ui/progress"; import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs"; import { Package, Search, Plus, ShoppingCart, Pill, Wrench, Fuel, Fish, CheckCircle, Clock, XCircle, Trash2, RefreshCw, Eye, Droplet, } from "lucide-react"; import { User, Farm, FishInventoryBatch } from "../types"; import AllocateFishToTank from "./AllocateFishToTank"; import { apiGet } from "../api"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "./ui/dialog"; import { Label } from "./ui/label"; import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue, } from "./ui/select"; import { BatchHealthModal } from "./tanks/modals/BatchHealthModal"; import HarvestedInventoryView from "./sales/HarvestedInventoryView"; import Combobox, { type ComboboxItem } from "./Combobox"; import { getFishTypes } from "../services/fishTypesApi"; import { FEEDING_TASK_COMPLETED_EVENT } from "../services/taskApi"; import { createFishPurchaseOrder, createProcurementSupplier, getProcurementSuppliers, } from "../services/procurementApi"; import { getFeedInventory, createFeed, getFeedByFoodType, getBatches, getBatchById, allocateBatch, deleteFeed, getMedicineInventory, getMedicineInventoryTotal, deleteMedicineBatch, addMedicineStock, } from "../api/inventoryApi"; // Types interface FeedItem { id: string; name: string; quantity: number; unit: string; foodType?: string; [key: string]: unknown; } interface MedicineInventoryBatch { id: string; farmId: string; medicineName: string; company: string; batchNumber: string; quantity: number; mlPerUnit?: number; unit: string; reorderLevel: number; expiryDate?: string; status?: string; notes?: string; } interface MedicineTotalItem { medicineName: string; totalQuantity: number; unit: string; } interface MedicineTypeItem { id: string; name: string; arabicName?: string; category?: string; description?: string; } interface InventoryProps { user: User; selectedFarm: Farm | null; } type ResourceType = "feed" | "medicine" | "fish_batch"; // Component export default function Inventory({ user, selectedFarm }: InventoryProps) { const [searchQuery, setSearchQuery] = useState(""); // Fish batches - API-driven const [fishBatches, setFishBatches] = useState([]); // Allocation modal const [selectedBatch, setSelectedBatch] = useState( null, ); const [showAllocateModal, setShowAllocateModal] = useState(false); // Feed inventory - API-driven const [feedInventory, setFeedInventory] = useState([]); const [medicineInventory, setMedicineInventory] = useState< MedicineInventoryBatch[] >([]); const [medicineTotals, setMedicineTotals] = useState([]); // Tanks for allocation const [tanks, setTanks] = useState([]); const [isTanksLoading, setIsTanksLoading] = useState(false); // Food Types + Add Resources const [foodTypes, setFoodTypes] = useState([]); const [medicineTypes, setMedicineTypes] = useState([]); const [isAddResourcesOpen, setIsAddResourcesOpen] = useState(false); const [newResourceData, setNewResourceData] = useState({ resourceType: "feed" as ResourceType, feedItemId: "", medicineItemId: "", medicineCompany: "", fishBatchItemId: "", quantityKg: "", mlPerUnit: "", receiveDate: new Date().toISOString().split("T")[0], expiryDate: "", }); const [fishTypeOptions, setFishTypeOptions] = useState< Array<{ id: string; name: string }> >([]); //delete modal const [deleteConfirmOpen, setDeleteConfirmOpen] = useState(false); const [deleteConfirmType, setDeleteConfirmType] = useState< "feed" | "medicine" >("feed"); const [deleteConfirmItem, setDeleteConfirmItem] = useState<{ id: string; name: string; medicineBatch?: MedicineInventoryBatch; } | null>(null); // Health modal state const [healthModalOpen, setHealthModalOpen] = useState(false); const [healthModalMode, setHealthModalMode] = useState< "health" | "quarantine" >("health"); const [batchForHealth, setBatchForHealth] = useState(null); const [selectedMedicineBatch, setSelectedMedicineBatch] = useState(null); const [isMedicineDetailsOpen, setIsMedicineDetailsOpen] = useState(false); const [isMedicineDeleting, setIsMedicineDeleting] = useState(false); // Data loaders const toNumber = (value: unknown, fallback = 0): number => { const parsed = Number(value); return Number.isFinite(parsed) ? parsed : fallback; }; const getAlertThreshold = (entry: any, fallback = 0): number => { const threshold = toNumber( entry?.alertThreshold ?? entry?.alertthreshold ?? entry?.reorderLevel ?? entry?.minimumStock ?? entry?.minStockLevel ?? entry?.threshold ?? entry?.lowStockThreshold ?? entry?.foodType?.alertThreshold ?? entry?.foodType?.alertthreshold ?? entry?.foodType?.reorderLevel ?? entry?.foodType?.minimumStock ?? entry?.foodType?.minStockLevel ?? entry?.foodType?.threshold ?? entry?.foodType?.lowStockThreshold, Number.NaN, ); if (Number.isFinite(threshold) && threshold > 0) { return threshold; } const fallbackNumber = toNumber(fallback, 0); return fallbackNumber > 0 ? fallbackNumber : 0; }; const getArrayPayload = (value: any): any[] => { if (Array.isArray(value)) return value; if (Array.isArray(value?.data)) return value.data; if (Array.isArray(value?.items)) return value.items; if (Array.isArray(value?.results)) return value.results; if (Array.isArray(value?.batches)) return value.batches; if (Array.isArray(value?.fishBatches)) return value.fishBatches; if (Array.isArray(value?.totals)) return value.totals; return []; }; const resolveFeedExpiryDate = (entry: any): string | undefined => { const candidates = [ entry?.expiryDate, entry?.expirationDate, entry?.expiresAt, entry?.expireDate, entry?.expiry, entry?.expiry_date, entry?.expiration_date, entry?.expiryAt, entry?.expiration, entry?.bestBefore, entry?.bestBeforeDate, entry?.foodType?.expiryDate, entry?.foodType?.expirationDate, entry?.foodType?.expiresAt, ]; let selectedValue: string | undefined; let selectedTimestamp = Number.NEGATIVE_INFINITY; for (const candidate of candidates) { const raw = candidate instanceof Date ? candidate.toISOString() : String(candidate ?? "").trim(); if (!raw) { continue; } const timestamp = new Date(raw).getTime(); if (!Number.isFinite(timestamp)) { continue; } // Keep the farthest valid expiry date when multiple backend fields exist. if (timestamp > selectedTimestamp) { selectedTimestamp = timestamp; selectedValue = raw; } } return selectedValue; }; const isReadyToAllocateStatus = (status: unknown): boolean => { const normalized = String(status || "").toUpperCase(); return ( normalized === "READY_TO_STOCK" || normalized === "READY" || normalized === "AVAILABLE" ); }; const normalizeFishBatch = (batch: any): FishInventoryBatch => { const currentQuantity = toNumber( batch?.quantity ?? batch?.currentQuantity ?? batch?.currentQty, 0, ); const initialQuantity = toNumber( batch?.initialQuantity ?? batch?.initialCount, currentQuantity, ); const averageWeight = toNumber( batch?.averageWeight ?? batch?.avgWeight ?? batch?.initialWeightGrams ?? batch?.initialAverageWeight, 0, ); return { id: String(batch?.id || batch?._id || ""), farmId: String(batch?.farmId || batch?.farm || selectedFarm?.id || ""), purchaseOrderId: String(batch?.purchaseOrderId || ""), species: String( batch?.species || batch?.fishTypeName || batch?.fishType?.name || "Unknown Batch", ), quantity: currentQuantity, initialQuantity, averageWeight, status: String( batch?.status || "", ).toUpperCase() as FishInventoryBatch["status"], healthCheckStatus: String( batch?.healthCheckStatus || batch?.healthStatus || "PENDING", ).toUpperCase() as FishInventoryBatch["healthCheckStatus"], healthCheckDate: batch?.healthCheckDate || batch?.healthCheckAt, deliveryDate: batch?.deliveryDate || batch?.receivedDate || new Date().toISOString(), quarantinePeriodDays: toNumber(batch?.quarantinePeriodDays, 0), notes: batch?.notes || "", fishTypeName: batch?.fishTypeName, } as FishInventoryBatch & { fishTypeName?: string }; }; const resolveMedicineDisplayName = ( entry: any, fallbackId?: string, ): string => { const rawName = String( entry?.medicineName || entry?.medicineType?.name || entry?.medicineTypeName || entry?.medicine?.name || entry?.name || entry?.itemName || entry?.productName || entry?.tradeName || "", ).trim(); const isUnknownName = !rawName || /^unknown(\s+medicine)?$/i.test(rawName); if (!isUnknownName) return rawName; const company = String( entry?.company || entry?.manufacturer || entry?.supplier || entry?.brand || entry?.medicine?.company || "", ).trim(); if (company && company !== "-") { return `${company} Medicine`; } const id = String(entry?.id || entry?._id || fallbackId || "").trim(); if (id) { return `Medicine ${id.slice(0, 8)}`; } return "Unnamed Medicine"; }; const normalizeMedicineBatch = ( entry: any, ): MedicineInventoryBatch | null => { const id = entry?.id || entry?._id; if (!id) return null; return { id: String(id), farmId: String(entry?.farmId || entry?.farm || selectedFarm?.id || ""), medicineName: resolveMedicineDisplayName(entry, String(id)), company: String( entry?.company || entry?.manufacturer || entry?.supplier || entry?.brand || entry?.medicine?.company || entry?.medicine?.manufacturer || "-", ), batchNumber: String( entry?.batchNumber || entry?.batch || entry?.lotNumber || entry?.code || "-", ), quantity: toNumber( entry?.quantity ?? entry?.currentQuantity ?? entry?.availableQuantity ?? entry?.stock ?? entry?.quantityKg, 0, ), mlPerUnit: toNumber(entry?.mlPerUnit ?? entry?.ml_per_unit, 0), unit: String(entry?.unit || entry?.quantityUnit || "unit"), reorderLevel: toNumber( entry?.reorderLevel ?? entry?.minimumStock ?? entry?.minStockLevel ?? 10, 10, ), expiryDate: entry?.expiryDate || entry?.expirationDate || entry?.expiresAt, status: String(entry?.status || "").toUpperCase() || undefined, notes: entry?.notes || entry?.description || "", }; }; const getMedicineBatchStatus = (batch: MedicineInventoryBatch): string => { if (batch.expiryDate && new Date(batch.expiryDate).getTime() < Date.now()) { return "EXPIRED"; } if (batch.quantity <= 0) return "OUT_OF_STOCK"; if (batch.quantity <= batch.reorderLevel) return "LOW_STOCK"; return batch.status || "IN_STOCK"; }; const medicineStatusBadgeClass = (status: string): string => { const normalized = status.toUpperCase(); if (normalized === "EXPIRED" || normalized === "OUT_OF_STOCK") { return "bg-red-100 text-red-800 border-red-200"; } if (normalized === "LOW_STOCK") { return "bg-orange-100 text-orange-800 border-orange-200"; } return "bg-green-100 text-green-800 border-green-200"; }; // GET /api/v1/inventory/batches const loadBatches = async () => { try { const res = await getBatches(); const batches = getArrayPayload(res).map(normalizeFishBatch); setFishBatches(batches); } catch (error) { console.error("Error loading batches", error); setFishBatches([]); } }; // GET /api/v1/inventory/feed const loadFeed = async () => { try { const res = await getFeedInventory(); const feed = getArrayPayload(res); setFeedInventory(feed); } catch (error) { console.error("Error loading feed inventory", error); setFeedInventory([]); } }; const loadMedicine = async (): Promise => { try { const res = await getMedicineInventory(); const normalized = getArrayPayload(res) .map(normalizeMedicineBatch) .filter((item): item is MedicineInventoryBatch => item !== null); const filtered = selectedFarm ? normalized.filter( (item) => !item.farmId || item.farmId === selectedFarm.id, ) : normalized; setMedicineInventory(filtered); return filtered; } catch (error) { console.error("Error loading medicine inventory", error); setMedicineInventory([]); return []; } }; const loadMedicineTotals = async () => { try { const res = await getMedicineInventoryTotal(); const rows = getArrayPayload(res); if (rows.length > 0) { setMedicineTotals( rows.map((row: any) => ({ medicineName: String( row?.medicineName || row?.name || row?.medicine?.name || "Medicine", ), totalQuantity: toNumber( row?.totalQuantity ?? row?.quantity ?? row?.total ?? row?.stock, 0, ), unit: String(row?.unit || row?.quantityUnit || "unit"), })), ); return; } const scalar = typeof res === "number" ? res : typeof res?.data === "number" ? res.data : Number.NaN; if (Number.isFinite(scalar)) { setMedicineTotals([ { medicineName: "All Medicines", totalQuantity: scalar, unit: "unit", }, ]); } else { setMedicineTotals([]); } } catch (error) { console.error("Error loading medicine totals", error); setMedicineTotals([]); } }; // GET /api/v1/aquaculture/food-types const loadFoodTypes = async () => { try { const res = await apiGet("/aquaculture/food-types"); const data = getArrayPayload(res?.data ?? res); setFoodTypes(data); } catch (error) { console.error("Error loading food types", error); setFoodTypes([]); } }; const loadFishTypeOptions = async () => { try { const fishTypes = await getFishTypes(); setFishTypeOptions( fishTypes .map((entry) => ({ id: String(entry?.id || entry?._id || ""), name: String(entry?.name || entry?.species || "Unknown Fish Type"), })) .filter((entry) => entry.id), ); } catch (error) { console.error("Error loading fish type options", error); setFishTypeOptions([]); } }; const loadMedicineTypes = async () => { try { const res = await apiGet("/inventory/medicine-types"); const data = getArrayPayload(res?.data ?? res); setMedicineTypes( data .map((entry: any) => { const id = String(entry?.id || entry?._id || "").trim(); const name = String(entry?.name || "").trim(); if (!id || !name) return null; return { id, name, arabicName: String(entry?.arabicName || "").trim() || undefined, category: String(entry?.category || "").trim() || undefined, description: String(entry?.description || "").trim() || undefined, }; }) .filter((entry): entry is MedicineTypeItem => entry !== null), ); } catch (error) { console.error("Error loading medicine types", error); setMedicineTypes([]); } }; // GET /api/v1/tanks const loadTanks = async () => { setIsTanksLoading(true); try { const res = await apiGet("/tanks"); const rawList = Array.isArray(res) ? res : Array.isArray(res?.data) ? res.data : Array.isArray(res?.items) ? res.items : Array.isArray(res?.results) ? res.results : []; const normalized = rawList .map((tank: any) => { const id = tank?.id || tank?._id; if (!id) return null; return { id: String(id), name: String(tank?.name || `Tank ${String(id).slice(0, 6)}`), farmId: String(tank?.farmId || selectedFarm?.id || ""), status: String(tank?.status || "UNKNOWN").toUpperCase(), biomass: Number(tank?.biomass?.actual ?? tank?.biomass ?? 0), capacity: Number( tank?.biomass?.capacity ?? tank?.capacity ?? tank?.biomassLimit ?? 0, ), }; }) .filter(Boolean); setTanks(normalized); } catch (error) { console.error("Error loading tanks", error); } finally { setIsTanksLoading(false); } }; useEffect(() => { loadBatches(); loadFeed(); loadMedicine(); loadMedicineTotals(); loadTanks(); loadFoodTypes(); loadMedicineTypes(); loadFishTypeOptions(); }, []); useEffect(() => { const handleFeedingTaskCompleted = () => { void loadFeed(); }; window.addEventListener( FEEDING_TASK_COMPLETED_EVENT, handleFeedingTaskCompleted, ); return () => { window.removeEventListener( FEEDING_TASK_COMPLETED_EVENT, handleFeedingTaskCompleted, ); }; }, []); useEffect(() => { if (!isAddResourcesOpen) return; void loadFoodTypes(); void loadMedicineTypes(); void loadFeed(); void loadMedicine(); void loadFishTypeOptions(); }, [isAddResourcesOpen]); // Handlers // GET /api/v1/inventory/batches/:id const fetchBatch = async (id: string) => { try { const res = await getBatchById(id); console.log(res); } catch (error) { console.error("Error fetching batch", error); } }; // PATCH /api/v1/inventory/batches/:id/allocate const handleAllocate = async ( batchId: string, tankId: string, quantity: number, avgWeight: number, stockingDate: string, notes?: string, ) => { void stockingDate; void notes; try { // Backend allocate route expects: { tankId, quantity, avgWeight }. await allocateBatch(batchId, { tankId, quantity, avgWeight: toNumber(avgWeight, 0), }); await loadBatches(); toast.success("Batch allocated to tank successfully"); } catch (error) { console.error("Allocation failed", error); toast.error("Failed to allocate batch to tank"); } finally { setShowAllocateModal(false); setSelectedBatch(null); } }; // health modal handlers const handleQuarantine = (batch: any) => { setBatchForHealth(batch); setHealthModalMode("quarantine"); setHealthModalOpen(true); }; const handleHealthCheck = (batch: any) => { setBatchForHealth(batch); setHealthModalMode("health"); setHealthModalOpen(true); }; const resetAddResourcesForm = () => { setNewResourceData({ resourceType: "feed", feedItemId: "", medicineItemId: "", medicineCompany: "", fishBatchItemId: "", quantityKg: "", mlPerUnit: "", receiveDate: new Date().toISOString().split("T")[0], expiryDate: "", }); }; const ensureMutationSucceeded = (response: any) => { if (!response || typeof response !== "object") { return; } const hasSuccessFlag = Object.prototype.hasOwnProperty.call( response, "success", ); if (hasSuccessFlag && response.success === false) { const message = typeof response.message === "string" && response.message.trim().length > 0 ? response.message : "Request failed"; throw new Error(message); } }; const parseApiErrorMessage = (error: unknown): string => { if (error instanceof Error && error.message.trim()) { const marker = "]:"; const markerIndex = error.message.indexOf(marker); if ( markerIndex >= 0 && markerIndex + marker.length < error.message.length ) { return error.message.slice(markerIndex + marker.length).trim(); } return error.message; } return "Failed to add resource. Please check your input and try again."; }; const isMissingEntityIdError = (value: unknown): boolean => { const message = typeof value === "string" ? value : String(value ?? ""); return /cannot read properties of undefined \(reading 'id'\)/i.test( message, ); }; const resolveUnitCost = (...values: Array): number => { for (const value of values) { const parsed = Number(value); if (Number.isFinite(parsed) && parsed > 0) { return parsed; } } return 1; }; const ensureSupplierForResource = async ( resourceType: ResourceType, ): Promise => { const requiredItemTypes = resourceType === "feed" ? ["FEED", "FOOD"] : resourceType === "medicine" ? ["MEDICINE"] : ["FISH", "FINGERLINGS"]; const primaryItemType = requiredItemTypes[0]; const fallbackName = resourceType === "feed" ? "Inventory Feed Supplier" : resourceType === "medicine" ? "Inventory Medicine Supplier" : "Inventory Fish Supplier"; const suppliers = await getProcurementSuppliers(); const existing = suppliers.find((supplier) => (Array.isArray(supplier.items) ? supplier.items : []).some((item) => requiredItemTypes.includes(String(item).toUpperCase()), ), ); if (existing?.id) { return existing.id; } const created = await createProcurementSupplier({ name: fallbackName, items: [primaryItemType], address: selectedFarm?.name ? `Auto-generated for ${selectedFarm.name}` : "Auto-generated from Inventory", }); if (!created?.id) { const refreshed = await getProcurementSuppliers(); const fallbackSupplier = refreshed.find((supplier) => (Array.isArray(supplier.items) ? supplier.items : []).some((item) => requiredItemTypes.includes(String(item).toUpperCase()), ), ); if (fallbackSupplier?.id) { return fallbackSupplier.id; } throw new Error("Unable to resolve procurement supplier"); } return created.id; }; const getExpiryWarning = (expiryDate?: string) => { const days = getDaysUntilExpiry(expiryDate); if (days === null || days < 0) return null; if (days <= 14) { return { text: "Critical Expiry", className: "bg-red-100 text-red-700 border border-red-200", }; } if (days <= 30) { return { text: "Expiring Soon", className: "bg-yellow-100 text-yellow-700 border border-yellow-200", }; } return null; }; const getStockWarning = (item: any) => { const reorderLevel = toNumber(item?.reorderLevel, 0); if (reorderLevel <= 0) return null; const quantity = toNumber(item?.quantity, 0); // At or below the reorder level → critical if (quantity <= reorderLevel) { return { text: "Critical Stock", className: "bg-red-100 text-red-700 border border-red-200", }; } // Within 50% above the reorder level → early warning if (quantity <= reorderLevel * 1.5) { return { text: "Warning Stock", className: "bg-yellow-100 text-yellow-700 border border-yellow-200", }; } return null; }; const handleAddResourceSubmit = async () => { const expectsFishCount = newResourceData.resourceType === "fish_batch"; const expectsUnits = newResourceData.resourceType === "medicine"; const expectsDiscreteQuantity = expectsFishCount || expectsUnits; const quantity = Number(newResourceData.quantityKg); if (!Number.isFinite(quantity) || quantity <= 0) { toast.error( expectsFishCount ? "Please enter a valid fish count" : expectsUnits ? "Please enter a valid units quantity" : "Please enter a valid quantity in Kg", ); return; } if (expectsDiscreteQuantity && !Number.isInteger(quantity)) { toast.error( expectsFishCount ? "Fish batch quantity must be a whole number" : "Medicine quantity must be a whole number", ); return; } if (!newResourceData.receiveDate) { toast.error("Please choose the receive date"); return; } if ( newResourceData.resourceType === "feed" && !newResourceData.expiryDate ) { toast.error("Please choose the expiry date for feed"); return; } if ( newResourceData.expiryDate && new Date(newResourceData.expiryDate).getTime() < new Date(newResourceData.receiveDate).getTime() ) { toast.error("Expiry date cannot be earlier than receive date"); return; } const receivedDateValue = newResourceData.receiveDate; const expiryDateValue = newResourceData.expiryDate || undefined; const expiryIsoValue = expiryDateValue ? `${expiryDateValue}T00:00:00.000Z` : undefined; try { let response: any; const resourceType = newResourceData.resourceType; if (resourceType === "feed") { const selectedFeedOptionId = String( newResourceData.feedItemId || "", ).trim(); if (!selectedFeedOptionId) { toast.error("Please select a feed item"); return; } const selectedFoodType = foodTypes.find( (entry) => String(entry?.id || entry?._id || "").trim() === selectedFeedOptionId, ); const selectedFeedInventoryItem = feedInventory.find((entry: any) => { const entryId = String(entry?.id || entry?._id || "").trim(); const rawFoodType = entry?.foodTypeId || entry?.foodType || entry?.foodId || entry?.foodType_id; const foodTypeIdFromEntry = String( typeof rawFoodType === "object" ? rawFoodType?.id || rawFoodType?._id || "" : rawFoodType || "", ).trim(); return ( entryId === selectedFeedOptionId || foodTypeIdFromEntry === selectedFeedOptionId ); }); const selectedFoodTypeMeta = (selectedFoodType ?? selectedFeedInventoryItem ?? {}) as Record; const nestedFoodType = selectedFeedInventoryItem?.foodType; const resolvedFoodTypeId = String( selectedFoodTypeMeta?.id || selectedFoodTypeMeta?._id || selectedFoodTypeMeta?.foodTypeId || selectedFoodTypeMeta?.foodType_id || (typeof nestedFoodType === "object" ? nestedFoodType?.id || nestedFoodType?._id : "") || selectedFeedOptionId, ).trim(); const feedUnitCost = resolveUnitCost( selectedFoodTypeMeta?.unitCost, selectedFoodTypeMeta?.costPerKg, selectedFoodTypeMeta?.pricePerKg, selectedFoodTypeMeta?.purchasePrice, ); const feedTotalCost = Number((quantity * feedUnitCost).toFixed(2)); const feedSupplier = String( selectedFoodTypeMeta?.supplier || selectedFoodTypeMeta?.manufacturer || selectedFoodTypeMeta?.company || "PO Supplier", ); const buildFeedPayload = ( withNestedFoodType: boolean, ): Record => { const payload: Record = { foodTypeId: resolvedFoodTypeId, quantityKg: quantity, quantity, initialQuantityKg: quantity, receivedDate: receivedDateValue, receiveDate: receivedDateValue, deliveryDate: receivedDateValue, packagingUnit: "KG", unitsReceived: Math.max(1, Math.ceil(quantity)), costPerKg: feedUnitCost, costPerUnit: feedUnitCost, totalCost: feedTotalCost, name: String( selectedFoodTypeMeta?.name || selectedFoodTypeMeta?.foodName || "Unknown Feed", ), supplier: feedSupplier, manufacturer: feedSupplier, }; if (withNestedFoodType) { payload.foodType = { id: resolvedFoodTypeId }; } if (expiryDateValue) { payload.expiryDate = expiryDateValue; payload.expirationDate = expiryDateValue; payload.expiresAt = expiryIsoValue; } return payload; }; response = await createFeed(buildFeedPayload(false)); if ( response && typeof response === "object" && response.success === false && isMissingEntityIdError(response.message) ) { // Some backend deployments expect nested `foodType.id` instead of only `foodTypeId`. response = await createFeed(buildFeedPayload(true)); } } else if (resourceType === "medicine") { const selectedMedicineId = String( newResourceData.medicineItemId || "", ).trim(); if (!selectedMedicineId) { toast.error("Please select a medicine type"); return; } const selectedMedicineType = medicineTypes.find( (entry) => Boolean(entry) && String(entry.id).trim() === selectedMedicineId, ); if (!selectedMedicineType) { toast.error("Please select a medicine type"); return; } const medicineCompany = String( newResourceData.medicineCompany || "", ).trim(); if (!medicineCompany) { toast.error("Please enter a company"); return; } if (!expiryDateValue) { toast.error("Please choose the expiry date"); return; } const medicineQuantity = Math.max(1, Math.round(quantity)); const mlPerUnitValue = Number(newResourceData.mlPerUnit); if (!Number.isFinite(mlPerUnitValue) || mlPerUnitValue <= 0) { toast.error("Please enter a valid ml per unit value"); return; } response = await addMedicineStock({ medicineTypeId: selectedMedicineType.id, quantity: medicineQuantity, mlPerUnit: mlPerUnitValue, company: medicineCompany, receivedDate: receivedDateValue, expiryDate: expiryDateValue, }); } else if (resourceType === "fish_batch") { const selectedFishType = fishTypeOptions.find( (entry) => String(entry.id) === String(newResourceData.fishBatchItemId || ""), ); if (!selectedFishType) { toast.error("Please select a fish batch item"); return; } const batchQuantity = Math.max(1, Math.round(quantity)); const supplierId = await ensureSupplierForResource("fish_batch"); const fishUnitCost = 1; await createFishPurchaseOrder({ supplierId, items: [ { fishTypeId: selectedFishType.id, quantity: batchQuantity, totalCost: batchQuantity * fishUnitCost, }, ], }); // Backend currently supports GET (not POST) on /inventory/batches. // Fish add-resource flow should create a procurement fish order only. response = { success: true }; } else { toast.error("Unsupported resource type selected"); return; } ensureMutationSucceeded(response); toast.success( resourceType === "fish_batch" ? "Fish purchase order created successfully" : "Resource added successfully", ); setIsAddResourcesOpen(false); resetAddResourcesForm(); await Promise.all([ loadFeed(), loadMedicine(), loadMedicineTotals(), loadBatches(), ]); } catch (error) { console.error("Add resource failed", error); toast.error(parseApiErrorMessage(error)); } }; // DELETE /api/v1/inventory/feed/:id const handleDeleteFeed = (id: string, name: string) => { setDeleteConfirmType("feed"); setDeleteConfirmItem({ id, name }); setDeleteConfirmOpen(true); }; const openMedicineDetails = (batch: MedicineInventoryBatch) => { setSelectedMedicineBatch(batch); setIsMedicineDetailsOpen(true); }; const handleDeleteMedicine = (batch: MedicineInventoryBatch) => { setDeleteConfirmType("medicine"); setDeleteConfirmItem({ id: batch.id, name: batch.medicineName, medicineBatch: batch, }); setDeleteConfirmOpen(true); }; const confirmDelete = async () => { if (!deleteConfirmItem) return; setDeleteConfirmOpen(false); if (deleteConfirmType === "feed") { try { await deleteFeed(deleteConfirmItem.id); toast.success("Feed record deleted"); await loadFeed(); } catch (error) { console.error("Delete feed failed", error); toast.error("Failed to delete record."); } } else { const batch = deleteConfirmItem.medicineBatch; if (!batch) return; try { setIsMedicineDeleting(true); await deleteMedicineBatch(batch.id); if (selectedMedicineBatch?.id === batch.id) { setIsMedicineDetailsOpen(false); setSelectedMedicineBatch(null); } const refreshedMedicine = await loadMedicine(); await loadMedicineTotals(); if (refreshedMedicine.some((item) => item.id === batch.id)) { throw new Error("Deleted medicine batch still present after refresh"); } toast.success("Medicine batch deleted"); } catch (error) { console.error("Medicine batch deletion failed", error); toast.error("Failed to delete medicine batch"); } finally { setIsMedicineDeleting(false); } } setDeleteConfirmItem(null); }; // GET /api/v1/inventory/feed/food-type/:foodId const filterFeed = async (foodId: string) => { try { const res = await getFeedByFoodType(foodId); const feed = Array.isArray(res) ? res : Array.isArray(res.data) ? res.data : []; setFeedInventory(feed); } catch (error) { console.error("Feed filter failed", error); setFeedInventory([]); } }; // Badge and icon helpers const getStatusBadge = (status: string) => { const normalized = String(status || "").toUpperCase(); switch (normalized) { case "READY_TO_STOCK": case "READY": return ( Ready to Stock ); case "QUARANTINE": return ( Quarantine ); case "DEPLETED": return ( Depleted ); case "IN_STOCK": return ( In Stock ); case "AVAILABLE": return ( Available ); default: return {normalized || "UNKNOWN"}; } }; const getHealthCheckBadge = (status: string) => { switch (status) { case "PASSED": return ( Passed ); case "PENDING": return ( Pending ); case "FAILED": return ( Failed ); default: return {status}; } }; const getTypeIcon = (type: string) => { switch (type) { case "feed": return ShoppingCart; case "medicine": return Pill; case "tool": return Wrench; case "fuel": return Fuel; default: return Package; } }; const getTypeColor = (type: string) => { switch (type) { case "feed": return "bg-blue-100 text-blue-800"; case "medicine": return "bg-green-100 text-green-800"; case "tool": return "bg-purple-100 text-purple-800"; case "fuel": return "bg-orange-100 text-orange-800"; default: return "bg-gray-100 text-gray-800"; } }; const mapApiStockStatusToUi = ( status: unknown, ): "good" | "low" | "critical" | null => { const normalized = String(status || "").toUpperCase(); if (!normalized) return null; if ( ["OUT_OF_STOCK", "CONSUMED", "DEPLETED", "EXPIRED", "FAILED"].includes( normalized, ) ) { return "critical"; } if (["LOW_STOCK", "LOW", "WARNING"].includes(normalized)) { return "low"; } if ( ["IN_STOCK", "AVAILABLE", "READY", "ACTIVE", "GOOD", "PASSED"].includes( normalized, ) ) { return "good"; } return null; }; const getStockStatus = (item: any) => { const apiStatus = mapApiStockStatusToUi(item.status); if (apiStatus) return apiStatus; const reorderLevel = toNumber(item.reorderLevel, 0); const quantity = toNumber(item.quantity, 0); if (reorderLevel > 0) { if (quantity <= reorderLevel * 0.5) return "critical"; if (quantity <= reorderLevel) return "low"; } return quantity <= 0 ? "critical" : "good"; }; const getStockStatusBadge = (status: "good" | "low" | "critical") => { if (status === "critical") { return ( Critical ); } if (status === "low") { return ( Low ); } return ( Healthy ); }; const getDaysUntilExpiry = (expiryDate?: string) => { if (!expiryDate) return null; const expiryTimestamp = new Date(expiryDate).getTime(); if (!Number.isFinite(expiryTimestamp)) return null; return Math.ceil((expiryTimestamp - Date.now()) / (1000 * 60 * 60 * 24)); }; // API inventory helpers const filteredFishBatches = selectedFarm ? fishBatches.filter((batch: any) => batch.farmId === selectedFarm.id) : fishBatches; const fishStockBatches = filteredFishBatches.filter( (batch: any) => String(batch?.status || "").toUpperCase() !== "QUARANTINE", ); const readyToAllocateBatches = filteredFishBatches.filter( (batch: any) => isReadyToAllocateStatus(batch.status) && (batch.quantity ?? 0) > 0, ); const feedStockInventory = feedInventory.map((f: any) => { // Find food type object from foodTypes list // Handle various ID field names returned by different backend versions const fid = f.foodTypeId || f.foodType || f.foodId || f.foodType_id; const foodTypeId = typeof fid === "object" ? fid?.id || fid?._id : fid; const ft = foodTypes.find((t) => (t.id || t._id) === foodTypeId); const name = f.name || (ft ? `${ft.name} ${f.manufacturer ? `(${f.manufacturer})` : ""}` : "Unknown Feed"); const arabicName = f.arabicName || ft?.arabicName; const unit = f.unit || ft?.unit || "kg"; const quantity = typeof f.quantityKg === "number" ? f.quantityKg : typeof f.quantity === "number" ? f.quantity : 0; const costPerUnit = f.costPerKg || f.unitCost || f.costPerUnit || ft?.costPerUnit || 0; const foodTypeThreshold = getAlertThreshold(ft, 100); return { ...f, type: "feed", name, arabicName, quantity, initialQuantity: toNumber( f.initialQuantityKg ?? f.initialQuantity ?? quantity, quantity, ), unit, reorderLevel: getAlertThreshold(f, foodTypeThreshold), costPerUnit: costPerUnit, supplier: f.manufacturer || f.supplier || ft?.supplier || "Main Supplier", expiryDate: resolveFeedExpiryDate(f), status: f.status || "IN_STOCK", batchNumber: f.batchNumber || "-", }; }); const finalFilteredInventory = feedStockInventory.filter((item: any) => item.name.toLowerCase().includes(searchQuery.toLowerCase()), ); const expiringItems = feedStockInventory.filter((item: any) => { if (!item.expiryDate) return false; const daysUntilExpiry = getDaysUntilExpiry(item.expiryDate); return ( daysUntilExpiry !== null && daysUntilExpiry <= 30 && daysUntilExpiry > 0 ); }); const lowFeedStockCount = feedStockInventory.filter( (item: any) => getStockStatus(item) !== "good", ).length; const totalMedicineStock = medicineInventory.reduce( (sum, batch) => sum + (batch.quantity || 0), 0, ); const expiredMedicineCount = medicineInventory.filter( (batch) => getMedicineBatchStatus(batch) === "EXPIRED", ).length; const lowMedicineStockCount = medicineInventory.filter( (batch) => getMedicineBatchStatus(batch) === "LOW_STOCK", ).length; const dedupeComboboxItems = ( items: Array, ): ComboboxItem[] => { const seen = new Set(); return items.filter((item): item is ComboboxItem => { if (!item || !item.value) return false; if (seen.has(item.value)) return false; seen.add(item.value); return true; }); }; const addResourceFeedItems: ComboboxItem[] = dedupeComboboxItems([ ...foodTypes.map((foodType) => { const id = String(foodType?.id || foodType?._id || "").trim(); if (!id) return null; const name = String(foodType?.name || "Unknown Feed"); return { value: id, label: name, sub: `ID: ${id.slice(0, 8)}`, }; }), ...feedInventory.map((entry: any) => { const rawFoodType = entry?.foodTypeId || entry?.foodType || entry?.foodId || entry?.foodType_id; const foodTypeId = String( typeof rawFoodType === "object" ? rawFoodType?.id || rawFoodType?._id || "" : rawFoodType || "", ).trim(); const entryId = String(entry?.id || entry?._id || "").trim(); const optionId = foodTypeId || entryId; if (!optionId) return null; const label = String( entry?.name || (typeof rawFoodType === "object" ? rawFoodType?.name : "") || `Feed ${optionId.slice(0, 8)}`, ); const supplier = String( entry?.supplier || entry?.manufacturer || "", ).trim(); return { value: optionId, label, sub: supplier ? `${supplier} - ID: ${optionId.slice(0, 8)}` : `ID: ${optionId.slice(0, 8)}`, }; }), ]); const addResourceMedicineTypeItems: ComboboxItem[] = medicineTypes .map((medicineType) => { const id = String(medicineType.id || "").trim(); if (!id) return null; return { value: id, label: medicineType.name, sub: medicineType.category ? `${medicineType.category} - ID: ${id.slice(0, 8)}` : `ID: ${id.slice(0, 8)}`, }; }) .filter((item): item is ComboboxItem => item !== null); const addResourceFishBatchItems: ComboboxItem[] = fishTypeOptions.map( (fishType) => ({ value: fishType.id, label: fishType.name, sub: `ID: ${fishType.id.slice(0, 8)}`, }), ); const addResourceItemOptions: ComboboxItem[] = newResourceData.resourceType === "feed" ? addResourceFeedItems : newResourceData.resourceType === "medicine" ? addResourceMedicineTypeItems : addResourceFishBatchItems; const addResourceItemLabel = newResourceData.resourceType === "feed" ? "Feed Item" : newResourceData.resourceType === "medicine" ? "Medicine Type" : "Fish Batch Item"; const addResourceItemPlaceholder = newResourceData.resourceType === "feed" ? "Search or select feed item..." : newResourceData.resourceType === "medicine" ? "Search or select medicine type..." : "Search or select fish batch item..."; const addResourceEmptyText = newResourceData.resourceType === "feed" ? "No feed items available." : newResourceData.resourceType === "medicine" ? "No medicine types available from API." : "No fish batch items available from API."; const addResourceSelectedItemValue = newResourceData.resourceType === "feed" ? newResourceData.feedItemId : newResourceData.resourceType === "medicine" ? newResourceData.medicineItemId : newResourceData.fishBatchItemId; const handleAddResourceItemChange = (item: ComboboxItem | null) => { const selectedId = item?.value ?? ""; setNewResourceData((previous) => { if (previous.resourceType === "feed") { return { ...previous, feedItemId: selectedId }; } if (previous.resourceType === "medicine") { return { ...previous, medicineItemId: selectedId }; } return { ...previous, fishBatchItemId: selectedId }; }); }; const addResourceQuantityLabel = newResourceData.resourceType === "fish_batch" ? "Quantity (Fish Count)" : newResourceData.resourceType === "medicine" ? "Quantity (Units)" : "Quantity (Kg)"; const addResourceQuantityStep = newResourceData.resourceType === "feed" ? "0.01" : "1"; const addResourceQuantityPlaceholder = newResourceData.resourceType === "fish_batch" ? "100" : newResourceData.resourceType === "medicine" ? "1" : "1"; // Render const currentFarm = selectedFarm; const isWarehouse = user.role.toLocaleLowerCase() === "warehouse"; const isTechnican = user.role.toLocaleLowerCase() === "technician"; return ( <> {" "}
Inventory Management
{currentFarm?.name}
{user.name .split(" ") .map((segment) => segment[0]) .join("") .toUpperCase()}

Track and manage your stock levels

{isWarehouse && ( )}
{/* Main Tabs */} Fish Stock Allocate to Tank Feed Stock Harvested Fish Medicine {/* Fish Stock Tab */}
Fish Inventory Batches

Manage fish from purchase orders to tank stocking

{fishStockBatches.map((batch) => ( ))}
Batch Identity Status Quantity
{batch.fishTypeName || batch.species || "Unknown Batch"}
ID: {batch.id?.split("-")[0] ?? batch.id}
{batch.purchaseOrderId && (
PO: {batch.purchaseOrderId.substring(0, 8)} ...
)}
{getStatusBadge(batch.status)}
{(batch.quantity ?? 0).toLocaleString()} fish
of{" "} {(batch.initialQuantity ?? 0).toLocaleString()}{" "} stocked
{fishStockBatches.length === 0 && (

No fish inventory found

Purchase orders will appear here

)}
{/* Allocate to Tank Tab */}
Allocate Fish to Tank

Choose any ready batch and allocate it directly to a tank

{readyToAllocateBatches.length === 0 && (

No batches are ready to stock right now.

)} {readyToAllocateBatches.map((batch) => (

{batch.fishTypeName || batch.species || "Fish Batch"}

Batch ID: {batch.id?.split("-")[0] ?? batch.id}

Qty:{" "} {(batch.quantity ?? 0).toLocaleString()} fish
{getStatusBadge(batch.status)} {isTechnican && ( )}
))}
{/* Feed Stock Tab */} {/* Summary Cards */}
Feed Batches
{feedStockInventory.length}

Feed records in inventory

Low Stock
{lowFeedStockCount}

Need reordering

Expiring Soon
{ expiringItems.filter((i: any) => { const days = getDaysUntilExpiry(i.expiryDate); return days !== null && days <= 30; }).length }

Within 30 days

{/* Search and Filter */}
setSearchQuery(e.target.value)} className="pl-10 h-9" />
{finalFilteredInventory.map((item: any) => { const Icon = getTypeIcon("feed"); const daysUntilExpiry = getDaysUntilExpiry(item.expiryDate); const expiryWarning = getExpiryWarning(item.expiryDate); const stockWarning = getStockWarning(item); const itemName = item.name; const stockStatus = getStockStatus(item); const quantity = toNumber(item.quantity, 0); const initialQuantity = toNumber( item.initialQuantity ?? item.quantity, quantity, ); const reorderLevel = toNumber(item.reorderLevel, 0); const stockLevelPercent = initialQuantity > 0 ? Math.min(100, (quantity / initialQuantity) * 100) : 0; const stockProgressClass = stockStatus === "critical" ? "h-1.5 mt-2 [&>div]:bg-red-500" : stockStatus === "low" ? "h-1.5 mt-2 [&>div]:bg-orange-500" : "h-1.5 mt-2 [&>div]:bg-emerald-500"; return (

{itemName}

{stockWarning && ( {stockWarning.text} )} {expiryWarning && ( {expiryWarning.text} )}

{item.supplier ? `Supplier: ${item.supplier}` : "Stock available in storage"}

Stock level:{" "} {quantity.toLocaleString()} {item.unit}

{reorderLevel > 0 && (

Reorder level: {reorderLevel.toLocaleString()}{" "} {item.unit}

)} {item.expiryDate && (

Expires:{" "} {new Date( item.expiryDate, ).toLocaleDateString()}

)}
{isWarehouse && ( )}
); })}
{finalFilteredInventory.length === 0 && (

No feed stock found

Try adjusting your search or add a new feed resource

)}
Medicine Batches
{medicineInventory.length}

Active inventory rows

Total Quantity
{totalMedicineStock.toLocaleString()}

Across all medicine batches

Low Stock
{lowMedicineStockCount}

Needs refill soon

Expired
{expiredMedicineCount}

Do not use

Medicine Inventory List

Table view with quantity status and batch-level controls

{medicineInventory.length === 0 ? (

No medicine inventory found for this farm.

Once medicine stock is received, it will appear here.

) : (
{medicineInventory.map((batch) => { const status = getMedicineBatchStatus(batch); const expiryWarning = getExpiryWarning( batch.expiryDate, ); return ( ); })}
Medicine Company Quantity Quantity (ml) Expiry Date Status Actions
{batch.medicineName} {batch.company || "-"} {batch.quantity.toLocaleString()} {batch.unit} {batch.mlPerUnit && batch.mlPerUnit > 0 ? ( batch.quantity * batch.mlPerUnit ).toLocaleString() + " ml" : "—"} {batch.expiryDate ? new Date( batch.expiryDate, ).toLocaleDateString() : "-"}
{status.replace(/_/g, " ")} {expiryWarning && ( {expiryWarning.text} )}
{isWarehouse && ( )}
)}
{/* Allocate Fish to Tank Modal */} {selectedBatch && ( { setShowAllocateModal(false); setSelectedBatch(null); }} batch={selectedBatch!} onAllocate={handleAllocate} farmId={selectedFarm?.id || ""} availableTanks={tanks} /> )} {/* Add Resources Modal */} { setIsAddResourcesOpen(open); if (!open) { resetAddResourcesForm(); } }} > Add resources Add inventory resources and select resource type, item, quantity, receive date, and expiry date.

{addResourceItemOptions.length > 0 ? `${addResourceItemOptions.length} item(s) available` : addResourceEmptyText}

setNewResourceData((previous) => ({ ...previous, quantityKg: event.target.value, })) } />
{newResourceData.resourceType === "medicine" && (
setNewResourceData((previous) => ({ ...previous, mlPerUnit: event.target.value, })) } />
)} {newResourceData.resourceType === "medicine" && (
setNewResourceData((previous) => ({ ...previous, medicineCompany: event.target.value, })) } />
)}
setNewResourceData((previous) => ({ ...previous, receiveDate: event.target.value, })) } />
{newResourceData.resourceType !== "fish_batch" && (
setNewResourceData((previous) => ({ ...previous, expiryDate: event.target.value, })) } />
)}
{ setIsMedicineDetailsOpen(open); if (!open) { setSelectedMedicineBatch(null); } }} > Medicine Details {selectedMedicineBatch && (

Medicine

{selectedMedicineBatch.medicineName}

Company

{selectedMedicineBatch.company || "-"}

Batch

{selectedMedicineBatch.batchNumber || "-"}

Each unit contains (ml)

{selectedMedicineBatch.mlPerUnit || "-"}

Status

{getMedicineBatchStatus(selectedMedicineBatch).replace( /_/g, " ", )}

Current Quantity

{selectedMedicineBatch.quantity.toLocaleString()}{" "} {selectedMedicineBatch.unit}

Expiry Date

{selectedMedicineBatch.expiryDate ? new Date( selectedMedicineBatch.expiryDate, ).toLocaleDateString() : "-"}

)}
{/* Health Check & Quarantine Modal - Inventory Batch version */} {batchForHealth && ( )}
{ if (!open) { setDeleteConfirmOpen(false); setDeleteConfirmItem(null); } }} > {deleteConfirmType === "feed" ? "Delete Feed" : "Delete Medicine"} Are you sure you want to permanently delete{" "} {deleteConfirmItem?.name ?? "this item"} ? This action cannot be undone. ); }