Spaces:
Running
Running
GitHub Actions commited on
Commit ·
f287aeb
0
Parent(s):
deploy: clean snapshot
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- .dockerignoreAdded+20
- .github/workflows/sync-to-huggen-face.ymlAdded+54
- .gitignoreAdded+12
- BACKEND_INFO.mdAdded+20
- DockerfileAdded+28
- README.mdAdded+10
- Swagger UI.htmlAdded
- batches.jsonAdded
- docker-compose.ymlAdded+16
- index.htmlAdded+16
- jest.config.cjsAdded+18
- jest.setup.jsAdded+1
- package-lock.jsonAdded
- package.jsonAdded+77
- pnpm-lock.yamlAdded
- src/.babelrcAdded+7
- src/App.tsxAdded+484
- src/Attributions.mdAdded+3
- src/FISH_TYPE_ENHANCEMENTS_README.mdAdded+427
- src/GROWTH_TRACKING_README.mdAdded+301
- src/HARVEST_MODULE_README.mdAdded+338
- src/HARVEST_PER_TANK_UPDATES.mdAdded+204
- src/api.tsAdded+94
- src/api/inventoryApi.tsAdded+57
- src/components/AIAssistant.tsxAdded+969
- src/components/Accounting.tsxAdded+12
- src/components/AllocateFishToTank.tsxAdded+387
- src/components/Analytics.tsxAdded+508
- src/components/Combobox.tsxAdded+120
- src/components/Dashboard.tsxAdded+754
- src/components/Farms.tsxAdded+366
- src/components/FishTypeManagement.tsxAdded+1
- src/components/FishTypeManagementEnhanced.tsxAdded+1745
- src/components/FoodTypeManagement.tsxAdded+500
- src/components/HarvestManagement.tsxAdded+1492
- src/components/HealthLibrary.tsxAdded+1507
- src/components/Inventory.tsxAdded+2562
- src/components/IoTManagement.tsxAdded+339
- src/components/Login.tsxAdded+324
- src/components/MedicineTypeManagement.tsxAdded+483
- src/components/NotificationCenter.tsxAdded+618
- src/components/Procurement.tsxAdded+2401
- src/components/ResponsiveComponents.tsxAdded+76
- src/components/ResponsivePageHeader.tsxAdded+25
- src/components/ResponsivePageLayout.tsxAdded+35
- src/components/ResponsiveTable.tsxAdded+37
- src/components/SalesModule.tsxAdded+199
- src/components/Sidebar.tsxAdded+185
- src/components/TankManagement.tsxAdded+600
- src/components/Tasks.tsxAdded+338
1234567891011121314151617181920node_modulesbuilddist.git.gitignore*.mdDockerfiledocker-compose.yml.npm.pnpm-storenpm-debug.log*yarn-debug.log*yarn-error.log*.env.env.local.env.development.local.env.test.local.env.production.local.vscode.idea123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354name: Sync to Hugging Face Space
on: push: branches: - main
jobs: sync-to-hub: runs-on: ubuntu-latest
steps: - name: Checkout repo uses: actions/checkout@v3 with: fetch-depth: 0
- name: Configure git identity run: | git config --global user.email "ci@github-actions.local" git config --global user.name "GitHub Actions"
- name: Create clean orphan deploy branch run: | git checkout --orphan deploy
# Remove binary/build files HF rejects rm -f public/*.png public/*.jpg public/*.ico || true rm -rf build node_modules || true
# Generate HF Space README config cat > README.md << 'EOF' --- title: Frontend emoji: 🚀 colorFrom: blue colorTo: indigo sdk: docker pinned: false ---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference EOF
git add . git commit -m "deploy: clean snapshot"
- name: Push to Hugging Face env: HF_TOKEN_FRONT: ${{ secrets.HF_TOKEN_FRONT }} run: | git remote add hf https://fouad12344321:$HF_TOKEN_FRONT@huggingface.co/spaces/fouad12344321/front git push hf deploy:main --force123456789101112build/dist/node_modules/public/.env.env.local.DS_Storescratch/*.log.gemini/doc/postman/1234567891011121314151617181920# Backend Integration Details
This document contains all the necessary credentials and links for connecting the frontend to the live backend API.
## Authentication Credentials
- **Email:** `e2e-lifecycle@test.com`- **Password:** `Test1234!`
### JWT Token```texteyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNmMzMzZGU4LTAzOTQtNDA5ZS05YWIyLTY1YjBhZjVkNjcyMiIsImVtYWlsIjoiZTJlLWxpZmVjeWNsZUB0ZXN0LmNvbSIsInJvbGUiOiJNQU5BR0VSIiwiZmFybUlkIjoiYTEwZWExYzYtOGQ2MS00NzhkLWIwYjAtZGY4NjgzNjU0M2UwIiwibW9kdWxlcyI6WyJub3RpZmljYXRpb25zIiwiaGVhbHRoIiwiYWktYXNzaXN0YW50IiwiZm9vZC10eXBlcyIsImZpc2gtdHlwZXMiLCJhbmFseXRpY3MiLCJhY2NvdW50aW5nIiwic2FsZXMiLCJpbnZlbnRvcnkiLCJoYXJ2ZXN0IiwicHJvY3VyZW1lbnQiLCJ0YW5rcyIsImRhc2hib2FyZCJdLCJpYXQiOjE3NzI2OTI1NTMsImV4cCI6MjEzMjY5MjU1M30.B17o9vVP8e5agC5Uge0OeTp__cY02EqqtLeu0tx8svM```
## Important Links
- **Backend Live API URL:** [https://yousseftallal-fishfarm-backend-api.hf.space/](https://yousseftallal-fishfarm-backend-api.hf.space/)- **Swagger Documentation:** [https://yousseftallal-fishfarm-backend-api.hf.space/docs](https://yousseftallal-fishfarm-backend-api.hf.space/docs)- **Postman Workspace:** [https://www.postman.com/crm999-9537/workspace/fishfarmerpsystem](https://www.postman.com/crm999-9537/workspace/fishfarmerpsystem)- **Figma UI:** [https://www.figma.com/make/NQ5ammQNPreS3CGW72Gk9j/FishFarm360-Management-System--Community-?p=f&t=sjOFAHCOJ0y6w089-0&fullscreen=1](https://www.figma.com/make/NQ5ammQNPreS3CGW72Gk9j/FishFarm360-Management-System--Community-?p=f&t=sjOFAHCOJ0y6w089-0&fullscreen=1)12345678910111213141516171819202122232425262728# -----------------------------# 1️⃣ Build Stage# -----------------------------FROM node:20-alpine AS builder
WORKDIR /app
COPY package*.json ./RUN npm install
COPY . .RUN npm run build
# -----------------------------# 2️⃣ Production Stage# -----------------------------FROM node:20-alpine
WORKDIR /app
RUN npm install -g serve
COPY --from=builder /app/build ./build
EXPOSE 7860
CMD ["serve", "-s", "build", "-l", "7860"]12345678910---title: Frontendemoji: 🚀colorFrom: bluecolorTo: indigosdk: dockerpinned: false---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference12345678910111213141516version: '3.8'
services: frontend: build: context: . dockerfile: Dockerfile ports: - "8080:80" environment: - VITE_FISH_API_BASE_URL=https://yousseftallal-fishfarm-backend-api.hf.space/api/v1 restart: always
networks: default: name: fish-farm-network12345678910111213141516<!DOCTYPE html><html lang="en">
<head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="icon" type="image/png" href="/favicon.png" /> <title>FishFarm360 Management System (Community)</title></head>
<body> <div id="root"></div> <script type="module" src="/src/main.tsx"></script></body>
</html>123456789101112131415161718module.exports = { // يخبر Jest أنه سيعمل في بيئة تشبه المتصفح (مهم جداً لـ React) testEnvironment: "jsdom",
// يخبر Jest باستخدام Babel لتحويل ملفات الـ JS والـ JSX والـ TS والـ TSX transform: { "^.+\\.(js|jsx|ts|tsx)$": "babel-jest", },
// يخبر Jest بكيفية التعامل مع ملفات الـ CSS والصور (يتجاهلها لكي لا ينهار الاختبار) moduleNameMapper: { "\\.(css|less|scss|sass)$": "identity-obj-proxy", "\\.(gif|ttf|eot|svg|png)$": "<rootDir>/__mocks__/fileMock.js", },
// إعدادات إضافية لتسهيل التعامل مع DOM setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],};1import '@testing-library/jest-dom';1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677{ "name": "FishFarm360 Management System (Community)", "version": "0.1.0", "private": true, "proxy": "http://localhost:5000", "dependencies": { "@emotion/react": "^11.14.0", "@emotion/styled": "^11.14.1", "@lucide/lab": "^0.1.2", "@microsoft/fetch-event-source": "^2.0.1", "@mui/material": "^9.0.1", "@radix-ui/react-accordion": "^1.2.3", "@radix-ui/react-alert-dialog": "^1.1.6", "@radix-ui/react-aspect-ratio": "^1.1.2", "@radix-ui/react-avatar": "^1.1.3", "@radix-ui/react-checkbox": "^1.1.4", "@radix-ui/react-collapsible": "^1.1.3", "@radix-ui/react-context-menu": "^2.2.6", "@radix-ui/react-dialog": "^1.1.6", "@radix-ui/react-dropdown-menu": "^2.1.6", "@radix-ui/react-hover-card": "^1.1.6", "@radix-ui/react-label": "^2.1.2", "@radix-ui/react-menubar": "^1.1.6", "@radix-ui/react-navigation-menu": "^1.2.5", "@radix-ui/react-popover": "^1.1.6", "@radix-ui/react-progress": "^1.1.2", "@radix-ui/react-radio-group": "^1.2.3", "@radix-ui/react-scroll-area": "^1.2.3", "@radix-ui/react-select": "^2.1.6", "@radix-ui/react-separator": "^1.1.2", "@radix-ui/react-slider": "^1.2.3", "@radix-ui/react-slot": "^1.1.2", "@radix-ui/react-switch": "^1.1.3", "@radix-ui/react-tabs": "^1.1.3", "@radix-ui/react-toggle": "^1.1.2", "@radix-ui/react-toggle-group": "^1.1.2", "@radix-ui/react-tooltip": "^1.1.8", "axios": "^1.13.6", "class-variance-authority": "^0.7.1", "clsx": "*", "cmdk": "^1.1.1", "embla-carousel-react": "^8.6.0", "input-otp": "^1.4.2", "lucide-react": "^0.487.0", "next-themes": "^0.4.6", "react": "^18.3.1", "react-day-picker": "^8.10.1", "react-dom": "^18.3.1", "react-hook-form": "^7.55.0", "react-resizable-panels": "^2.1.7", "recharts": "^2.15.2", "sonner": "^2.0.3", "tailwind-merge": "*", "vaul": "^1.1.2" }, "devDependencies": { "@testing-library/jest-dom": "^6.9.1", "@testing-library/react": "^16.3.0", "@testing-library/user-event": "^14.6.1", "@types/node": "^20.10.0", "@types/react": "^19.2.14", "@types/react-dom": "^19.2.3", "@vitejs/plugin-react-swc": "^3.10.2", "jsdom": "^24.1.3", "vite": "6.3.5", "vitest": "^2.1.8" }, "scripts": { "dev": "npx vite", "build": "vite build", "test": "jest", "test:vitest": "vitest run --config vitest.config.ts", "test:unit": "vitest run --config vitest.config.ts", "test:watch": "vitest --config vitest.config.ts", "test:live": "vitest run --config vitest.live.config.ts" }}1234567{ "presets": [ ["@babel/preset-env", { "targets": { "node": "current" } }], ["@babel/preset-react", { "runtime": "automatic" }], "@babel/preset-typescript" ]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484import { useState, useEffect, useMemo } from "react";import Login from "./components/Login";import Dashboard from "./components/Dashboard";import TankManagement from "./components/TankManagement";import Accounting from "./components/Accounting";import Inventory from "./components/Inventory";import Analytics from "./components/Analytics";import AIAssistant from "./components/AIAssistant";import HealthLibrary from "./components/HealthLibrary";import NotificationCenter from "./components/NotificationCenter";import Procurement from "./components/Procurement";import SalesModule from "./components/SalesModule";import FishTypeManagement from "./components/FishTypeManagement";import FoodTypeManagement from "./components/FoodTypeManagement";import MedicineTypeManagement from "./components/MedicineTypeManagement";import { HarvestManagement } from "./components/HarvestManagement";import IoTManagement from "./components/IoTManagement";import Farms from "./components/Farms";import Tasks from "./components/Tasks";import Sidebar from "./components/Sidebar";import UserManagement from "./components/UserManagement";import { Toaster } from "./components/ui/sonner";import { User, Farm } from "./types";import { clearAuthSession, getStoredAppUser, getAccessToken,} from "./services/authSession";import { apiGet, API_BASE } from "./api";import { mockFarms } from "./mockData";import { fetchEventSource } from "@microsoft/fetch-event-source";import { getMetadata } from "./services/metaApi";import { buildModuleLabelMap, isPageAllowed, resolveAllowedPages,} from "./services/moduleAccess";
export default function App() { const [currentUser, setCurrentUser] = useState<User | null>(null); const [currentPage, setCurrentPage] = useState("dashboard"); const [selectedFarm, setSelectedFarm] = useState<Farm | null>(null); const [notifications, setNotifications] = useState<any[]>([]); const [moduleLabelMap, setModuleLabelMap] = useState<Record<string, string>>( {}, ); const allowedPages = useMemo(() => { if (!currentUser) { return ["dashboard"]; } return resolveAllowedPages(currentUser); }, [currentUser]); const effectiveAllowedPages = useMemo(() => { if (!currentUser) { return ["dashboard"]; }
return allowedPages; }, [allowedPages, currentUser]); useEffect(() => { const user = getStoredAppUser();
if (user) { setCurrentUser(user);
if (user.role?.toLowerCase() === "worker") { setCurrentPage("tasks"); }
fetchFarms(user); } }, []);
useEffect(() => { if (!currentUser) return;
const controller = new AbortController();
const asRecord = (value: unknown): Record<string, unknown> => value && typeof value === "object" ? (value as Record<string, unknown>) : {};
const toText = (value: unknown): string => { if (typeof value === "string") return value.trim(); if (typeof value === "number" || typeof value === "boolean") return String(value); return ""; };
const formatMessage = (template: string, data: Record<string, unknown>) => { if (!template) return ""; let formatted = template; Object.entries(data).forEach(([key, value]) => { formatted = formatted.replace( new RegExp(`{{${key}}}`, "g"), String(value), ); }); return formatted; };
const parseTimestampValue = (value: unknown): Date | null => { if (value instanceof Date) { return Number.isNaN(value.getTime()) ? null : value; }
if (typeof value === "number" && Number.isFinite(value)) { const normalized = Math.abs(value) < 1e12 ? value * 1000 : value; const date = new Date(normalized); return Number.isNaN(date.getTime()) ? null : date; }
if (typeof value === "string" && value.trim()) { const trimmed = value.trim(); if (/^\d+(\.\d+)?$/.test(trimmed)) { const numericValue = Number(trimmed); if (Number.isFinite(numericValue)) { const normalized = Math.abs(numericValue) < 1e12 ? numericValue * 1000 : numericValue; const date = new Date(normalized); if (!Number.isNaN(date.getTime())) return date; } }
const date = new Date(trimmed); return Number.isNaN(date.getTime()) ? null : date; }
return null; };
const pickTimestamp = (...values: unknown[]): string => { for (const value of values) { const parsed = parseTimestampValue(value); if (parsed) return parsed.toISOString(); } return new Date().toISOString(); };
const mapIncomingNotification = (payload: unknown) => { const root = asRecord(payload); const nested = asRecord(root.notification); const notification = Object.keys(nested).length > 0 ? nested : root;
const eventType = toText(root.type).toLowerCase(); if (eventType === "connected" || eventType === "heartbeat") { return null; }
const data = asRecord(notification.data);
const subjectTemplate = toText(notification.subject) || toText(root.subject) || toText(data.subject) || toText(notification.title);
const bodyTemplate = toText(notification.body) || toText(root.body) || toText(notification.message) || toText(root.message) || toText(data.body);
const subject = formatMessage(subjectTemplate, data).trim(); const message = formatMessage(bodyTemplate, data).trim(); const title = toText(notification.title) || toText(root.title) || subject || toText(notification.templateName) || toText(root.templateName) || "Notification";
if ( !subject && !message && !toText(notification.id) && !toText(root.id) ) { return null; }
const statusKey = toText(data.status).toUpperCase(); const priorityKey = toText(notification.priority).toLowerCase(); const priorityMap: Record<string, string> = { CRITICAL: "critical", HIGH: "high", WARNING: "medium", INFO: "low", };
const normalizedPriority = priorityKey === "critical" || priorityKey === "high" || priorityKey === "medium" || priorityKey === "low" ? priorityKey : priorityMap[statusKey] || "medium";
return { id: toText(notification.id) || toText(root.id) || Math.random().toString(36).slice(2, 11), title, subject: subject || title, message, type: "alert", priority: normalizedPriority, timestamp: pickTimestamp( notification.timestamp, root.timestamp, notification.createdAt, root.createdAt, notification.created_at, root.created_at, notification.sentAt, root.sentAt, ), read: false, data, }; };
const connectToSSE = async () => { console.log("Attempting to connect to Notification Stream..."); try { const token = getAccessToken(); await fetchEventSource(`${API_BASE}/notifications/stream`, { method: "GET", headers: { Authorization: `Bearer ${token}`, Accept: "text/event-stream", }, signal: controller.signal, async onopen(response) { if (!response.ok) { console.error( "Failed to connect to notifications stream:", response.status, response.statusText, ); } }, onmessage(ev) { const raw = typeof ev.data === "string" ? ev.data.trim() : String(ev.data ?? "").trim(); if (!raw || raw === "[DONE]") { return; } const looksLikeJson = raw.startsWith("{") || raw.startsWith("["); if (!looksLikeJson) { return; }
try { const payload = JSON.parse(raw); const newNotification = mapIncomingNotification(payload); if (!newNotification) { return; }
setNotifications((prev: any[]) => { const existingIndex = prev.findIndex( (item) => item.id === newNotification.id, ); if (existingIndex === -1) { return [newNotification, ...prev]; } const next = [...prev]; next[existingIndex] = { ...next[existingIndex], ...newNotification, }; return next; }); } catch (err) { console.error("Failed to parse notification event:", err); } }, onerror(err) { console.warn("SSE connection error, retrying...", err); throw err; }, }); } catch (err) { console.error("SSE fatal error:", err); } };
void connectToSSE();
return () => { controller.abort(); }; }, [currentUser]);
useEffect(() => { if (!currentUser) { setModuleLabelMap({}); return; }
let cancelled = false;
const loadMetadataModules = async () => { try { const metadata = await getMetadata(); if (!cancelled) { setModuleLabelMap(buildModuleLabelMap(metadata.modules)); } } catch { if (!cancelled) { setModuleLabelMap({}); } } };
void loadMetadataModules();
return () => { cancelled = true; }; }, [currentUser]);
useEffect(() => { if (!currentUser) return;
if ( currentPage === "dashboard" && !effectiveAllowedPages.includes("dashboard") ) { const fallbackPage = effectiveAllowedPages[0] || "tanks"; setCurrentPage(fallbackPage); return; }
if (!isPageAllowed(currentPage, effectiveAllowedPages)) { setCurrentPage(effectiveAllowedPages[0] || "tanks"); } }, [currentPage, currentUser, effectiveAllowedPages]);
const fetchFarms = async (user: User) => { try { const res = await apiGet<any>("/farms"); const apiFarms = res.data || (Array.isArray(res) ? res : []);
if (apiFarms.length > 0) { const farm = apiFarms.find((f: any) => f.id === user.farmId) || apiFarms[0]; setSelectedFarm(farm); } else if (user.farmId) { // Fallback to mock if needed, but only if they belong to one const mockFarm = mockFarms.find((f) => f.id === user.farmId); if (mockFarm) setSelectedFarm(mockFarm); } } catch (err) { console.error("Failed to fetch farms:", err); // Fallback if (user.farmId) { const mockFarm = mockFarms.find((f) => f.id === user.farmId); if (mockFarm) setSelectedFarm(mockFarm); } } };
const handleLogin = (user: User) => { setCurrentUser(user); fetchFarms(user); if (user.role?.toLowerCase() === "worker") { setCurrentPage("tasks"); } else { setCurrentPage("dashboard"); } }; const handlePageChange = (page: string) => { if (!isPageAllowed(page, effectiveAllowedPages)) { return; } setCurrentPage(page); };
const handleLogout = () => { setCurrentUser(null); clearAuthSession(); setCurrentPage("dashboard"); setSelectedFarm(null); };
if (!currentUser) { return <Login onLogin={handleLogin} />; }
return ( <div className="flex h-screen bg-[#F9FAFB]"> <Sidebar currentPage={currentPage} onPageChange={handlePageChange} onLogout={handleLogout} user={currentUser} notifications={notifications} allowedPages={effectiveAllowedPages} moduleLabelMap={moduleLabelMap} />
<div className="flex-1 overflow-auto"> {currentPage === "dashboard" && isPageAllowed("dashboard", effectiveAllowedPages) && ( <Dashboard user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "tanks" && ( <TankManagement user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "accounting" && ( <Accounting user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "inventory" && ( <Inventory user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "analytics" && ( <Analytics user={currentUser} selectedFarm={selectedFarm} /> )}
{currentPage === "iot-management" && ( <IoTManagement user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "farms" && ( <Farms user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "ai-assistant" && <AIAssistant user={currentUser} />} {currentPage === "health" && ( <HealthLibrary user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "notifications" && ( <NotificationCenter user={currentUser} notifications={notifications} onUpdateNotifications={setNotifications} /> )} {currentPage === "tasks" && <Tasks user={currentUser} />} {currentPage === "procurement" && ( <Procurement user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "sales" && ( <SalesModule user={currentUser} selectedFarm={selectedFarm} allowedPages={effectiveAllowedPages} onNavigateToPage={handlePageChange} /> )} {currentPage === "fish-types" && ( <FishTypeManagement user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "food-types" && ( <FoodTypeManagement user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "medicine-types" && ( <MedicineTypeManagement user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "users" && ( <UserManagement user={currentUser} selectedFarm={selectedFarm} /> )} {currentPage === "harvest" && ( <HarvestManagement farmId={selectedFarm?.id || "farm-1"} userRole={currentUser.role} /> )} </div> <Toaster /> </div> );}123This Figma Make file includes components from [shadcn/ui](https://ui.shadcn.com/) used under [MIT license](https://github.com/shadcn-ui/ui/blob/main/LICENSE.md).
This Figma Make file includes photos from [Unsplash](https://unsplash.com) used under [license](https://unsplash.com/license).123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427# Fish Type Management - Enhanced Features
## OverviewComprehensive fish type management system with feeding rate matrices, protein requirements, meal frequency rules, critical parameters, and allowed food types.
## New Features Added
### 1. ✅ Feeding Rate Matrix**Purpose:** Define feeding rates (% of body weight) based on fish weight ranges and water temperature
**Structure:**```typescript{ weight_ranges: [ { min: 10, max: 15 }, { min: 15, max: 20 }, { min: 20, max: 30 } ], temperatures: [18, 23, 26, 30], rates: [ [2.0, 3.0, 4.25, 4.5], // Rates for 10-15g at each temp [2.0, 2.75, 4.0, 4.25], // Rates for 15-20g [1.8, 2.5, 3.75, 4.0] // Rates for 20-30g ]}```
**UI Features:**- Dynamic table with weight ranges as rows and temperatures as columns- Add/remove weight ranges- Edit rates in real-time- Visual instructions for usage
**Use Case:**System automatically calculates daily feed amount based on:- Current fish average weight- Current water temperature- Number of fish in batch
### 2. ✅ Meal Frequency Rules**Purpose:** Define how many meals per day based on fish weight
**Structure:**```typescript[ { maxWeight: 5, mealsPerDay: 6 }, // Fish up to 5g: 6 meals/day { maxWeight: 10, mealsPerDay: 5 }, // Fish 5-10g: 5 meals/day { maxWeight: 25, mealsPerDay: 4 }, // Fish 10-25g: 4 meals/day { maxWeight: 50, mealsPerDay: 3 }, // Fish 25-50g: 3 meals/day { maxWeight: null, mealsPerDay: 2 } // Fish >50g: 2 meals/day]```
**UI Features:**- List of rules with max weight and meals per day- Add/remove rules dynamically- Support for "null" (any weight above)- Visual cards for each rule
**Use Case:**System automatically determines feeding schedule based on current fish weight
### 3. ✅ Protein Requirements**Purpose:** Define protein percentage requirements based on fish size/growth stage
**Structure:**```typescript[ { minWeight: 0, maxWeight: 10, proteinPercentage: 35 }, // Fry stage { minWeight: 10, maxWeight: 50, proteinPercentage: 32 }, // Fingerling { minWeight: 50, maxWeight: 200, proteinPercentage: 30 }, // Grower { minWeight: 200, maxWeight: null, proteinPercentage: 28 } // Finisher]```
**UI Features:**- Grid layout with min/max weight ranges- Protein percentage input- Add/remove requirements- Support for null (no upper limit)
**Use Case:**- Filter food types by protein content- Recommend appropriate feed based on fish size- Quality control for feed selection
### 4. ✅ Critical Parameters**Purpose:** Flag which water quality parameters are most critical for this species
**Options:**- Temperature- DO (Dissolved Oxygen)- pH- NH3 (Ammonia)- NH4 (Ammonium)- NO2 (Nitrite)- NO3 (Nitrate)- Salinity
**UI Features:**- Grid of selectable cards- Visual checkbox/selection state- Multiple selection supported
**Use Case:**- Prioritize monitoring and alerts- Dashboard displays critical parameters first- Automated alert threshold configuration
### 5. ✅ Allowed Food Types**Purpose:** Define which food types are suitable for this fish species
**UI Features:**- List of all available food types- Visual selection cards- Food icon and name display- Checkmark for selected items
**Integration:**- Connected to Food Type Management module- Dynamic list from `mockFoodTypes`- Multi-selection supported
**Use Case:**- Filter feed options when creating feeding schedules- Prevent unsuitable feed assignment- Quality assurance for batch management
## UI/UX Improvements
### Tabbed Modal InterfaceThe create/edit modal now uses **5 tabs** for better organization:
1. **Basic Info** - Name, Scientific Name, Arabic Name - Target SGR - Description - Critical Parameters selection
2. **Water Quality** - Temperature ranges (min/optimal/max) - Dissolved Oxygen (min/safe) - pH Range (min/max) - NH3, NO2, NO3 levels - Performance Benchmarks (FCR, Survival Rate)
3. **Feeding Rates** - Interactive feeding rate matrix table - Weight ranges configuration - Temperature-based rates - Usage instructions
4. **Protein & Meals** - Protein requirements by weight - Meal frequency rules - Add/remove rules dynamically
5. **Food Types** - Allowed food types selection - Active/inactive status toggle - Additional notes
### Visual Enhancements- ✅ Color-coded selection states- ✅ Icons for visual clarity- ✅ Responsive grid layouts- ✅ Clear labels and instructions- ✅ Info cards with usage tips- ✅ Validation feedback
## Data Structure
### Complete Fish Type Schema```typescriptinterface FishType { // Basic Info id: string; name: string; scientificName: string; arabicName?: string; description?: string; // Water Quality Parameters tempMin: number; tempOptimal: number; tempMax: number; doMin: number; doSafe: number; phMin: number; phMax: number; nh3Safe: number; nh3Critical: number; no2Max: number; no3Max?: number; // Performance Benchmarks fcrMin: number; fcrMax: number; survivalRate: number; targetSGR: number; // NEW: Feeding Rate Matrix feedingRateMatrix: { weight_ranges: Array<{ min: number; max: number }>; temperatures: number[]; rates: number[][]; }; // NEW: Meal Frequency Rules mealFrequencyRules: Array<{ maxWeight: number | null; mealsPerDay: number; }>; // NEW: Protein Requirements proteinRequirements: Array<{ minWeight: number | null; maxWeight: number | null; proteinPercentage: number; }>; // NEW: Critical Parameters criticalParameters?: string[]; // NEW: Allowed Food Types allowedFoodTypes: string[]; // Food Type IDs // Metadata isActive: boolean; notes?: string; createdAt: Date; updatedAt: Date;}```
## Example Usage
### Creating a Fish Type with All Features```typescriptconst nileTilapia = { name: 'Nile Tilapia', scientificName: 'Oreochromis niloticus', arabicName: 'البلطي النيلي', // Water quality tempMin: 20, tempOptimal: 28, tempMax: 32, doMin: 3, doSafe: 5, phMin: 6.5, phMax: 8.5, // Critical parameters criticalParameters: ['DO', 'NH3', 'Temperature'], // Feeding rate matrix feedingRateMatrix: { weight_ranges: [ { min: 10, max: 20 }, { min: 20, max: 50 }, { min: 50, max: 100 } ], temperatures: [20, 25, 28, 30], rates: [ [3.0, 4.0, 4.5, 4.0], [2.5, 3.5, 4.0, 3.5], [2.0, 3.0, 3.5, 3.0] ] }, // Meal frequency mealFrequencyRules: [ { maxWeight: 5, mealsPerDay: 6 }, { maxWeight: 25, mealsPerDay: 4 }, { maxWeight: 100, mealsPerDay: 3 }, { maxWeight: null, mealsPerDay: 2 } ], // Protein requirements proteinRequirements: [ { minWeight: 0, maxWeight: 10, proteinPercentage: 35 }, { minWeight: 10, maxWeight: 50, proteinPercentage: 32 }, { minWeight: 50, maxWeight: 200, proteinPercentage: 30 }, { minWeight: 200, maxWeight: null, proteinPercentage: 28 } ], // Allowed food types allowedFoodTypes: ['1', '3', '4'], // IDs of suitable feeds isActive: true};```
## Integration with Other Modules
### 1. Feeding Schedule Creation```typescript// System uses feeding rate matrixconst feedingRate = getFeedingRate( fishType.feedingRateMatrix, currentAvgWeight, // e.g., 45g currentTemp // e.g., 27°C);
// Calculate daily feedconst dailyFeed = (biomass * feedingRate) / 100;
// Determine meal frequencyconst mealsPerDay = getMealFrequency( fishType.mealFrequencyRules, currentAvgWeight);
// Split daily feed across mealsconst feedPerMeal = dailyFeed / mealsPerDay;```
### 2. Feed Selection Filter```typescript// Only show allowed food typesconst availableFeeds = allFoodTypes.filter(feed => fishType.allowedFoodTypes.includes(feed.id) && meetsPro teinRequirement(feed, currentAvgWeight, fishType));```
### 3. Water Quality Monitoring```typescript// Prioritize critical parametersconst criticalAlerts = waterQualityReadings.filter(reading => fishType.criticalParameters.includes(reading.parameter) && reading.status === 'critical');```
## Mock Data
Mock food types are defined in the component:```typescriptconst mockFoodTypes = [ { id: '1', name: 'High Protein Tilapia Feed 32%' }, { id: '2', name: 'Fingerling Starter 38%' }, { id: '3', name: 'Grower Feed 28%' }, { id: '4', name: 'Finisher Feed 25%' }];```
## API Endpoints (For Future Backend)
```typescript// Create fish typePOST /fish-typesBody: FishType (complete schema)
// Update fish typePUT /fish-types/:idBody: Partial<FishType>
// Get fish type with all relationsGET /fish-types/:id?include=allowedFoodTypes
// Get feeding rate for specific conditionsGET /fish-types/:id/feeding-rate?weight=45&temperature=27
// Get meal frequency for weightGET /fish-types/:id/meal-frequency?weight=45
// Get protein requirement for weightGET /fish-types/:id/protein-requirement?weight=45```
## Benefits
1. **Automation:** - Auto-calculate feeding amounts - Auto-determine meal schedules - Auto-filter appropriate feeds
2. **Quality Control:** - Prevent unsuitable feed selection - Ensure protein requirements met - Monitor critical parameters
3. **Efficiency:** - Reduce manual calculations - Standardize feeding practices - Improve feed conversion rates
4. **Scalability:** - Support multiple fish species - Easy to add new species - Flexible rules system
5. **Accuracy:** - Temperature-adjusted feeding - Weight-based protein requirements - Species-specific parameters
## Testing Instructions
1. Navigate to **Fish Type Management**2. Click **"Add Fish Type"**3. Fill in all 5 tabs: - Basic Info (add critical parameters) - Water Quality (set ranges) - Feeding Rates (configure matrix) - Protein & Meals (set requirements and rules) - Food Types (select allowed types)4. Click **"Create Fish Type"**5. Verify all data is saved correctly
## Future Enhancements
- [ ] Import feeding rate matrix from CSV- [ ] Copy matrix from existing fish type- [ ] Visual graph of feeding rates- [ ] Batch update multiple fish types- [ ] Export fish type configuration to JSON- [ ] Protein requirement recommendations based on growth stage- [ ] Integration with AI for optimal feeding rates- [ ] Historical performance data visualization
---
Created: February 2026Version: 2.0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301# Growth Tracking System - FishFarm360
## OverviewComprehensive growth measurement recording and tracking system with multi-language support (English & Arabic).
## Components Created
### 1. RecordGrowthMeasurement.tsx**Location:** `/components/tanks/RecordGrowthMeasurement.tsx`
**Features:**- ✅ Record sampling measurements for fish batches- ✅ Support for detailed individual weight entry or bulk input- ✅ Real-time calculations (Average Weight, SGR, Weight Gain, Biomass)- ✅ Statistical analysis (Std Deviation, CV%)- ✅ Performance ratings (EXCELLENT, GOOD, ACCEPTABLE, POOR)- ✅ Success modal with recommendations- ✅ Multi-language support (EN/AR)- ✅ RTL support for Arabic- ✅ Responsive design
**Key Calculations:**```javascript// Average WeightaverageWeight = totalSampleWeight / sampleSize
// Specific Growth Rate (SGR)SGR = [(ln(currentWeight) - ln(lastWeight)) / days] × 100
// Weight GainweightGain = currentWeight - lastWeightweightGainPercentage = (weightGain / lastWeight) × 100
// Estimated BiomassestimatedBiomass = (currentCount × averageWeight) / 1000```
**Usage:**```tsx<RecordGrowthMeasurement open={showModal} onClose={() => setShowModal(false)} batch={{ id: 'batch-001', batchNumber: 'BATCH-2026-001', tankName: 'Tank A-01', fishType: 'Nile Tilapia', daysInCulture: 45, lastWeight: 250, currentCount: 920 }} language="en" // or "ar" onSuccess={(data) => console.log('Saved:', data)}/>```
### 2. GrowthHistory.tsx**Location:** `/components/tanks/GrowthHistory.tsx`
**Features:**- ✅ Timeline view of all growth measurements- ✅ Interactive growth chart (Weight & SGR over time)- ✅ Performance badges and ratings- ✅ Quick access to record new measurements- ✅ Multi-language support- ✅ Responsive layout
**Usage:**```tsx<GrowthHistory batch={batchInfo} measurements={[...measurements]} language="en" onMeasurementAdded={() => { // Refresh data }}/>```
### 3. Translation System**Location:** `/i18n/translations.ts`
**Supported Languages:**- English (en)- Arabic (ar) with RTL support
**Usage:**```tsximport { getTranslation, Language } from '../../i18n/translations';
const t = (key: string) => getTranslation('en', key);t('growthMeasurement.title') // "Record Growth Sampling"```
## Demo Page**Location:** `/components/GrowthTrackingDemo.tsx`
Access via sidebar: **"Growth Tracking Demo"**
Features:- Test record growth measurement modal- View growth history timeline- See multi-language support- Test all features with mock data
## Data Schema
### GrowthMeasurement Interface```typescriptinterface GrowthMeasurement { id: string; batchId: string; tankId: string; // Measurement Details measuredAt: Date; daysInCulture: number; // Sampling sampleSize: number; totalSampleWeightGrams: number; averageWeightGrams: number; minWeightGrams: number; maxWeightGrams: number; stdDeviationGrams?: number; coefficientOfVariation?: number; // Optional Length averageLengthCm?: number; conditionFactor?: number; // Estimated Totals estimatedFishCount: number; estimatedBiomassKg: number; // Growth Metrics sgr?: number; // Specific Growth Rate (%/day) adg?: number; // Average Daily Gain (g/day) weightGainGrams?: number; weightGainPercentage?: number; // Feed Conversion fcr?: number; // Feed Conversion Ratio survivalRate?: number; // Performance Ratings fcrRating?: 'EXCELLENT' | 'GOOD' | 'ACCEPTABLE' | 'POOR'; sgrRating?: 'EXCELLENT' | 'GOOD' | 'ACCEPTABLE' | 'POOR'; overallRating?: 'EXCELLENT' | 'GOOD' | 'ACCEPTABLE' | 'POOR'; recommendations?: string[]; // Metadata measuredBy?: string; isEstimate: boolean; notes?: string; createdAt: Date;}```
## Mock Data**Location:** `/mockData.ts`
Three sample measurements available:- `mockGrowthMeasurements[0]` - Day 45 (GOOD rating)- `mockGrowthMeasurements[1]` - Day 15 (EXCELLENT rating)- `mockGrowthMeasurements[2]` - Day 60 (ACCEPTABLE rating)
## Integration Points
### In Tank ManagementAdd to batch detail view:```tsximport RecordGrowthMeasurement from './tanks/RecordGrowthMeasurement';
// In batch row<Button onClick={() => setShowGrowthModal(true)}> Sample Growth</Button>```
### In DashboardQuick action shortcut:```tsx<Button onClick={() => openGrowthTracking()}> <Scale className="w-4 h-4 mr-2" /> Record Growth</Button>```
## Key Features
### 1. Detailed Weight Entry- Individual fish weights input- Bulk paste support (comma/newline separated)- Automatic statistics calculation- Weight distribution analysis
### 2. Real-time Calculations- Instant feedback as user types- SGR rating with color coding- Weight gain percentage- Estimated total biomass
### 3. Validation- Sample size: 10-100 fish (recommended 20-50)- Required fields checking- Date validation (not future)- Logical weight ranges
### 4. Performance RatingsSGR Ratings:- 🟢 EXCELLENT: > 2.5%/day- 🟡 GOOD: 2.0-2.5%/day- 🟠 ACCEPTABLE: 1.5-2.0%/day- 🔴 POOR: < 1.5%/day
### 5. Multi-languageAll UI text translatable:- Form labels- Button text- Validation messages- Success messages- Recommendations
## API Endpoints (For Future Backend)
```typescript// Record new measurementPOST /tanks/:tankId/batches/:batchId/growth-measurementsBody: { measuredAt: Date, sampleSize: number, totalSampleWeightGrams: number, individualWeights?: number[], notes?: string}
// Get growth historyGET /tanks/:tankId/batches/:batchId/growth-measurements
// Get single measurementGET /growth-measurements/:id
// Update measurementPUT /growth-measurements/:id
// Delete measurementDELETE /growth-measurements/:id```
## Testing Instructions
1. **Login** to the system2. Navigate to **"Growth Tracking Demo"** in sidebar3. Click **"Record Growth Measurement"** button4. Fill in the form: - Sample size: 30 - Total weight: 9750g - Optional: Enable detailed entry and paste weights5. Review real-time calculations6. Click **"Save Measurement"**7. See success modal with performance summary8. Click **"Show Growth History"** to view timeline and chart
## Language Switching
To test Arabic:```tsx<RecordGrowthMeasurement language="ar" // ... other props/>```
The UI will automatically:- Switch to RTL layout- Display Arabic text- Mirror component alignment
## Dependencies- React- Recharts (for growth charts)- Lucide React (icons)- UI Components (shadcn/ui based)
## Future Enhancements- [ ] Weight distribution histogram- [ ] Export to PDF/Excel- [ ] Photo upload for sampling- [ ] Multiple fish type comparison- [ ] Predictive growth modeling- [ ] Push notifications for sampling reminders- [ ] Batch comparison analytics- [ ] Mobile app integration
## SupportFor questions or issues, contact the development team.
---Created: February 2026Version: 1.0.0123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338# Harvest Module - Complete Implementation
## Overviewوحدة الحصاد الشاملة (Harvest Module) هي نظام متكامل لإدارة دورة الحصاد الكاملة من التنبؤ إلى الإكمال، مع التدريج، إنشاء المخزون، ولوحات التحليلات.
## Features Implemented
### 1. Harvest Dashboard (لوحة تحكم الحصاد)- **KPI Cards**: عرض مؤشرات الأداء الرئيسية - الحصادات النشطة - الكمية المحصودة هذا الشهر - متوسط FCR - الأحواض الجاهزة للحصاد - متوسط معدل البقاء - التوصية التالية
- **Active Harvests List**: قائمة الحصادات النشطة مع: - معلومات الحوض والدفعة - نوع الحصاد (Full/Partial/Selective) - شريط التقدم - الوزن المدرج vs المقدر - زر المتابعة
- **Completed Harvests**: الحصادات المكتملة مع ملخص سريع
### 2. Start Harvest Workflow (سير عمل بدء الحصاد)نموذج متعدد الخطوات يتضمن 4 مراحل:
#### Step 1: Harvest Details (تفاصيل الحصاد)- اختيار الحوض والدفعة- نوع الحصاد: - **Full Harvest**: حصاد كامل (100%) - **Partial Harvest**: حصاد جزئي مع slider لتحديد النسبة - **Selective Harvest**: حصاد انتقائي (الأسماك الكبيرة فقط)- التاريخ والوقت- الوزن المقدر (تلقائي)- فحص الطقس- ملاحظات إضافية
#### Step 2: Grading Interface (واجهة التدريج)- **Progress Bar**: شريط تقدم يعرض الكمية المدرجة vs المقدرة- **Grade Selection Cards**: بطاقات اختيار الدرجات: - Super (⭐): 300-500g @ 50 EGP/kg - Grade 1 (🔵): 200-300g @ 45 EGP/kg - Grade 2 (🟠): 150-200g @ 40 EGP/kg - Sherr (🔴): <150g @ 30 EGP/kg - Waste (⚠️): 0 EGP/kg
- **Weight Entry**: إدخال الوزن مع حساب تلقائي للقيمة- **Condition Selection**: اختيار حالة الأسماك (Excellent/Good/Fair/Poor)- **Notes**: ملاحظات اختيارية- **Recorded Grades List**: قائمة بالدرجات المسجلة مع إمكانية الحذف- **Auto-save**: حفظ تلقائي كل 30 ثانية
#### Step 3: Review & Complete (المراجعة والإكمال)- **Harvest Summary**: ملخص الحصاد - المعلومات الأساسية - الوزن المقدر vs الفعلي - نسبة الدقة
- **Grade Distribution**: توزيع الدرجات - رسم بياني شريطي أفقي - مقارنة مع المتوقع (species average) - تحليل الفروقات
- **Financial Performance**: الأداء المالي - إجمالي الإيرادات - تكاليف الإنتاج (علف، تشغيل، زريعة) - تكاليف الحصاد (عمالة، نقل، تغليف، ثلج، أخرى) - صافي الربح وهامش الربح - التكلفة والإيراد والربح لكل كيلوجرام - FCR
- **Batch Impact**: تأثير على الدفعة - الحالة قبل وبعد الحصاد - الأسماك والكتلة الحيوية المتبقية - حالة الدفعة الجديدة
- **Next Steps Checklist**: قائمة الخطوات التالية - إنشاء lots المخزون - أرقام اللوت التلقائية - نوع التخزين وتاريخ الانتهاء - القيود المحاسبية
- **Validation & Warnings**: التحقق والتحذيرات - تحذير إذا هامش الربح < 15% - تحذير إذا الفرق عن المقدر > 20%
#### Step 4: Completion Confirmation (تأكيد الإكمال)- **Success Message**: رسالة نجاح مع رقم الحصاد- **Completion Checklist**: قائمة بما تم إنجازه- **Inventory Created**: قائمة lots المخزون المنشأة- **Quick Actions**: إجراءات سريعة - عرض المخزون - إنشاء طلب بيع - عرض التحليلات - طباعة التقرير - إرسال بالبريد الإلكتروني - مشاركة QR codes
- **Summary Stats**: إحصائيات ملخصة
### 3. Harvest History & Analytics (تاريخ الحصاد والتحليلات)- **Filters**: فلاتر بالفترة الزمنية ونوع السمك- **KPIs**: مؤشرات الأداء - إجمالي المحصود - متوسط هامش الربح - متوسط FCR - إجمالي الإيرادات - متوسط معدل البقاء - أفضل أداء
- **Grade Distribution Trends**: اتجاهات توزيع الدرجات - رسم بياني خطي للاتجاهات - مؤشرات الارتفاع/الانخفاض - Insights ذكية
- **Revenue by Grade**: الإيرادات حسب الدرجة - رسم بياني شريطي أفقي مكدس
- **Recent Harvests Table**: جدول الحصادات الأخيرة - قابل للفرز والبحث
- **Performance Alerts**: تنبيهات الأداء - تحذيرات FCR المرتفع - تهاني للأداء الممتاز
### 4. Tank Harvest Performance (أداء حصاد الحوض)- **Tank Overview**: نظرة عامة على الحوض - الحجم - عدد الحصادات - الإنتاج مدى الحياة - الإيرادات مدى الحياة
- **Performance Metrics**: مقاييس الأداء - متوسط FCR - متوسط البقاء - متوسط دورة النمو
- **Harvest Timeline**: خط زمني للحصادات - تصور بصري للحصادات - تفاصيل كل حصاد
- **Grade Distribution Comparison**: مقارنة توزيع الدرجات - جدول مقارنة عبر الحصادات - مؤشرات الاتجاه
- **Insights**: رؤى ذكية - تحليل الاتجاهات - توصيات
- **Full Harvest History Table**: جدول تاريخ الحصاد الكامل - قابل للتصدير (CSV)
## Components Created
### Main Components1. `HarvestManagement.tsx` - المكون الرئيسي2. `HarvestDashboard.tsx` - لوحة التحكم3. `StartHarvestWorkflow.tsx` - سير عمل بدء الحصاد4. `HarvestHistory.tsx` - تاريخ الحصاد والتحليلات5. `TankHarvestPerformance.tsx` - أداء حصاد الحوض
### Workflow Steps1. `HarvestDetailsStep.tsx` - خطوة التفاصيل2. `HarvestGradingStep.tsx` - خطوة التدريج3. `HarvestReviewStep.tsx` - خطوة المراجعة4. `HarvestCompletionStep.tsx` - خطوة التأكيد
### Shared Components1. `GradeCard.tsx` - بطاقة الدرجة2. `HarvestProgressBar.tsx` - شريط تقدم الحصاد3. `FinancialSummaryCard.tsx` - بطاقة الملخص المالي4. `GradeDistributionChart.tsx` - رسم بياني توزيع الدرجات
### Context1. `HarvestContext.tsx` - إدارة حالة الحصاد
### Typesتم تحديث `types.ts` بـ:- `HarvestType`: 'FULL' | 'PARTIAL' | 'SELECTIVE'- `HarvestStatus`: 'DRAFT' | 'GRADING' | 'REVIEW' | 'COMPLETED' | 'CANCELLED'- `HarvestCondition`: 'EXCELLENT' | 'GOOD' | 'FAIR' | 'POOR'- `GradeType`: 'SUPER' | 'GRADE_1' | 'GRADE_2' | 'SHERR' | 'WASTE'- `HarvestCosts`: تفاصيل تكاليف الحصاد- `HarvestEvent`: تحديث شامل- `HarvestGrading`: تحديث شامل- `FishGradePricing`: إضافة gradeType و color و icon
## Design System
### Colors- **Harvest Status**: - DRAFT: #3B82F6 (Blue) - COMPLETED: #10B981 (Green) - CANCELLED: #6B7280 (Gray)
- **Harvest Types**: - FULL: #8B5CF6 (Purple) 🟣 - PARTIAL: #F59E0B (Orange) 🟠 - SELECTIVE: #EC4899 (Pink) 🩷
- **Grade Quality**: - Super: #10B981 (Green) ⭐ - Grade 1: #3B82F6 (Blue) 🔵 - Grade 2: #F59E0B (Orange) 🟠 - Sherr: #EF4444 (Red) 🔴 - Waste: #DC2626 (Dark Red) ⚠️
- **Alerts**: - Positive: #10B981 (Green) - Warning: #F59E0B (Yellow) - Loss: #EF4444 (Red)
### Icons- استخدام Lucide React للأيقونات- استخدام Emojis للتصنيفات والحالات
## Data Flow
1. **Start Harvest**: المستخدم يبدأ حصاد جديد2. **Enter Details**: إدخال تفاصيل الحصاد ونوعه3. **Grade Fish**: تدريج الأسماك مع تسجيل الأوزان4. **Review**: مراجعة البيانات وإدخال التكاليف5. **Complete**: إكمال الحصاد وإنشاء المخزون6. **Inventory Created**: إنشاء lots المخزون تلقائياً7. **Available for Sales**: المنتجات متاحة للبيع فوراً
## Integration Points
### مع Inventory Module- إنشاء `HarvestedInventory` تلقائياً عند إكمال الحصاد- ربط كل lot بـ tankId و harvestEventId- تتبع القدرة البيعية
### مع Sales Module- المنتجات المحصودة متاحة فوراً في Sales Orders- عرض Tank name في كل line item- تتبع أصل كل منتج مباع
### مع Tank Management- تحديث حالة الدفعة (Batch Status)- تحديث الكتلة الحيوية (Biomass)- تحديث عدد الأسماك- حساب FCR و Survival Rate
### مع Accounting- إنشاء قيود محاسبية تلقائياً- تسجيل الإيرادات والتكاليف- حساب الأرباح
## Mobile Optimization
### Grading Interface- تصميم Portrait Mode الأساسي- بطاقات الدرجات بحجم 120×120px كحد أدنى- إدخال الوزن بحجم كبير (64px height)- لوحة مفاتيح رقمية أصلية- عمليات بيد واحدة- دعم الوضع الأفقي- إمكانية العمل بدون اتصال (Offline)- مزامنة تلقائية عند الاتصال
### Accessibility- وضع التباين العالي للاستخدام الخارجي- خطوط كبيرة (16px min body, 24px inputs)- إدخال صوتي للعمل بدون استخدام اليدين- متوافق مع قارئ الشاشة
## Future Enhancements
1. **Harvest Prediction AI** - التنبؤ بأفضل وقت للحصاد - تحليل السعر والطلب - تقدير توزيع الدرجات - حساب الربحية المتوقعة
2. **QR Code Traceability** - إنشاء QR codes لكل lot - تتبع كامل من الزريعة للمستهلك - معلومات الشهادات والجودة
3. **Weather Integration** - جلب بيانات الطقس الفعلية - توصيات بناءً على الطقس - تنبيهات الظروف غير المناسبة
4. **Advanced Analytics** - تحليل الموسمية - مقارنة الأداء عبر المزارع - Benchmarking ضد معايير الصناعة - تحليل الاتجاهات طويلة المدى
5. **Integration with Scales** - ربط مع موازين إلكترونية - قراءة تلقائية للأوزان - تقليل الأخطاء البشرية
## Usage
### للوصول للوحدة:1. تسجيل الدخول للنظام2. الضغط على "Harvest" في القائمة الجانبية3. عرض لوحة التحكم الرئيسية
### لبدء حصاد جديد:1. الضغط على "Start New Harvest"2. اختيار الحوض والدفعة3. تحديد نوع الحصاد4. تدريج الأسماك5. مراجعة وإدخال التكاليف6. إكمال الحصاد
### لعرض التحليلات:1. الضغط على "View History" أو اختيار "Analytics" من القائمة2. استخدام الفلاتر لتحديد الفترة3. عرض الاتجاهات والرؤى4. الضغط على أي tank لعرض أداءه المفصل
## Notes
- جميع البيانات حالياً mock data للعرض التوضيحي- في التطبيق الحقيقي، سيتم استبدال البيانات بـ API calls فعلية- التصميم responsive ويعمل على جميع أحجام الشاشات- الواجهة مُحسّنة للاستخدام الميداني- دعم RTL جاهز للغة العربية (يحتاج تفعيل)
## Color Scheme- Primary: #0A4D68 (Ocean Blue)- Secondary: #088395 (Teal)- Success: #10B981 (Green)- Warning: #F59E0B (Orange/Amber)- Error: #EF4444 (Red)- Background: #F9FAFB (Light Gray)
---
تم تنفيذ الوحدة بالكامل وفقاً للتصميم المفصل في `/imports/harvest-design-overview.md`. جميع الشاشات الـ8 والميزات المطلوبة موجودة ووظيفية.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204# Harvest Per Tank Updates - Summary
## ✅ Changes Made
### 1. **Updated Types** (`/types.ts`)
Added tank-specific fields to `HarvestedInventory`:
```typescriptexport interface HarvestedInventory { id: string; tankId: string; // ✅ NEW - Links harvest to specific tank farmId: string; // ✅ NEW - Links harvest to farm harvestEventId: string; // ✅ NEW - Links to harvest event fishType: FishType; gradePricing: FishGradePricing; weight: number; storageType: StorageType; expiryDate: Date; harvestedAt: Date; createdAt: Date; updatedAt: Date;}```
### 2. **Updated Harvested Inventory View** (`/components/sales/HarvestedInventoryView.tsx`)
**Added Features:**- ✅ Tank ID added to each harvest item- ✅ Farm ID added to each harvest item- ✅ Harvest Event ID added to each harvest item- ✅ Tank Name displayed in harvest cards (Badge)- ✅ Tank filter dropdown added to filters- ✅ `getTankName()` helper function to display tank names
**Example Data:**```typescript{ id: 'harv-inv-001', tankId: 'tank-a05', // Tank A05 farmId: selectedFarm.id, harvestEventId: 'harvest-001', fishType: { name: 'Nile Tilapia', ... }, gradePricing: { gradeName: 'Super', pricePerKg: 50, ... }, weight: 120, // kg storageType: 'FRESH', // Total value: 120 kg × 50 EGP/kg = 6,000 EGP}```
**UI Updates:**- Filter section now includes: Storage Type | Expiry Status | **Tank Filter** ✅- Each harvest card shows tank name: `Nile Tilapia [Tank A05]` ✅
### 3. **Updated Accounting Module** (`/components/Accounting.tsx`)
**Added Features:**- ✅ Tank-based revenue calculation- ✅ Revenue mapping per tank: - Tank A05: 16,000 EGP - Tank B03: 7,225 EGP - Tank C01: 12,000 EGP - All Tanks: 45,000 EGP
**Tank-Based Profit Calculation:**When you select a specific tank:- **Total Expenses** - Filtered by selected tank- **Estimated Revenue** - Based on tank's harvested inventory- **Projected Profit** - Revenue - Expenses for that tank- **Profit Margin** - (Profit / Revenue) × 100%
**Example for Tank A05:**```Harvested Stock:- 120 kg Super grade @ 50 EGP/kg = 6,000 EGP- 200 kg Grade 1 @ 45 EGP/kg = 9,000 EGPTotal Revenue: 16,000 EGP
Tank Expenses: (filtered from Accounting)Projected Profit: 16,000 - Expenses```
### 4. **New Section: Cost Allocation by Tank**
Added detailed breakdown showing:- Total expenses per tank- Cost per fish for each tank- Visual progress bar showing percentage of total costs- Tank species and name
## 🎯 How It Works
### Complete Flow:
1. **Harvest a Tank** - Create HarvestEvent with tankId - Generate HarvestGrading items 2. **Create Harvested Inventory** - Each inventory item has: - `tankId` (which tank it came from) - `harvestEventId` (which harvest event) - `farmId` (which farm) 3. **View in Sales Module** - Go to Sales → Harvested Stock - Filter by tank to see specific tank's inventory - Each card shows tank name badge 4. **Sell Products** - Create sales orders - Link to specific harvested inventory items 5. **Calculate Profit in Accounting** - Select specific tank from filter - View expenses for that tank only - View revenue from that tank's harvests - Calculate profit = revenue - expenses
## 📊 Visual Examples
### Harvested Inventory Card:```┌────────────────────────────────────────┐│ Nile Tilapia [Tank A05] 🐟 ││ Super (300-500g) │├────────────────────────────────────────┤│ Weight: 120 kg ││ Price: 50 EGP/kg ││ Total Value: 6,000 EGP ││ ││ 🟢 FRESH | ✅ Good (15d) ││ 📅 Harvested: 2026-02-15 │└────────────────────────────────────────┘```
### Accounting - Tank Selection:```Filters: [This Month] [Tank A05 ▼]
┌─ Financial Overview ────────────────┐│ Total Expenses: $8,450 ││ Estimated Revenue: $16,000 │ ← Tank A05 specific│ Projected Profit: $7,550 ││ Profit Margin: 47.2% │└─────────────────────────────────────┘
┌─ Cost Allocation by Tank ───────────┐│ Tank A05 - Nile Tilapia ││ $8,450 $2.11/fish ││ ████████░░░░░░░░ 45% ││ ││ Tank B03 - Seabass ��│ $5,200 $3.25/fish ││ █████░░░░░░░░░░░ 28% │└─────────────────────────────────────┘```
## 🔍 Where to See Changes
1. **Sales Module → Harvested Stock Tab** - Tank badge on each harvest card - Tank filter in top filters - Filtered stats by tank
2. **Accounting Module** - Tank selector shows tank-specific finances - Cost Allocation by Tank section at bottom - Revenue changes based on selected tank
3. **Data Structure** (`types.ts`) - HarvestedInventory interface updated - All harvest items now have tankId, farmId, harvestEventId
## 📝 Mock Data
The system now has 3 harvest items:- **2 items from Tank A05** (harvest-001) - 120 kg Nile Tilapia Super - 200 kg Nile Tilapia Grade 1 - Total: 320 kg, 16,000 EGP
- **1 item from Tank B03** (harvest-002) - 85 kg European Seabass Premium - Total: 85 kg, 7,225 EGP
## ✅ Verification Checklist
To verify the changes are working:
- [ ] Go to Sales Module → Harvested Stock- [ ] Check if Tank name badge appears on harvest cards- [ ] Use Tank filter dropdown - select "Tank A05"- [ ] Verify only Tank A05 items are shown- [ ] Go to Accounting Module- [ ] Select Tank from dropdown filter- [ ] Check if Revenue changes based on tank selection- [ ] Scroll down to "Cost Allocation by Tank" section- [ ] Verify each tank shows its expenses and cost per fish
---
**Last Updated:** February 28, 2026**Status:** ✅ Completed and Deployed12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394import { getAccessToken } from './services/authSession';
export const DEFAULT_API_BASE = 'https://fouadkhaild-asd.hf.space/api/v1';
const getEnvValue = (key: string): string | undefined => { const importMetaEnv = (import.meta as ImportMeta & { env?: Record<string, string | undefined> }).env; const fromVite = importMetaEnv?.[key]; if (fromVite?.trim()) { return fromVite.trim(); }
if (typeof process !== 'undefined' && process.env?.[key]?.trim()) { return process.env[key]?.trim(); }
return undefined;};
export const API_BASE = (getEnvValue('VITE_FISH_API_BASE_URL') || getEnvValue('FISH_API_BASE_URL') || DEFAULT_API_BASE).replace(/\/+$/, '');
const buildHeaders = (): HeadersInit => { const token = getAccessToken(); return { ...(token ? { Authorization: `Bearer ${token}` } : {}), };};
type ApiErrorResponse = { status: number; statusText: string; data: unknown;};
const request = async <T>(path: string, method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE', body?: unknown): Promise<T> => { const response = await fetch(`${API_BASE}${path}`, { method, headers: { ...(body !== undefined ? { 'Content-Type': 'application/json' } : {}), ...buildHeaders(), }, ...(body === undefined ? {} : { body: JSON.stringify(body) }), });
const text = await response.text(); const trimmedText = text.trim(); const parsedBody = (() => { if (!trimmedText) { return undefined; }
try { return JSON.parse(text); } catch { return text; } })();
if (!response.ok) { console.error('API request failed', { method, path, status: response.status, statusText: response.statusText, rawResponse: text, });
const error = new Error( `${method} ${path} failed [${response.status}]: ${trimmedText || response.statusText}`, ) as Error & { response?: ApiErrorResponse };
error.response = { status: response.status, statusText: response.statusText, data: parsedBody ?? { message: trimmedText || response.statusText, }, };
throw error; }
if (parsedBody === undefined) { return undefined as T; }
return parsedBody as T;};
export const apiGet = <T>(path: string): Promise<T> => request<T>(path, 'GET');export const apiPost = <T>(path: string, body: unknown): Promise<T> => request<T>(path, 'POST', body);export const apiPut = <T>(path: string, body: unknown): Promise<T> => request<T>(path, 'PUT', body);export const apiPatch = <T>(path: string, body: unknown): Promise<T> => request<T>(path, 'PATCH', body);export const apiDelete = <T>(path: string): Promise<T> => request<T>(path, 'DELETE');123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import { apiGet, apiPost, apiPatch, apiDelete } from "../api";
export const getFeedInventory = () => apiGet<any>("/inventory/feed");
export const createFeed = (data: any) => apiPost<any>("/inventory/feed", data);
export const createMedicine = (data: any) => apiPost<any>("/inventory/medicine", data);
export const createFishBatch = (data: any) => apiPost<any>("/inventory/batches", data);
export const createHarvestedFish = (data: any) => apiPost<any>("/inventory/harvested", data);
export const getFeedByFoodType = (foodId: string) => apiGet<any>(`/inventory/feed/food-type/${foodId}`);
export const getBatches = () => apiGet<any>("/inventory/batches");
export const getBatchById = (id: string) => apiGet<any>(`/inventory/batches/${id}`);
export const quarantineBatch = (id: string) => apiPatch<any>(`/inventory/batches/${id}/quarantine`, {});
export const healthCheckBatch = (id: string, data: any) => apiPatch<any>(`/inventory/batches/${id}/health-check`, data);
export const allocateBatch = (id: string, data: any) => apiPatch<any>(`/inventory/batches/${id}/allocate`, data);
export const deleteFeed = (id: string) => apiDelete<any>(`/inventory/feed/${id}`);
export const getMedicineInventory = () => apiGet<any>("/inventory/medicine");
export const getMedicineInventoryTotal = () => apiGet<any>("/inventory/medicine/total");
export const updateMedicineBatchQuantity = (id: string, newQuantity: number) => apiPatch<any>(`/inventory/medicine/${id}/quantity`, { newQuantity });
export const deleteMedicineBatch = (id: string) => apiDelete<any>(`/inventory/medicine/${id}`);
export const addMedicineStock = (data: { medicineTypeId: string; quantity: number; mlPerUnit: number; company: string; receivedDate: string; expiryDate: string;}) => apiPost<any>("/inventory/medicine/stock", data);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969import { useCallback, useEffect, useMemo, useState } from "react";import { Camera, CheckCircle2, History, Loader2, RefreshCw, Sparkles, Stethoscope, Upload,} from "lucide-react";import { toast } from "sonner";import { User } from "../types";import { AI_API_BASE, AIHealthServiceStatus, AIPredictResponse, AutomatedHealthReport, buildAutomatedHealthReportWithLibrary, confidenceToPercent, getAIServiceHealth, getAnnotatedImageSrc, humanizePredictionLabel, predictFishDisease,} from "../services/aiDetectionApi";import { createHealthCheck, formatHealthStatus, getHealthStatusColor, HealthCheckResponseDTO, recordRecoveredHealthCheck,} from "../services/healthCheckApi";import { fetchAllTankHealthOverviews, TankHealthOverview,} from "../services/tankHealthOverview";import { Badge } from "./ui/badge";import { Button } from "./ui/button";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Input } from "./ui/input";import { Label } from "./ui/label";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "./ui/select";import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";import { HealthCheckModal } from "./tanks/modals/HealthCheckModal";import { HealthChecksTab } from "./tanks/tabs/HealthChecksTab";import { RobotHealthReport } from "./health/RobotHealthReport";
interface AIAssistantProps { user: User;}
const getBatchLabel = (batch: any) => batch?.batchNumber ? `Batch ${batch.batchNumber}` : `Batch ${String(batch?.id || "").slice(0, 8)}`;
const formatDateTime = (value?: string) => { if (!value) return "Unknown"; const date = new Date(value); if (Number.isNaN(date.getTime())) return value; return date.toLocaleString(undefined, { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", });};
export default function AIAssistant({ user }: AIAssistantProps) { const [tanks, setTanks] = useState<any[]>([]); const [batchesByTank, setBatchesByTank] = useState<Record<string, any[]>>({}); const [healthHistoryByTank, setHealthHistoryByTank] = useState< Record<string, HealthCheckResponseDTO[]> >({}); const [healthOverviewByTank, setHealthOverviewByTank] = useState< Record<string, TankHealthOverview> >({}); const [selectedTankId, setSelectedTankId] = useState(""); const [selectedBatchId, setSelectedBatchId] = useState(""); const [loadingHistory, setLoadingHistory] = useState(true); const [selectedFile, setSelectedFile] = useState<File | null>(null); const [previewUrl, setPreviewUrl] = useState<string | null>(null); const [analysis, setAnalysis] = useState<AIPredictResponse | null>(null); const [report, setReport] = useState<AutomatedHealthReport | null>(null); const [aiHealth, setAiHealth] = useState<AIHealthServiceStatus | null>(null); const [loadingAIHealth, setLoadingAIHealth] = useState(true); const [isAnalyzing, setIsAnalyzing] = useState(false); const [isSavingCheck, setIsSavingCheck] = useState(false); const [showHealthModal, setShowHealthModal] = useState(false); const [selectedBatchForModal, setSelectedBatchForModal] = useState<any>(null); const [improvingRecordId, setImprovingRecordId] = useState<string | null>( null, ); const [expandedImage, setExpandedImage] = useState<{ src: string; title: string; } | null>(null);
const loadTankHealthHistory = useCallback(async () => { setLoadingHistory(true); try { const result = await fetchAllTankHealthOverviews(); const overviewMap = result.overviews.reduce< Record<string, TankHealthOverview> >((acc, overview) => { acc[overview.tank.id] = overview; return acc; }, {});
setTanks(result.tanks); setBatchesByTank(result.batchesByTank); setHealthHistoryByTank(result.historyByTank); setHealthOverviewByTank(overviewMap); setSelectedTankId((previous) => { if (previous && result.tanks.some((tank) => tank.id === previous)) return previous; return result.tanks[0]?.id || ""; }); } catch (error) { toast.error( `Failed to load tank health history: ${(error as Error).message}`, ); } finally { setLoadingHistory(false); } }, []);
const loadAIHealth = useCallback(async () => { setLoadingAIHealth(true); try { const nextHealth = await getAIServiceHealth(); setAiHealth(nextHealth); } catch (error) { toast.error( `AI endpoint health check failed: ${(error as Error).message}`, ); setAiHealth(null); } finally { setLoadingAIHealth(false); } }, []);
useEffect(() => { void loadTankHealthHistory(); void loadAIHealth(); }, [loadAIHealth, loadTankHealthHistory]);
useEffect(() => { const currentBatches = batchesByTank[selectedTankId] || []; setSelectedBatchId((previous) => { if (previous && currentBatches.some((batch) => batch.id === previous)) { return previous; } return currentBatches[0]?.id || ""; }); }, [batchesByTank, selectedTankId]);
useEffect(() => { if (!selectedFile) { setPreviewUrl(null); return; }
const objectUrl = URL.createObjectURL(selectedFile); setPreviewUrl(objectUrl); return () => URL.revokeObjectURL(objectUrl); }, [selectedFile]);
const selectedTank = useMemo( () => tanks.find((tank) => tank.id === selectedTankId) || null, [selectedTankId, tanks], ); const selectedTankBatches = useMemo( () => batchesByTank[selectedTankId] || [], [batchesByTank, selectedTankId], ); const selectedTankHistory = useMemo( () => healthHistoryByTank[selectedTankId] || [], [healthHistoryByTank, selectedTankId], ); const selectedTankOverview = healthOverviewByTank[selectedTankId] || null; const recentHistory = selectedTankHistory.slice(0, 3); const selectedBatch = selectedTankBatches.find((batch) => batch.id === selectedBatchId) || null; const annotatedImageSrc = getAnnotatedImageSrc(analysis); const matchingDiseaseHistory = useMemo(() => { if (!report?.isKnownClassification) return []; const labels = [ report.payload.bacterialType, report.template.key, report.template.title, ...report.template.aliases, ] .filter(Boolean) .map((value) => String(value).toLowerCase());
return selectedTankHistory .filter((record) => { const disease = String(record.bacterialType || "").toLowerCase(); return labels.some( (label) => disease && (disease.includes(label) || label.includes(disease)), ); }) .slice(0, 5); }, [report, selectedTankHistory]);
const handleAnalyze = async () => { if (!selectedFile) { toast.error("Please choose an image first."); return; }
setIsAnalyzing(true); try { const result = await predictFishDisease(selectedFile); setAnalysis(result); setReport(await buildAutomatedHealthReportWithLibrary(result)); toast.success("AI image analysis completed."); } catch (error) { toast.error((error as Error).message); } finally { setIsAnalyzing(false); } };
const handleSaveAnalysis = async () => { if (!selectedBatchId) { toast.error("Please choose a tank batch before saving."); return; } if (!report) { toast.error("Run AI analysis before saving a health check."); return; } if (!report.isKnownClassification) { toast.error( report.saveBlockedReason || "Unknown AI results cannot be saved to history.", ); return; }
setIsSavingCheck(true); try { await createHealthCheck(selectedBatchId, { batchId: selectedBatchId, healthStatus: report.payload.healthStatus!, checkType: report.payload.checkType || "TARGETED", bacterialType: report.payload.bacterialType, bacterialLoadPercentage: report.payload.bacterialLoadPercentage, treatmentSuggestion: report.payload.treatmentSuggestion, feedingAdvice: report.payload.feedingAdvice, checkedAt: report.payload.checkedAt, medicineId: report.payload.medicineId || undefined, }); toast.success("AI health report saved to tank history."); await loadTankHealthHistory(); } catch (error) { toast.error((error as Error).message); } finally { setIsSavingCheck(false); } };
const handleMarkImproved = async ( _batch: any, record: HealthCheckResponseDTO, ) => { setImprovingRecordId(record.id); try { await recordRecoveredHealthCheck(record.batchId, record); toast.success("Recovery report saved."); await loadTankHealthHistory(); } catch (error) { toast.error( `Failed to save recovery report: ${(error as Error).message}`, ); } finally { setImprovingRecordId(null); } };
return ( <div className="space-y-6 p-6"> <div className="flex flex-col gap-3 lg:flex-row lg:items-center lg:justify-between"> <div> <h1 className="text-2xl">AI Assistant</h1> <p className="text-gray-600"> Live AI endpoint status, fixed robot reports, and batch-by-batch tank health history. </p> </div> <div className="flex flex-wrap gap-2"> <Badge className="bg-purple-100 text-purple-700"> <Sparkles className="mr-1 h-3 w-3" /> AI-Powered </Badge> <Badge variant="outline" className={ aiHealth?.status === "healthy" ? "border-emerald-200 bg-emerald-50 text-emerald-700" : "border-slate-200 text-slate-600" } > {loadingAIHealth ? "Checking AI endpoint..." : aiHealth?.status === "healthy" ? `AI API Healthy • ${aiHealth.version || "ready"}` : "AI API status unavailable"} </Badge> <Button variant="outline" onClick={() => void loadAIHealth()} disabled={loadingAIHealth} > <RefreshCw className={`mr-2 h-4 w-4 ${loadingAIHealth ? "animate-spin" : ""}`} /> Check AI Link </Button> <Button variant="outline" onClick={() => void loadTankHealthHistory()} disabled={loadingHistory} > <RefreshCw className={`mr-2 h-4 w-4 ${loadingHistory ? "animate-spin" : ""}`} /> Refresh Data </Button> </div> </div>
<Card> <CardContent className="flex flex-col gap-2 p-4 text-sm text-slate-600 lg:flex-row lg:items-center lg:justify-between"> <span>AI endpoint: {AI_API_BASE}</span> <span> {aiHealth?.timestamp ? `Last health check: ${formatDateTime(aiHealth.timestamp)}` : "Health check pending"} </span> </CardContent> </Card>
<Tabs defaultValue="disease" className="space-y-4"> <TabsList className="grid w-full grid-cols-2 bg-white lg:w-auto"> <TabsTrigger value="disease"> <Camera className="mr-2 h-4 w-4" /> Disease Detection </TabsTrigger> <TabsTrigger value="history"> <History className="mr-2 h-4 w-4" /> Tank Health History </TabsTrigger> </TabsList>
<TabsContent value="disease" className="space-y-4"> <Card> <CardHeader> <CardTitle className="text-sm"> Generate Fixed AI Health Report </CardTitle> <p className="text-xs text-gray-600"> Select the tank and batch, run the AI image analysis, then save the fixed report into the health-check history endpoint. </p> </CardHeader> <CardContent className="grid gap-4 md:grid-cols-2 xl:grid-cols-3"> <div className="space-y-2"> <Label htmlFor="ai-tank-select">Tank</Label> <Select value={selectedTankId} onValueChange={setSelectedTankId} > <SelectTrigger id="ai-tank-select"> <SelectValue placeholder="Select tank" /> </SelectTrigger> <SelectContent> {tanks.map((tank) => ( <SelectItem key={tank.id} value={tank.id}> {tank.name} </SelectItem> ))} </SelectContent> </Select> </div> <div className="space-y-2"> <Label htmlFor="ai-batch-select">Batch</Label> <Select value={selectedBatchId} onValueChange={setSelectedBatchId} > <SelectTrigger id="ai-batch-select"> <SelectValue placeholder="Select batch" /> </SelectTrigger> <SelectContent> {selectedTankBatches.map((batch) => ( <SelectItem key={batch.id} value={batch.id}> {getBatchLabel(batch)} </SelectItem> ))} </SelectContent> </Select> </div> <div className="space-y-2"> <Label>Current tank status</Label> <div className="rounded-lg border border-slate-200 bg-slate-50 px-4 py-3 text-sm text-slate-700"> {selectedTankOverview?.latestRecord ? `${formatHealthStatus(selectedTankOverview.latestRecord.healthStatus)} • ${selectedTankOverview.currentDiseaseLabel}` : "No saved reports yet"} </div> </div> </CardContent> </Card>
<div className="grid grid-cols-1 gap-5 lg:grid-cols-[460px_minmax(0,760px)] lg:items-start lg:justify-start"> <Card> <CardHeader> <CardTitle className="text-sm">Upload Fish Image</CardTitle> <p className="text-xs text-gray-600"> This uses the verified AI endpoint from the CRM app integration. </p> </CardHeader> <CardContent className="space-y-4"> <Input id="ai-health-image" type="file" accept="image/*" className="hidden" onChange={(event) => setSelectedFile(event.target.files?.[0] || null) } />
<div className="grid w-fit grid-cols-2 gap-3"> <div className="space-y-2"> <div className="flex items-center justify-between gap-2"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500"> Original image </p> {previewUrl && ( <Button type="button" variant="ghost" size="sm" className="h-7 px-2 text-xs text-[#0A4D68]" onClick={() => setExpandedImage({ src: previewUrl, title: "Original fish image", }) } > Preview </Button> )} </div> <div className="h-44 w-44 overflow-hidden rounded-lg border border-slate-200 bg-slate-50 sm:h-52 sm:w-52"> {previewUrl ? ( <button type="button" className="relative h-full w-full cursor-zoom-in overflow-hidden" onClick={() => setExpandedImage({ src: previewUrl, title: "Original fish image", }) } > <img src={previewUrl} alt="Selected fish" className="h-full w-full object-contain p-2" /> <span className="absolute bottom-2 left-2 rounded-md bg-slate-900/75 px-2 py-1 text-[10px] font-medium text-white"> Show below </span> </button> ) : ( <label htmlFor="ai-health-image" className="flex h-full w-full cursor-pointer flex-col items-center justify-center p-3 text-center transition-colors hover:bg-[#F3FBFC]" > <Upload className="mb-3 h-10 w-10 text-slate-400" /> <p className="text-sm font-medium text-slate-700"> Upload image </p> <p className="mt-1 text-xs text-slate-500"> Stays inside this square </p> </label> )} </div> </div>
<div className="space-y-2"> <div className="flex items-center justify-between gap-2"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500"> AI output </p> {annotatedImageSrc && ( <Button type="button" variant="ghost" size="sm" className="h-7 px-2 text-xs text-[#0A4D68]" onClick={() => setExpandedImage({ src: annotatedImageSrc, title: "Annotated AI output", }) } > Preview </Button> )} </div> <div className="h-44 w-44 overflow-hidden rounded-lg border border-slate-200 bg-slate-50 sm:h-52 sm:w-52"> {annotatedImageSrc ? ( <button type="button" className="relative h-full w-full cursor-zoom-in overflow-hidden" onClick={() => setExpandedImage({ src: annotatedImageSrc, title: "Annotated AI output", }) } > <img src={annotatedImageSrc} alt="Annotated AI result" className="h-full w-full object-contain p-2" /> <span className="absolute bottom-2 left-2 rounded-md bg-slate-900/75 px-2 py-1 text-[10px] font-medium text-white"> Show below </span> </button> ) : ( <div className="flex h-full w-full flex-col items-center justify-center p-3 text-center"> <Camera className="mb-3 h-10 w-10 text-slate-300" /> <p className="text-sm font-medium text-slate-700"> AI output </p> <p className="mt-1 text-xs text-slate-500"> Appears here after analysis </p> </div> )} </div> </div> </div>
<div className="flex w-fit flex-wrap gap-2"> <Button asChild variant="outline"> <label htmlFor="ai-health-image" className="cursor-pointer"> {previewUrl ? "Change Image" : "Choose Image"} </label> </Button> <Button className="flex-1 bg-[#088395] hover:bg-[#0A4D68]" onClick={handleAnalyze} disabled={!selectedFile || isAnalyzing} > {isAnalyzing ? ( <Loader2 className="mr-2 h-4 w-4 animate-spin" /> ) : ( <Sparkles className="mr-2 h-4 w-4" /> )} Analyze </Button> <Button variant="outline" onClick={() => { setSelectedFile(null); setAnalysis(null); setReport(null); }} > Reset </Button> </div>
{expandedImage && ( <div className="w-full max-w-[460px] overflow-hidden rounded-lg border border-slate-200 bg-white p-3"> <div className="mb-2 flex items-center justify-between gap-2"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500"> {expandedImage.title} </p> <Button type="button" variant="ghost" size="sm" className="h-7 px-2 text-xs" onClick={() => setExpandedImage(null)} > Hide </Button> </div> <div className="flex h-[320px] items-center justify-center overflow-auto rounded-lg bg-slate-50"> <img src={expandedImage.src} alt={expandedImage.title} className="max-h-[300px] w-auto max-w-full object-contain p-2" /> </div> </div> )} </CardContent> </Card>
<Card className="w-full max-w-[760px]"> <CardHeader> <CardTitle className="text-sm">AI Analysis Result</CardTitle> </CardHeader> <CardContent className="max-h-[70vh] overflow-y-auto pr-1"> {report ? ( <div className="space-y-4"> {!report.isKnownClassification && ( <div className="rounded-lg border border-amber-200 bg-amber-50 p-4 text-sm text-amber-800"> {report.saveBlockedReason || "Unknown AI results are displayed for review only and cannot be saved to history."} </div> )} <div className="rounded-lg border border-[#CBE7EC] bg-[#F4FBFC] p-4"> <div className="flex items-start justify-between gap-3"> <div> <p className="text-xs font-semibold uppercase tracking-wide text-[#088395]"> Top Prediction </p> <p className="mt-1 text-lg font-bold text-slate-900"> {report.topPredictionDisplay} </p> </div> <Badge className="bg-[#0A4D68] text-white"> {report.confidencePercent.toFixed(1)}% </Badge> </div> <p className="mt-2 text-sm text-slate-600"> Save target: {selectedTank?.name || "No tank selected"} {selectedBatch ? ` • ${getBatchLabel(selectedBatch)}` : ""} </p> </div>
{analysis?.predictions?.length ? ( <div className="space-y-2 rounded-lg border border-slate-200 bg-white p-4"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500"> Prediction Breakdown </p> {analysis.predictions.slice(0, 4).map((prediction) => ( <div key={`${prediction.class}-${prediction.confidence}`} className="space-y-1" > <div className="flex items-center justify-between text-sm text-slate-700"> <span> {humanizePredictionLabel(prediction.class)} </span> <span> {confidenceToPercent( prediction.confidence, ).toFixed(1)} % </span> </div> <div className="h-2 overflow-hidden rounded-full bg-slate-200"> <div className="h-full rounded-full bg-[#088395]" style={{ width: `${confidenceToPercent(prediction.confidence)}%`, }} /> </div> </div> ))} </div> ) : null}
{report.isKnownClassification && ( <> <RobotHealthReport template={report.template} healthStatus={report.mappedHealthStatus} confidencePercent={report.confidencePercent} checkedAt={report.payload.checkedAt} batchLabel={ selectedBatch ? getBatchLabel(selectedBatch) : undefined } topPredictionLabel={report.topPredictionDisplay} title="Fixed AI Health Report" compact libraryRecommendation={report.libraryRecommendation} requireLibraryRecommendation={report.diseaseDetected} />
<div className="rounded-lg border border-slate-200 bg-white p-4"> <div className="flex flex-wrap items-center justify-between gap-3"> <div> <p className="text-sm font-semibold text-slate-900"> Previous records for this disease </p> <p className="mt-1 text-xs text-slate-500"> Matched from saved health records for this tank using the disease name and Health Library aliases. </p> </div> <Badge variant="outline" className="border-[#B9E0E7] text-[#0A4D68]" > {matchingDiseaseHistory.length} record {matchingDiseaseHistory.length === 1 ? "" : "s"} </Badge> </div> {matchingDiseaseHistory.length === 0 ? ( <p className="mt-4 rounded-lg border border-dashed border-slate-200 bg-slate-50 p-4 text-sm text-slate-500"> No older saved records for this disease in the selected tank yet. </p> ) : ( <div className="mt-4 space-y-2"> {matchingDiseaseHistory.map((record) => ( <div key={record.id} className="rounded-lg border border-slate-200 bg-slate-50 p-3" > <div className="flex flex-wrap items-center justify-between gap-2"> <p className="text-sm font-semibold text-slate-900"> {record.bacterialType || "Automated report"} </p> <Badge variant="outline" className={getHealthStatusColor( record.healthStatus, )} > {formatHealthStatus(record.healthStatus)} </Badge> </div> <p className="mt-1 text-xs text-slate-500"> {formatDateTime(record.checkedAt)} </p> {record.bacterialLoadPercentage != null && ( <p className="mt-2 text-xs text-slate-600"> Recorded disease percentage:{" "} {Number( record.bacterialLoadPercentage, ).toFixed(1)} % </p> )} </div> ))} </div> )} </div> </> )}
<Button className="w-full bg-[#088395] hover:bg-[#0A4D68]" onClick={handleSaveAnalysis} disabled={ !report || !selectedBatchId || isSavingCheck || !report.isKnownClassification } > {isSavingCheck ? ( <Loader2 className="mr-2 h-4 w-4 animate-spin" /> ) : ( <Stethoscope className="mr-2 h-4 w-4" /> )} Save to Health History </Button> </div> ) : ( <div className="flex min-h-[320px] flex-col items-center justify-center text-center text-gray-500"> <Camera className="mb-3 h-12 w-12 text-gray-400" /> <p className="text-sm"> Upload an image and run AI analysis first. </p> <p className="mt-1 text-xs text-gray-400"> The result will be saved as a fixed report tied to the detected disease template. </p> </div> )} </CardContent> </Card> </div>
<Card> <CardHeader> <CardTitle className="text-sm"> Recent Checks for Selected Tank </CardTitle> </CardHeader> <CardContent> {recentHistory.length === 0 ? ( <p className="py-4 text-sm text-gray-500"> No health checks recorded for the selected tank yet. </p> ) : ( <div className="space-y-3"> {recentHistory.map((record) => ( <div key={record.id} className="rounded-lg border border-slate-200 p-4" > <div className="flex flex-wrap items-center gap-2"> <Badge variant="outline" className={getHealthStatusColor(record.healthStatus)} > {formatHealthStatus(record.healthStatus)} </Badge> <Badge variant="outline" className="border-slate-200 text-slate-600" > {record.bacterialType || "Automated report"} </Badge> </div> <p className="mt-3 text-sm font-semibold text-slate-900"> {record.bacterialType || "No saved disease label"} </p> <p className="mt-1 text-sm text-slate-500"> {formatDateTime(record.checkedAt)} </p> </div> ))} </div> )} </CardContent> </Card> </TabsContent>
<TabsContent value="history" className="space-y-4"> {loadingHistory && tanks.length === 0 ? ( <Card> <CardContent className="flex min-h-[280px] items-center justify-center"> <Loader2 className="h-6 w-6 animate-spin text-[#088395]" /> </CardContent> </Card> ) : ( <div className="grid grid-cols-1 gap-4 lg:grid-cols-[300px_1fr]"> <Card> <CardHeader> <CardTitle className="text-sm">Tanks</CardTitle> </CardHeader> <CardContent className="space-y-2"> {tanks.map((tank) => { const overview = healthOverviewByTank[tank.id]; const tankHistory = healthHistoryByTank[tank.id] || []; const tankBatches = batchesByTank[tank.id] || []; const isActive = tank.id === selectedTankId;
return ( <button key={tank.id} onClick={() => setSelectedTankId(tank.id)} className={`w-full rounded-lg border p-3 text-left transition-colors ${ isActive ? "border-[#088395] bg-[#F3FBFC]" : "border-slate-200 hover:bg-slate-50" }`} > <div className="flex items-start justify-between gap-3"> <div> <p className="font-semibold text-slate-900"> {tank.name} </p> <p className="text-xs text-slate-500"> {tankBatches.length} batch {tankBatches.length === 1 ? "" : "es"} •{" "} {tankHistory.length} report {tankHistory.length === 1 ? "" : "s"} </p> </div> {overview?.latestRecord ? ( <Badge variant="outline" className={getHealthStatusColor( overview.latestRecord.healthStatus, )} > {formatHealthStatus( overview.latestRecord.healthStatus, )} </Badge> ) : ( <Badge variant="outline" className="border-slate-200 text-slate-500" > No data </Badge> )} </div> {overview?.currentDiseaseLabel && tankHistory.length > 0 && ( <p className="mt-2 text-xs text-slate-500"> {overview.currentDiseaseLabel} </p> )} </button> ); })} </CardContent> </Card>
{selectedTank ? ( <HealthChecksTab tankBatches={selectedTankBatches} healthChecks={selectedTankHistory} loading={loadingHistory} onCreate={(batch) => { setSelectedBatchForModal( batch ?? selectedTankBatches[0] ?? null, ); setShowHealthModal(true); }} onRefresh={() => void loadTankHealthHistory()} onMarkImproved={handleMarkImproved} improvingRecordId={improvingRecordId} /> ) : ( <Card> <CardContent className="flex min-h-[280px] items-center justify-center text-sm text-slate-500"> Select a tank to view its health history. </CardContent> </Card> )} </div> )} </TabsContent> </Tabs>
{selectedTank && ( <HealthCheckModal open={showHealthModal} onOpenChange={setShowHealthModal} tank={selectedTank} tankBatches={selectedTankBatches} batchId={selectedBatchForModal?.id} onSuccess={() => void loadTankHealthHistory()} /> )} </div> );}123456789101112import { User, Farm } from '../types';import AccountingModule from './accounting/AccountingModule';
interface AccountingProps { user: User; selectedFarm: Farm | null; language?: 'en' | 'ar';}
export default function Accounting({ user, selectedFarm, language = 'en' }: AccountingProps) { return <AccountingModule user={user} selectedFarm={selectedFarm} language={language} />;}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387import { useEffect, useMemo, useState } from "react";import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";import { Button } from "./ui/button";import { Input } from "./ui/input";import { Label } from "./ui/label";import { Textarea } from "./ui/textarea";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "./ui/select";import { Fish, AlertCircle } from "lucide-react";import { FishInventoryBatch } from "../types";import { mockTanks } from "../mockData";
interface AllocateFishToTankProps { batch: FishInventoryBatch; isOpen: boolean; onClose: () => void; onAllocate: ( batchId: string, tankId: string, quantity: number, avgWeight: number, stockingDate: string, notes?: string, ) => void; farmId: string; availableTanks?: any[];}
interface FormErrors { tank?: string; quantity?: string; avgWeight?: string; stockingDate?: string; notes?: string;}
const MAX_NOTES_LENGTH = 500;
export default function AllocateFishToTank({ batch, isOpen, onClose, onAllocate, farmId, availableTanks = [],}: AllocateFishToTankProps) { const todayDate = new Date().toISOString().split("T")[0];
const [selectedTankId, setSelectedTankId] = useState<string>(""); const [quantity, setQuantity] = useState<string>(""); const [avgWeight, setAvgWeight] = useState<string>( String(batch.averageWeight ?? 0), ); const [stockingDate, setStockingDate] = useState<string>(todayDate); const [notes, setNotes] = useState<string>(""); const [errors, setErrors] = useState<FormErrors>({});
useEffect(() => { setAvgWeight(String(batch.averageWeight ?? 0)); }, [batch.id, batch.averageWeight]);
const normalizeTank = (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 || ""), status: String(tank?.status || "UNKNOWN").toUpperCase(), biomass: Number(tank?.biomass?.actual ?? tank?.biomass ?? 0), capacity: Number( tank?.biomass?.capacity ?? tank?.capacity ?? tank?.biomassLimit ?? 0, ), }; };
const tanks = useMemo(() => { const source = availableTanks.length > 0 ? availableTanks : mockTanks; const normalized = source.map(normalizeTank).filter(Boolean) as Array<{ id: string; name: string; farmId: string; status: string; biomass: number; capacity: number; }>;
return normalized.filter((tank) => { const farmMatch = !farmId || tank.farmId === farmId; const isEmpty = tank.biomass <= 0; return farmMatch && isEmpty; }); }, [availableTanks, farmId]);
const validateForm = () => { const newErrors: FormErrors = {};
if (tanks.length === 0) { newErrors.tank = "No allocatable tanks available"; }
if (!selectedTankId) { newErrors.tank = "Please select a tank"; } else if (!tanks.some((tank) => tank.id === selectedTankId)) { newErrors.tank = "Selected tank is not valid"; }
const parsedQuantity = Number(quantity); if (!quantity || Number.isNaN(parsedQuantity)) { newErrors.quantity = "Please enter a valid quantity"; } else if (!Number.isInteger(parsedQuantity) || parsedQuantity <= 0) { newErrors.quantity = "Quantity must be a whole number greater than zero"; } else if (parsedQuantity > batch.quantity) { newErrors.quantity = `Quantity cannot exceed ${batch.quantity.toLocaleString()} fish`; }
const parsedAvgWeight = Number(avgWeight); if (avgWeight === "" || Number.isNaN(parsedAvgWeight)) { newErrors.avgWeight = "Please enter average weight"; } else if (parsedAvgWeight < 0) { newErrors.avgWeight = "Average weight cannot be negative"; } else if (parsedAvgWeight > 10000) { newErrors.avgWeight = "Average weight is too high"; }
if (!stockingDate) { newErrors.stockingDate = "Please select a stocking date"; } else if (stockingDate > todayDate) { newErrors.stockingDate = "Stocking date cannot be in the future"; }
if (notes.length > MAX_NOTES_LENGTH) { newErrors.notes = `Notes cannot exceed ${MAX_NOTES_LENGTH} characters`; }
setErrors(newErrors); return Object.keys(newErrors).length === 0; };
const handleSubmit = () => { if (!validateForm()) return;
onAllocate( batch.id, selectedTankId, Number(quantity), Number(avgWeight), stockingDate, notes.trim() || undefined, );
handleClose(); };
const handleClose = () => { setSelectedTankId(""); setQuantity(""); setAvgWeight(String(batch.averageWeight ?? 0)); setStockingDate(todayDate); setNotes(""); setErrors({}); onClose(); };
return ( <Dialog open={isOpen} onOpenChange={handleClose}> <DialogContent className="max-w-2xl p-0 h-[90vh] max-h-[90vh] overflow-hidden gap-0" style={{ display: "flex", flexDirection: "column" }} > <div className="h-full flex flex-col" style={{ minHeight: 0 }}> <DialogHeader className="px-6 pt-6 pb-3 shrink-0 border-b"> <DialogTitle className="text-2xl flex items-center gap-2"> <Fish className="w-6 h-6 text-[#0A4D68]" /> Allocate Fish to Tank </DialogTitle> </DialogHeader>
<div className="allocate-modal-scroll px-6 py-4 space-y-6 pb-8" style={{ flex: 1, minHeight: 0 }} > <div className="bg-blue-50 border border-blue-200 rounded-lg p-4"> <div className="flex items-start gap-3"> <div className="bg-blue-100 p-2 rounded-lg"> <Fish className="w-5 h-5 text-[#0A4D68]" /> </div> <div className="flex-1"> <div className="flex items-center gap-2 mb-2"> <p className="text-sm font-bold text-gray-700"> Inventory Batch </p> <span className="text-[10px] text-gray-400 font-mono"> ID: {batch.id.split("-")[0]} </span> </div> <div className="grid grid-cols-2 gap-3"> <div> <p className="text-xs text-gray-600">Species</p> <p className="font-medium">{batch.species}</p> </div> <div> <p className="text-xs text-gray-600">Available</p> <p className="font-medium"> {batch.quantity.toLocaleString()} fish </p> </div> </div> </div> </div> </div>
<div className="space-y-2"> <Label htmlFor="tank"> Select Tank <span className="text-red-500">*</span> </Label> <Select value={selectedTankId} onValueChange={setSelectedTankId}> <SelectTrigger id="tank" className={errors.tank ? "border-red-500" : ""} > <SelectValue placeholder="Choose a tank..." /> </SelectTrigger> <SelectContent> {tanks.map((tank) => ( <SelectItem key={tank.id} value={tank.id}> {tank.name} </SelectItem> ))} {tanks.length === 0 && ( <SelectItem value="__no_tanks__" disabled> No available tanks for allocation </SelectItem> )} </SelectContent> </Select> {errors.tank && ( <p className="text-xs text-red-600">{errors.tank}</p> )} {tanks.length === 0 && ( <p className="text-xs text-orange-600"> No allocatable tanks found. Tank must be in ACTIVE, READY, or EMPTY status. </p> )} </div>
<div className="space-y-2"> <Label htmlFor="avgWeight"> Avg Weight (g) <span className="text-red-500">*</span> </Label> <Input id="avgWeight" type="number" value={avgWeight} onChange={(e) => { setAvgWeight(e.target.value); if (errors.avgWeight) { setErrors({ ...errors, avgWeight: undefined }); } }} placeholder="Enter average weight in grams" className={errors.avgWeight ? "border-red-500" : ""} min="0" step="0.01" /> {errors.avgWeight && ( <p className="text-xs text-red-600 flex items-center gap-1"> <AlertCircle className="w-3 h-3" /> {errors.avgWeight} </p> )} </div>
<div className="space-y-2"> <Label htmlFor="quantity"> Quantity to Stock <span className="text-red-500">*</span> </Label> <div className="relative"> <Input id="quantity" type="number" value={quantity} onChange={(e) => { setQuantity(e.target.value); if (errors.quantity) { setErrors({ ...errors, quantity: undefined }); } }} placeholder="Enter number of fish" className={errors.quantity ? "border-red-500" : ""} min="1" step="1" max={batch.quantity} /> <span className="absolute right-3 top-1/2 -translate-y-1/2 text-sm text-gray-500"> fish </span> </div> {errors.quantity && ( <p className="text-xs text-red-600 flex items-center gap-1"> <AlertCircle className="w-3 h-3" /> {errors.quantity} </p> )} {quantity && !errors.quantity && Number(quantity) > 0 && ( <p className="text-xs text-gray-600"> Remaining in inventory:{" "} <span className="font-medium"> {(batch.quantity - Number(quantity)).toLocaleString()} fish </span> </p> )} </div>
<div className="space-y-2"> <Label htmlFor="stockingDate"> Stocking Date <span className="text-red-500">*</span> </Label> <Input id="stockingDate" type="date" value={stockingDate} onChange={(e) => { setStockingDate(e.target.value); if (errors.stockingDate) { setErrors({ ...errors, stockingDate: undefined }); } }} max={todayDate} className={errors.stockingDate ? "border-red-500" : ""} /> <p className="text-xs text-gray-500">Default: Today</p> {errors.stockingDate && ( <p className="text-xs text-red-600">{errors.stockingDate}</p> )} </div>
<div className="space-y-2"> <Label htmlFor="notes">Notes (optional)</Label> <Textarea id="notes" value={notes} onChange={(e) => { setNotes(e.target.value); if (errors.notes) { setErrors({ ...errors, notes: undefined }); } }} placeholder="Add any additional notes..." rows={3} className={errors.notes ? "border-red-500" : ""} /> <div className="flex items-center justify-between"> <p className="text-xs text-gray-500"> {notes.length}/{MAX_NOTES_LENGTH} </p> {errors.notes && ( <p className="text-xs text-red-600">{errors.notes}</p> )} </div> </div> </div>
<div className="shrink-0 border-t px-6 py-4 bg-background flex items-center justify-end gap-3"> <Button variant="outline" onClick={handleClose}> Cancel </Button> <Button onClick={handleSubmit} className="bg-[#0A4D68] hover:bg-[#083d52]" > <Fish className="w-4 h-4 mr-2" /> Stock Tank </Button> </div> </div> </DialogContent> </Dialog> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508import { useState } from 'react';import { Card, CardContent, CardHeader, CardTitle } from './ui/card';import { Button } from './ui/button';import { Badge } from './ui/badge';import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';import { Slider } from './ui/slider';import { TrendingUp, Brain, Target, Zap, DollarSign, Fish, Activity} from 'lucide-react';import { LineChart, Line, BarChart, Bar, AreaChart, Area, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer, Legend } from 'recharts';import { User, Farm } from '../types';
interface AnalyticsProps { user: User; selectedFarm: Farm | null;}
export default function Analytics({ user, selectedFarm }: AnalyticsProps) { const [predictionDays, setPredictionDays] = useState([30]); const [feedRate, setFeedRate] = useState([3.5]); const [temperature, setTemperature] = useState([26]);
// Growth Prediction Data const growthPrediction = [ { week: 'Week 1', actual: 120, predicted: 122 }, { week: 'Week 2', actual: 145, predicted: 147 }, { week: 'Week 3', actual: 175, predicted: 173 }, { week: 'Week 4', actual: 210, predicted: 208 }, { week: 'Week 5', actual: 245, predicted: 248 }, { week: 'Week 6', actual: 285, predicted: 287 }, { week: 'Week 7', predicted: 328 }, { week: 'Week 8', predicted: 372 }, ];
// Profitability Analysis const profitabilityData = [ { month: 'May', revenue: 38000, costs: 28500, profit: 9500 }, { month: 'Jun', revenue: 42000, costs: 30200, profit: 11800 }, { month: 'Jul', revenue: 45000, costs: 31800, profit: 13200 }, { month: 'Aug', revenue: 48000, costs: 33500, profit: 14500 }, { month: 'Sep', revenue: 51000, costs: 35100, profit: 15900 }, { month: 'Oct', revenue: 54000, costs: 36800, profit: 17200 }, ];
// FCR Trends const fcrTrends = [ { date: 'Sep 15', fcr: 1.42, target: 1.40 }, { date: 'Sep 22', fcr: 1.38, target: 1.40 }, { date: 'Sep 29', fcr: 1.35, target: 1.40 }, { date: 'Oct 06', fcr: 1.37, target: 1.40 }, { date: 'Oct 13', fcr: 1.35, target: 1.40 }, { date: 'Oct 20', fcr: 1.33, target: 1.40 }, ];
// KPIs const kpis = [ { label: 'Predicted Weight (30 days)', value: '420g', change: '+47%', trend: 'up' }, { label: 'Forecasted FCR', value: '1.32', change: '-5%', trend: 'down' }, { label: 'Survival Rate Prediction', value: '96.8%', change: '+1.2%', trend: 'up' }, { label: 'Expected ROI', value: '42%', change: '+8%', trend: 'up' }, ];
// Scenario simulation results const scenarioResults = { currentFeed: { finalWeight: 420, fcr: 1.32, cost: 3250, profit: 14800 }, optimized: { finalWeight: 445, fcr: 1.28, cost: 3180, profit: 16200 } };
return ( <div className="p-6 space-y-6"> <div className="flex items-center justify-between"> <div> <h1 className="text-2xl">AI Analytics & Predictions</h1> <p className="text-gray-600">Data-driven insights for optimal performance</p> </div> <Badge className="bg-purple-100 text-purple-700"> <Brain className="w-3 h-3 mr-1" /> AI-Powered </Badge> </div>
{/* Key Performance Indicators */} <div className="grid grid-cols-1 md:grid-cols-4 gap-4"> {kpis.map((kpi, index) => ( <Card key={index}> <CardHeader className="pb-2"> <CardTitle className="text-sm">{kpi.label}</CardTitle> </CardHeader> <CardContent> <div className="text-2xl">{kpi.value}</div> <p className={`text-xs mt-1 flex items-center gap-1 ${ kpi.trend === 'up' ? 'text-green-600' : 'text-blue-600' }`}> <TrendingUp className="w-3 h-3" /> {kpi.change} vs target </p> </CardContent> </Card> ))} </div>
<Tabs defaultValue="growth" className="space-y-4"> <TabsList> <TabsTrigger value="growth">Growth Prediction</TabsTrigger> <TabsTrigger value="profitability">Profitability</TabsTrigger> <TabsTrigger value="scenario">Scenario Simulation</TabsTrigger> <TabsTrigger value="performance">Performance Metrics</TabsTrigger> </TabsList>
{/* Growth Prediction */} <TabsContent value="growth" className="space-y-4"> <Card> <CardHeader> <CardTitle className="text-sm">AI Growth Forecast Model</CardTitle> <p className="text-xs text-gray-600"> Predictions based on historical data, water quality, and feeding patterns </p> </CardHeader> <CardContent> <ResponsiveContainer width="100%" height={300}> <AreaChart data={growthPrediction}> <defs> <linearGradient id="colorActual" x1="0" y1="0" x2="0" y2="1"> <stop offset="5%" stopColor="#3b82f6" stopOpacity={0.8}/> <stop offset="95%" stopColor="#3b82f6" stopOpacity={0}/> </linearGradient> <linearGradient id="colorPredicted" x1="0" y1="0" x2="0" y2="1"> <stop offset="5%" stopColor="#10b981" stopOpacity={0.8}/> <stop offset="95%" stopColor="#10b981" stopOpacity={0}/> </linearGradient> </defs> <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="week" /> <YAxis label={{ value: 'Weight (g)', angle: -90, position: 'insideLeft' }} /> <Tooltip /> <Legend /> <Area type="monotone" dataKey="actual" stroke="#3b82f6" fillOpacity={1} fill="url(#colorActual)" name="Actual Weight" /> <Area type="monotone" dataKey="predicted" stroke="#10b981" fillOpacity={1} fill="url(#colorPredicted)" strokeDasharray="5 5" name="Predicted Weight" /> </AreaChart> </ResponsiveContainer> </CardContent> </Card>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-4"> <Card className="lg:col-span-2"> <CardHeader> <CardTitle className="text-sm">Model Insights</CardTitle> </CardHeader> <CardContent className="space-y-3"> <div className="flex items-start gap-3 p-3 bg-blue-50 rounded-lg"> <Brain className="w-5 h-5 text-blue-600 mt-0.5" /> <div> <p className="text-sm">Optimal Growth Trajectory</p> <p className="text-xs text-gray-600 mt-1"> Current growth rate is 3% above predicted baseline. Fish are responding well to current feeding regime. </p> </div> </div> <div className="flex items-start gap-3 p-3 bg-green-50 rounded-lg"> <Target className="w-5 h-5 text-green-600 mt-0.5" /> <div> <p className="text-sm">Harvest Window</p> <p className="text-xs text-gray-600 mt-1"> Recommended harvest at 112 days (Week 16) when fish reach optimal market size of 650-700g. </p> </div> </div> <div className="flex items-start gap-3 p-3 bg-purple-50 rounded-lg"> <Zap className="w-5 h-5 text-purple-600 mt-0.5" /> <div> <p className="text-sm">Growth Acceleration Opportunity</p> <p className="text-xs text-gray-600 mt-1"> Increasing feed protein content by 2% could improve SGR by 0.3% with minimal cost increase. </p> </div> </div> </CardContent> </Card>
<Card> <CardHeader> <CardTitle className="text-sm">Prediction Confidence</CardTitle> </CardHeader> <CardContent className="space-y-4"> <div> <div className="flex items-center justify-between mb-2"> <span className="text-sm">Model Accuracy</span> <span className="text-sm">94.2%</span> </div> <div className="h-2 bg-gray-200 rounded-full overflow-hidden"> <div className="h-full bg-green-600" style={{ width: '94.2%' }} /> </div> </div> <div> <div className="flex items-center justify-between mb-2"> <span className="text-sm">Data Quality</span> <span className="text-sm">91%</span> </div> <div className="h-2 bg-gray-200 rounded-full overflow-hidden"> <div className="h-full bg-blue-600" style={{ width: '91%' }} /> </div> </div> <div> <div className="flex items-center justify-between mb-2"> <span className="text-sm">Historical Match</span> <span className="text-sm">88.5%</span> </div> <div className="h-2 bg-gray-200 rounded-full overflow-hidden"> <div className="h-full bg-purple-600" style={{ width: '88.5%' }} /> </div> </div> <div className="pt-3 border-t"> <p className="text-xs text-gray-600"> Predictions are updated every 6 hours based on real-time sensor data and growth sampling. </p> </div> </CardContent> </Card> </div> </TabsContent>
{/* Profitability Dashboard */} <TabsContent value="profitability" className="space-y-4"> <div className="grid grid-cols-1 lg:grid-cols-2 gap-4"> <Card> <CardHeader> <CardTitle className="text-sm">Revenue vs Cost Trends</CardTitle> </CardHeader> <CardContent> <ResponsiveContainer width="100%" height={300}> <LineChart data={profitabilityData}> <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="month" /> <YAxis /> <Tooltip /> <Legend /> <Line type="monotone" dataKey="revenue" stroke="#10b981" strokeWidth={2} name="Revenue" /> <Line type="monotone" dataKey="costs" stroke="#ef4444" strokeWidth={2} name="Costs" /> <Line type="monotone" dataKey="profit" stroke="#3b82f6" strokeWidth={2} name="Profit" /> </LineChart> </ResponsiveContainer> </CardContent> </Card>
<Card> <CardHeader> <CardTitle className="text-sm">Profit Margin Analysis</CardTitle> </CardHeader> <CardContent> <ResponsiveContainer width="100%" height={300}> <BarChart data={profitabilityData}> <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="month" /> <YAxis /> <Tooltip /> <Bar dataKey="profit" fill="#3b82f6" /> </BarChart> </ResponsiveContainer> </CardContent> </Card> </div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4"> <Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Projected Annual Revenue</CardTitle> </CardHeader> <CardContent> <div className="text-2xl">$648,000</div> <p className="text-xs text-green-600 mt-1 flex items-center gap-1"> <TrendingUp className="w-3 h-3" /> +18% vs last year </p> </CardContent> </Card>
<Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Average Profit Margin</CardTitle> </CardHeader> <CardContent> <div className="text-2xl">31.8%</div> <p className="text-xs text-green-600 mt-1"> Above industry average (28%) </p> </CardContent> </Card>
<Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Break-even Point</CardTitle> </CardHeader> <CardContent> <div className="text-2xl">Day 98</div> <p className="text-xs text-gray-600 mt-1"> 14 days ahead of schedule </p> </CardContent> </Card> </div> </TabsContent>
{/* Scenario Simulation */} <TabsContent value="scenario" className="space-y-4"> <Card> <CardHeader> <CardTitle className="text-sm">What-If Scenario Planning</CardTitle> <p className="text-xs text-gray-600"> Simulate different conditions to optimize your operations </p> </CardHeader> <CardContent className="space-y-6"> <div className="grid grid-cols-1 md:grid-cols-3 gap-6"> <div className="space-y-3"> <label className="text-sm"> Prediction Timeframe: {predictionDays[0]} days </label> <Slider value={predictionDays} onValueChange={setPredictionDays} min={7} max={90} step={1} /> </div>
<div className="space-y-3"> <label className="text-sm"> Feed Rate: {feedRate[0]}% body weight/day </label> <Slider value={feedRate} onValueChange={setFeedRate} min={2} max={5} step={0.1} /> </div>
<div className="space-y-3"> <label className="text-sm"> Water Temperature: {temperature[0]}°C </label> <Slider value={temperature} onValueChange={setTemperature} min={22} max={30} step={0.5} /> </div> </div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="p-4 border-2 border-gray-200 rounded-lg"> <h4 className="text-sm mb-3">Current Settings</h4> <div className="space-y-2"> <div className="flex justify-between text-sm"> <span className="text-gray-600">Predicted Final Weight</span> <span>{scenarioResults.currentFeed.finalWeight}g</span> </div> <div className="flex justify-between text-sm"> <span className="text-gray-600">Expected FCR</span> <span>{scenarioResults.currentFeed.fcr}</span> </div> <div className="flex justify-between text-sm"> <span className="text-gray-600">Total Feed Cost</span> <span>${scenarioResults.currentFeed.cost}</span> </div> <div className="flex justify-between text-sm pt-2 border-t"> <span>Projected Profit</span> <span className="text-blue-600">${scenarioResults.currentFeed.profit}</span> </div> </div> </div>
<div className="p-4 border-2 border-green-200 bg-green-50 rounded-lg"> <h4 className="text-sm mb-3 flex items-center gap-2"> <Zap className="w-4 h-4" /> Optimized Scenario </h4> <div className="space-y-2"> <div className="flex justify-between text-sm"> <span className="text-gray-600">Predicted Final Weight</span> <span className="text-green-700">{scenarioResults.optimized.finalWeight}g (+{scenarioResults.optimized.finalWeight - scenarioResults.currentFeed.finalWeight}g)</span> </div> <div className="flex justify-between text-sm"> <span className="text-gray-600">Expected FCR</span> <span className="text-green-700">{scenarioResults.optimized.fcr} (-0.04)</span> </div> <div className="flex justify-between text-sm"> <span className="text-gray-600">Total Feed Cost</span> <span className="text-green-700">${scenarioResults.optimized.cost} (-$70)</span> </div> <div className="flex justify-between text-sm pt-2 border-t border-green-200"> <span>Projected Profit</span> <span className="text-green-700">${scenarioResults.optimized.profit} (+${scenarioResults.optimized.profit - scenarioResults.currentFeed.profit})</span> </div> </div> </div> </div>
<Button className="w-full"> Apply Optimized Settings </Button> </CardContent> </Card> </TabsContent>
{/* Performance Metrics */} <TabsContent value="performance" className="space-y-4"> <Card> <CardHeader> <CardTitle className="text-sm">Feed Conversion Ratio Trends</CardTitle> </CardHeader> <CardContent> <ResponsiveContainer width="100%" height={300}> <LineChart data={fcrTrends}> <CartesianGrid strokeDasharray="3 3" /> <XAxis dataKey="date" /> <YAxis domain={[1.2, 1.5]} /> <Tooltip /> <Legend /> <Line type="monotone" dataKey="fcr" stroke="#3b82f6" strokeWidth={2} name="Actual FCR" /> <Line type="monotone" dataKey="target" stroke="#10b981" strokeWidth={2} strokeDasharray="5 5" name="Target FCR" /> </LineChart> </ResponsiveContainer> </CardContent> </Card>
<div className="grid grid-cols-1 md:grid-cols-3 gap-4"> <Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Performance Score</CardTitle> </CardHeader> <CardContent> <div className="text-2xl">8.7/10</div> <div className="flex gap-1 mt-2"> {[...Array(9)].map((_, i) => ( <div key={i} className="flex-1 h-2 bg-green-600 rounded-full" /> ))} <div className="flex-1 h-2 bg-gray-200 rounded-full" /> </div> <p className="text-xs text-gray-600 mt-2">Excellent performance</p> </CardContent> </Card>
<Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Efficiency Rating</CardTitle> </CardHeader> <CardContent> <div className="text-2xl">92%</div> <p className="text-xs text-green-600 mt-1 flex items-center gap-1"> <TrendingUp className="w-3 h-3" /> Top 10% of farms </p> </CardContent> </Card>
<Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Sustainability Index</CardTitle> </CardHeader> <CardContent> <div className="text-2xl">A+</div> <p className="text-xs text-gray-600 mt-1"> Low environmental impact </p> </CardContent> </Card> </div> </TabsContent> </Tabs> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120import { useMemo, useState } from "react";import { Check, ChevronsUpDown } from "lucide-react";import { buttonVariants } from "./ui/button";import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList,} from "./ui/command";import { Popover, PopoverContent, PopoverTrigger } from "./ui/popover";import { Label } from "./ui/label";import { cn } from "./ui/utils";
export interface ComboboxItem { value: string; label: string; sub?: string; disabled?: boolean;}
interface ComboboxProps { items: ComboboxItem[]; value: string | null; onChange: (item: ComboboxItem | null) => void; label?: string; placeholder?: string; searchPlaceholder?: string; emptyText?: string; disabled?: boolean;}
export default function Combobox({ items, value, onChange, label, placeholder = "Search or select...", searchPlaceholder = "Search...", emptyText = "No items found.", disabled = false,}: ComboboxProps) { const [open, setOpen] = useState(false);
const selectedItem = useMemo( () => items.find((item) => item.value === value) ?? null, [items, value], );
const isDisabled = disabled;
return ( <div className="grid gap-2"> {label && <Label>{label}</Label>} <Popover open={open} onOpenChange={setOpen}> <PopoverTrigger asChild> <button type="button" role="combobox" aria-expanded={open} className={cn( buttonVariants({ variant: "outline" }), "w-full justify-between font-normal", )} disabled={isDisabled} > <span className="truncate text-left"> {selectedItem ? selectedItem.label : placeholder} </span> <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" /> </button> </PopoverTrigger> <PopoverContent portalled={false} side="bottom" align="start" className="z-[70] w-[var(--radix-popover-trigger-width)] p-0" > <Command> <CommandInput placeholder={searchPlaceholder} /> <CommandList> <CommandEmpty>{emptyText}</CommandEmpty> <CommandGroup> {items.map((item) => ( <CommandItem key={item.value} value={item.value} keywords={[item.label, item.sub ?? "", item.value]} disabled={item.disabled} onSelect={() => { onChange(item.value === value ? null : item); setOpen(false); }} className="flex items-start gap-2 py-2" > <div className="flex min-w-0 flex-1 flex-col"> <span className="truncate">{item.label}</span> {item.sub && ( <span className="text-xs text-gray-500 truncate"> {item.sub} </span> )} </div> <Check className={cn( "ml-2 h-4 w-4 shrink-0", value === item.value ? "opacity-100" : "opacity-0", )} /> </CommandItem> ))} </CommandGroup> </CommandList> </Command> </PopoverContent> </Popover> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754// ============================================================// Dashboard.tsx – Hazem Yasser// ============================================================// WHY useEffect + fetch?// The dashboard must show live data the moment it loads. We// call GET /api/v1/dashboard inside a useEffect so React first// renders the skeleton/loading UI and then hydrates it with// real numbers when the API responds. This avoids a blank// screen AND keeps the UI responsive while waiting.//// WHY keep mockFarms for the farm-selector?// The /dashboard endpoint does not return a list of all farms// the user belongs to – that requires a separate /farms route// which is not yet part of Hazem's task scope. The farm dropdown// is therefore still backed by mockFarms so the rest of the app// (tank management, etc.) can still receive a selectedFarm prop.// ============================================================
import { useState, useEffect, useRef } from "react";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "./ui/select";import { Button } from "./ui/button";import { Badge } from "./ui/badge";import { Progress } from "./ui/progress";import { Fish, Scale, Wheat, DollarSign, TrendingUp, AlertCircle, Clock, Calendar, RefreshCw, CheckCircle2, Cpu, Wifi, WifiOff, Thermometer, Zap, Activity,} from "lucide-react";import { User, Farm } from "../types";import { mockFarms } from "../mockData";import { apiGet } from "../api";import { subscribeToTankSensorStream, SensorReadingEvent,} from "../services/iotApi";
// ── Types that mirror the actual /api/v1/dashboard response shape ──interface DashboardFishSummary { totalActiveFish: string | number; // API returns string "12,500" with comma! totalBiomassKg: number; biomassCapacityPercentage?: number; activeTanks?: number; totalTanks?: number;}interface DashboardFeedStock { totalStockKg: number; estimatedDaysRemaining?: number; feedStockRemainingLabel?: string;}interface DashboardPredictedRevenue { totalProjectedRevenue: number; nextHarvestRevenue?: number; nearestHarvestDate?: string; nextHarvestDateFormatted?: string;}interface DashboardUpcomingHarvest { tankName: string; estimatedWeight?: number; projectedRevenue?: number; earliestHarvestDate?: string; batches?: { fishType?: string; daysToHarvest?: number; status?: string }[];}interface DashboardWaterAlert { tankName?: string; parameter?: string; value?: string | number; status?: string;}interface DashboardData { fishSummary?: DashboardFishSummary; feedStock?: DashboardFeedStock; predictedRevenue?: DashboardPredictedRevenue; upcomingHarvests?: DashboardUpcomingHarvest[]; waterQualityAlerts?: DashboardWaterAlert[];}
interface DashboardProps { user: User; selectedFarm: Farm | null;}
// ── Sensor threshold helpers ──type StatusLevel = "optimal" | "acceptable" | "warning" | "critical";
const getTemperatureStatus = (temp: number): StatusLevel => { if (temp >= 22 && temp <= 28) return "optimal"; if ((temp >= 18 && temp < 22) || (temp > 28 && temp <= 30)) return "acceptable"; if ((temp >= 15 && temp < 18) || (temp > 30 && temp <= 32)) return "warning"; return "critical";};const getPhStatus = (ph: number): StatusLevel => { if (ph >= 7.0 && ph <= 8.0) return "optimal"; if ((ph >= 6.5 && ph < 7.0) || (ph > 8.0 && ph <= 8.5)) return "acceptable"; if ((ph >= 6.0 && ph < 6.5) || (ph > 8.5 && ph <= 9.0)) return "warning"; return "critical";};const getTurbidityStatus = (ntu: number): StatusLevel => { if (ntu <= 25) return "optimal"; if (ntu <= 50) return "acceptable"; if (ntu <= 150) return "warning"; return "critical";};
function SensorBadge({ status }: { status: StatusLevel }) { return ( <Badge className={`text-[10px] font-bold px-2 py-0.5 w-fit ${ status === "optimal" ? "bg-[#10B981] text-white" : status === "acceptable" ? "bg-[#3B82F6] text-white" : status === "warning" ? "bg-[#F59E0B] text-white" : "bg-red-600 text-white" }`} > {status.toUpperCase()} </Badge> );}
export default function Dashboard({ user, selectedFarm }: DashboardProps) { const [currentFarm, setCurrentFarm] = useState<Farm>( selectedFarm || mockFarms[0], );
// Update currentFarm if selectedFarm changes from props useEffect(() => { if (selectedFarm) { setCurrentFarm(selectedFarm); } }, [selectedFarm]);
// ── API state ── const [dashData, setDashData] = useState<DashboardData | null>(null); const [tanks, setTanks] = useState<any[]>([]); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null); const [lastRefreshed, setLastRefreshed] = useState<Date>(new Date());
// ── Sensor stream state ── // ── Sensor stream state ── const [liveReadings, setLiveReadings] = useState< Record< string, { reading: SensorReadingEvent; tank: any; connected: boolean } > >({}); const disconnectTimersRef = useRef< Record<string, ReturnType<typeof setTimeout>> >({});
// ── Fetch dashboard data ── const fetchDashboard = async (isManual = false) => { if (isManual) setLoading(true); setError(null); try { const [dashRes, tanksRes] = await Promise.all([ apiGet<{ success: boolean; data: DashboardData }>("/dashboard"), apiGet<{ success: boolean; data: any[] } | any[]>("/tanks"), ]); setDashData(dashRes.data); const tanksData = Array.isArray(tanksRes) ? tanksRes : tanksRes.data; setTanks(tanksData); setLastRefreshed(new Date()); } catch (err) { setError((err as Error).message); } finally { setLoading(false); } };
useEffect(() => { let cancelled = false;
const loadData = async () => { setLoading(true); setError(null); try { const [dashRes, tanksRes] = await Promise.all([ apiGet<{ success: boolean; data: DashboardData }>("/dashboard"), apiGet<{ success: boolean; data: any[] } | any[]>("/tanks"), ]); if (!cancelled) { setDashData(dashRes.data); const tanksData = Array.isArray(tanksRes) ? tanksRes : tanksRes.data; setTanks(tanksData); setLastRefreshed(new Date()); } } catch (err) { if (!cancelled) setError((err as Error).message); } finally { if (!cancelled) setLoading(false); } };
loadData(); return () => { cancelled = true; }; }, [currentFarm.id]);
// ── Sensor stream subscription ── useEffect(() => { if (tanks.length === 0) return;
const cleanups: (() => void)[] = [];
tanks.forEach((tank) => { const tankId = String(tank?.id || ""); if (!tankId) return;
console.log( "[Dashboard Stream] subscribing to tankId:", tankId, tank.name, );
const resetDisconnectTimer = () => { if (disconnectTimersRef.current[tankId]) clearTimeout(disconnectTimersRef.current[tankId]); disconnectTimersRef.current[tankId] = setTimeout(() => { setLiveReadings((prev) => prev[tankId] ? { ...prev, [tankId]: { ...prev[tankId], connected: false } } : prev, ); }, 5_000); };
const unsubscribe = subscribeToTankSensorStream({ tankId, onSensorReading: (reading) => { console.log( "[Dashboard Stream] got reading from:", tank.name, reading, ); setLiveReadings((prev) => ({ ...prev, [tankId]: { reading, tank, connected: true }, })); resetDisconnectTimer(); }, onConnectionStatusChange: (isConnected) => { setLiveReadings((prev) => prev[tankId] ? { ...prev, [tankId]: { ...prev[tankId], connected: isConnected }, } : prev, ); if (isConnected) resetDisconnectTimer(); }, onError: () => { setLiveReadings((prev) => prev[tankId] ? { ...prev, [tankId]: { ...prev[tankId], connected: false } } : prev, ); }, });
cleanups.push(unsubscribe); });
return () => { cleanups.forEach((fn) => fn()); Object.values(disconnectTimersRef.current).forEach(clearTimeout); }; }, [tanks.length]);
// ── Resolve safe display values from the real API shape ── const rawFish = dashData?.fishSummary?.totalActiveFish ?? 0; const totalFish = typeof rawFish === "string" ? parseInt(rawFish.replace(/,/g, ""), 10) : rawFish; const totalBiomass = dashData?.fishSummary?.totalBiomassKg ?? 0; const biomassCapacityPct = dashData?.fishSummary?.biomassCapacityPercentage ?? 0; const feedStock = dashData?.feedStock?.totalStockKg ?? 0; const feedDaysRemaining = dashData?.feedStock?.estimatedDaysRemaining ?? 0; const predictedRevenue = dashData?.predictedRevenue?.totalProjectedRevenue ?? 0; const nextHarvestDateFormatted = dashData?.predictedRevenue?.nextHarvestDateFormatted ?? "TBD";
const upcomingHarvests = dashData?.upcomingHarvests ?? []; const waterAlerts = dashData?.waterQualityAlerts ?? []; const nextHarvestStatus = upcomingHarvests[0]?.batches?.[0]?.status;
const getStatusColor = (status: string) => { switch (status) { case "critical": return "bg-[#EF4444] text-white"; case "warning": return "bg-[#F59E0B] text-white"; case "optimal": return "bg-[#10B981] text-white"; default: return "bg-gray-500 text-white"; } };
const getStatusIcon = (status: string) => { switch (status.toLowerCase()) { case "critical": return "🔴"; case "warning": return "🟡"; case "optimal": return "🟢"; default: return "⚪"; } };
// ── Skeleton card used while loading ── const SkeletonCard = () => ( <Card className="bg-white shadow-sm animate-pulse"> <CardContent className="p-6"> <div className="h-4 bg-gray-200 rounded w-1/2 mb-3" /> <div className="h-8 bg-gray-200 rounded w-3/4 mb-2" /> <div className="h-3 bg-gray-200 rounded w-1/3" /> </CardContent> </Card> );
return ( <div className="min-h-screen bg-[#F9FAFB]"> {/* ── Top Navigation Bar ── */} <div className="bg-[#0A4D68] text-white px-6 py-4"> <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> <Fish className="w-6 h-6" /> <span className="text-xl font-semibold">Fish Farm 360</span> </div>
<div className="flex items-center gap-4"> <div className="bg-white/10 px-4 py-2 rounded-lg border border-white/20"> <span className="text-sm font-medium">{currentFarm.name}</span> </div>
<div className="flex items-center gap-2"> <div className="text-right"> <p className="text-sm font-medium">{user.name}</p> <p className="text-xs text-gray-300 capitalize">{user.role}</p> </div> <div className="w-10 h-10 rounded-full bg-[#088395] flex items-center justify-center font-semibold"> {user.name .split(" ") .map((n) => n[0]) .join("") .toUpperCase()} </div> </div> </div> </div> </div>
<div className="p-6 space-y-6"> {/* ── Page Title + Refresh ── */} <div className="flex items-center justify-between"> <div> <h1 className="text-3xl font-semibold text-gray-900">Dashboard</h1> <p className="text-gray-600 mt-1">Welcome back, {user.name}</p> </div> <div className="flex items-center gap-3"> <span className="text-xs text-black-500"> Last updated: {lastRefreshed.toLocaleTimeString()} </span> <Button variant="outline" size="sm" onClick={() => fetchDashboard(true)} disabled={loading} > <RefreshCw className={`w-4 h-4 mr-1 ${loading ? "animate-spin" : ""}`} /> Refresh </Button> </div> </div>
{/* ── Error banner ── */} {error && ( <div className="bg-red-50 border border-red-200 rounded-lg p-4 flex items-center gap-3"> <AlertCircle className="w-5 h-5 text-red-500 flex-shrink-0" /> <div> <p className="text-sm font-medium text-red-800"> Failed to load dashboard data </p> <p className="text-xs text-red-600 mt-0.5">{error}</p> </div> </div> )}
{/* ── KPI Cards ── */} {loading ? ( <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4"> {[1, 2, 3, 4].map((i) => ( <SkeletonCard key={i} /> ))} </div> ) : ( <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4"> {/* Total Active Fish */} <Card className="bg-white shadow-sm"> <CardContent className="p-6"> <div className="flex items-start justify-between"> <div> <p className="text-sm text-gray-600 mb-1"> Total Active Fish </p> <p className="text-3xl font-bold text-gray-900"> {totalFish.toLocaleString()} </p> <p className="text-sm text-gray-500 mt-1"> Across {dashData?.fishSummary?.activeTanks ?? 0} tanks </p> </div> <div className="w-12 h-12 rounded-lg bg-[#E0F4F5] flex items-center justify-center"> <Fish className="w-6 h-6 text-[#088395]" /> </div> </div> </CardContent> </Card>
{/* Total Biomass */} <Card className="bg-white shadow-sm"> <CardContent className="p-6"> <div className="flex items-start justify-between"> <div className="flex-1"> <p className="text-sm text-gray-600 mb-1">Total Biomass</p> <p className="text-3xl font-bold text-gray-900"> {totalBiomass.toLocaleString()} kg </p> </div> <div className="w-12 h-12 rounded-lg bg-[#E0F4F5] flex items-center justify-center"> <Scale className="w-6 h-6 text-[#088395]" /> </div> </div> </CardContent> </Card>
{/* Feed Stock */} <Card className="bg-white shadow-sm"> <CardContent className="p-6"> <div className="flex items-start justify-between"> <div> <p className="text-sm text-gray-600 mb-1">Feed Stock</p> <p className="text-3xl font-bold text-gray-900"> {feedStock.toLocaleString()} kg </p> <p className="text-sm text-gray-500 mt-1"> Current inventory </p> </div> <div className="w-12 h-12 rounded-lg bg-[#FEF3C7] flex items-center justify-center"> <Wheat className="w-6 h-6 text-[#F59E0B]" /> </div> </div> </CardContent> </Card>
{/* Total Tanks */} <Card className="bg-white shadow-sm"> <CardContent className="p-6"> <div className="flex items-start justify-between"> <div> <p className="text-sm text-gray-600 mb-1">Total Tanks</p> <p className="text-3xl font-bold text-gray-900"> {dashData?.fishSummary?.totalTanks ?? tanks.length} </p> <p className="text-sm text-gray-500 mt-1"> {dashData?.fishSummary?.activeTanks ?? 0} active tanks </p> </div> <div className="w-12 h-12 rounded-lg bg-gray-100 flex items-center justify-center"> <TrendingUp className="w-6 h-6 text-gray-600" /> </div> </div> </CardContent> </Card> </div> )}
{/* ── Second Row – Sensor Measurements + Upcoming Harvests ── */} <div className="grid grid-cols-1 lg:grid-cols-2 gap-4"> {/* Sensor Measurements Cards */} {Object.keys(liveReadings).length === 0 ? ( <Card className="bg-white border border-gray-100 shadow-sm overflow-hidden"> <CardContent className="p-4"> <div className="flex items-center gap-2 mb-3"> <div className="w-7 h-7 rounded-lg bg-emerald-50 flex items-center justify-center"> <Cpu className="w-4 h-4 text-emerald-600" /> </div> <div> <h4 className="text-sm font-semibold text-gray-900"> Sensor Measurements </h4> <p className="text-[10px] text-gray-400 uppercase tracking-wide"> No active streams </p> </div> </div> {loading ? ( <div className="grid grid-cols-3 gap-2 animate-pulse"> {[1, 2, 3].map((i) => ( <div key={i} className="h-20 bg-gray-100 rounded-xl" /> ))} </div> ) : ( <div className="text-center py-6 bg-gray-50 rounded-xl border border-dashed border-gray-200"> <Cpu className="w-6 h-6 text-gray-300 mx-auto mb-2" /> <p className="text-sm text-gray-400 font-medium"> Waiting for sensor data… </p> <p className="text-xs text-gray-300 mt-0.5"> Stream will connect automatically </p> </div> )} </CardContent> </Card> ) : ( <div className="space-y-3"> {Object.values(liveReadings) .sort((a, b) => Number(b.connected) - Number(a.connected)) .map(({ reading, tank, connected }) => ( <Card key={tank.id} className="bg-white border border-gray-100 shadow-sm overflow-hidden" > <CardContent className="p-4"> {/* Header */} <div className="flex items-center justify-between mb-3"> <div className="flex items-center gap-2"> <div className="w-7 h-7 rounded-lg bg-emerald-50 flex items-center justify-center"> <Cpu className="w-4 h-4 text-emerald-600" /> </div> <div> <h4 className="text-sm font-semibold text-gray-900"> Sensor Measurements </h4> <p className="text-[10px] text-gray-400 uppercase tracking-wide"> Active link: {tank?.name || "Tank"} </p> </div> </div> {connected ? ( <div className="flex items-center gap-1.5 px-2 py-1 bg-emerald-50 rounded-full border border-emerald-100"> <div className="w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse" /> <span className="text-[10px] font-semibold text-emerald-700"> 🟢 Live </span> </div> ) : ( <div className="flex items-center gap-1.5 px-2 py-1 bg-red-50 rounded-full border border-red-200"> <div className="w-1.5 h-1.5 rounded-full bg-red-500" /> <span className="text-[10px] font-semibold text-red-600"> 🔴 Offline </span> </div> )} </div>
{/* Metrics */} <div className="grid grid-cols-3 gap-2"> {/* Temperature */} <div className="bg-gray-50 rounded-xl p-3 flex flex-col gap-1"> <div className="flex items-center gap-1.5"> <Thermometer className="w-3.5 h-3.5 text-orange-400" /> <span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider"> Temp </span> </div> <div className="flex items-baseline gap-1"> <span className="text-xl font-black text-gray-900"> {reading.temperature.toFixed(1)} </span> <span className="text-xs font-semibold text-orange-400"> °C </span> </div> {connected && ( <SensorBadge status={getTemperatureStatus(reading.temperature)} /> )} </div>
{/* pH */} <div className="bg-gray-50 rounded-xl p-3 flex flex-col gap-1"> <div className="flex items-center gap-1.5"> <Activity className="w-3.5 h-3.5 text-green-500" /> <span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider"> pH Level </span> </div> <div className="flex items-baseline gap-1"> <span className="text-xl font-black text-gray-900"> {reading.ph.toFixed(2)} </span> <span className="text-xs font-semibold text-green-500"> — </span> </div> {connected && ( <SensorBadge status={getPhStatus(reading.ph)} /> )} </div>
{/* Turbidity */} <div className="bg-gray-50 rounded-xl p-3 flex flex-col gap-1"> <div className="flex items-center gap-1.5"> <Zap className="w-3.5 h-3.5 text-blue-400" /> <span className="text-[10px] font-semibold text-gray-400 uppercase tracking-wider"> Turbidity </span> </div> <div className="flex items-baseline gap-1"> <span className="text-xl font-black text-gray-900"> {reading.turbidity_ntu.toFixed(2)} </span> <span className="text-xs font-semibold text-blue-400 font-mono"> ntu </span> </div> {connected && ( <SensorBadge status={getTurbidityStatus(reading.turbidity_ntu)} /> )} </div> </div>
{/* Footer */} <div className="flex items-center justify-between mt-3 pt-3 border-t border-gray-100"> {connected ? ( <div className="flex items-center gap-1.5 text-[10px] text-emerald-600 font-semibold"> <Wifi className="w-3 h-3 text-emerald-500" /> Stream sync active </div> ) : ( <div className="flex items-center gap-1.5 text-[10px] text-red-500 font-semibold"> <WifiOff className="w-3 h-3 text-red-500" /> Stream sync inactive </div> )} <span className={`text-[10px] font-semibold ${connected ? "text-black-400" : "text-red-400"}`} > Last updated{" "} {new Date(reading.timestamp).toLocaleTimeString()} </span> </div> </CardContent> </Card> ))} </div> )}
{/* Upcoming Harvests */} <Card className="bg-white shadow-sm"> <CardHeader> <CardTitle className="text-lg">Upcoming Harvests</CardTitle> </CardHeader> <CardContent> {loading ? ( <div className="space-y-3 animate-pulse"> {[1, 2, 3].map((i) => ( <div key={i} className="h-16 bg-gray-100 rounded-lg" /> ))} </div> ) : upcomingHarvests.length === 0 ? ( <p className="text-sm text-gray-500 py-4 text-center"> No harvest dates scheduled yet </p> ) : ( <div className="space-y-3"> {upcomingHarvests.map((harvest, idx) => ( <div key={idx} className="p-3 rounded-lg bg-gray-50 border border-gray-200" > <div className="flex items-center justify-between mb-1"> <div> <p className="font-medium text-sm"> {harvest.tankName} </p> {harvest.estimatedWeight && ( <p className="text-xs text-gray-600"> {harvest.estimatedWeight.toLocaleString()} kg est. </p> )} </div> {harvest.batches?.[0] && ( <Badge className={`${ harvest.batches[0].status === "READY" ? "bg-green-600" : "bg-[#088395]" } text-white text-xs flex items-center gap-1`} > {harvest.batches[0].status === "READY" ? ( <CheckCircle2 className="w-3 h-3" /> ) : ( <Clock className="w-3 h-3" /> )} {harvest.batches[0].status} </Badge> )} </div> {harvest.batches?.map((b, bi) => ( <p key={bi} className="text-xs text-gray-500"> {b.fishType} </p> ))} </div> ))} </div> )} </CardContent> </Card> </div> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366import { useState, useEffect } from "react";import { User, Farm } from "../types";import { apiGet, apiPost, apiDelete, apiPut, apiPatch } from "../api";import { Card, CardHeader, CardTitle } from "./ui/card";import { Icon, Trash, Pencil } from "lucide-react";import { barn } from "@lucide/lab";
interface Props { user: User; selectedFarm: Farm | null;}
export default function Farms({ user }: Props) { const [showModal, setShowModal] = useState(false); const [name, setName] = useState(""); const [location, setLocation] = useState(""); const [submitting, setSubmitting] = useState(false); const [farms, setFarms] = useState<Farm[]>([]); const [loading, setLoading] = useState<boolean>(true); const [deleteFarmId, setDeleteFarmId] = useState<string | null>(null); const [editFarmId, setEditFarmId] = useState<string | null>(null); const [editName, setEditName] = useState(""); const [editLocation, setEditLocation] = useState(""); const fetchFarms = async () => { try { const json = await apiGet<{ success: boolean; data: Farm[]; }>("/farms");
if (json.success) { setFarms(json.data); } } catch (error) { console.error("Failed to fetch farms:", error); } finally { setLoading(false); } };
useEffect(() => { fetchFarms(); }, []); const handleAddFarm = async () => { if (!name.trim() || !location.trim()) { alert("All fields are required"); return; }
try { setSubmitting(true);
const json = await apiPost<{ success: boolean; data: Farm; }>("/farms", { name, location, });
if (json) { await fetchFarms();
setName(""); setLocation(""); setShowModal(false); } else { alert("Failed to add farm"); } } catch (error) { console.error(error); alert("Something went wrong"); } finally { setSubmitting(false); } };
/* const openEditFarm = (farm: Farm) => { setEditFarmId(farm.id); setEditName(farm.name); setEditLocation(farm.location || ""); };
const handleEditFarm = async () => { if (!editName.trim() || !editLocation.trim()) { alert("All fields are required"); return; }
try { setSubmitting(true);
const json = await apiPut<{ success: boolean; data: Farm; }>(`/farms/${editFarmId}`, { name: editName, location: editLocation, });
console.log("UPDATE RESPONSE:", json); // 👈 IMPORTANT
if (json?.success) { await fetchFarms();
setEditName(""); setEditLocation(""); setEditFarmId(null); } else { alert("Update failed"); } } catch (error) { console.error(error); alert("Something went wrong"); } finally { setSubmitting(false); } };*/ // 👉 OPEN MODAL ONLY (no delete here) const handleDeleteFarm = (farmId: string) => { setDeleteFarmId(farmId); };
// 👉 CONFIRM DELETE const confirmDeleteFarm = async () => { if (!deleteFarmId) return;
try { const res = await apiDelete<{ success: boolean; message?: string; }>(`/farms/${deleteFarmId}`);
if (res?.success) { await fetchFarms(); setDeleteFarmId(null); } else { // 👇 HANDLE ERROR MESSAGE FROM BACKEND if ( res?.message?.includes("foreign key") || res?.message?.includes("referenced") ) { alert( "This farm cannot be deleted because it is linked to existing records.", ); } else { alert(res?.message || "Failed to delete farm"); } } } catch (error) { console.error(error); alert("Something went wrong while deleting the farm"); } }; return ( <div className="p-6 bg-[#F9FAFB] min-h-screen"> {/* Header */} <div className="flex justify-between items-center mb-6"> <div> <h1 className="text-3xl font-semibold text-gray-900">Farms</h1> <p className="text-sm text-gray-500"> Welcome back, {user?.name ?? "User"} </p> </div>
<button onClick={() => setShowModal(true)} className="px-4 py-2 bg-[#088395] text-white rounded-lg text-sm hover:bg-[#0A4D68] transition" > Add Farm </button> </div>
{/* Add Farm Modal */} {showModal && ( <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50"> <div className="bg-white rounded-xl p-6 w-[400px] shadow-lg"> <h2 className="text-lg font-semibold mb-4">Add New Farm</h2>
<div className="mb-4"> <label className="text-sm font-medium">Farm Name *</label> <input value={name} onChange={(e) => setName(e.target.value)} className="w-full mt-1 p-2 border rounded-md" placeholder="Enter farm name" /> </div>
<div className="mb-4"> <label className="text-sm font-medium">Farm Location *</label> <input value={location} onChange={(e) => setLocation(e.target.value)} className="w-full mt-1 p-2 border rounded-md" placeholder="Enter location" /> </div>
<div className="flex justify-end gap-2"> <button onClick={() => setShowModal(false)} className="px-3 py-1 text-sm bg-gray-200 rounded-md" > Cancel </button>
<button onClick={handleAddFarm} disabled={submitting} className="px-4 py-2 bg-[#088395] text-white rounded-md text-sm" > {submitting ? "Adding..." : "Add Farm"} </button> </div> </div> </div> )}
{/* ✅ Edit MODAL */}
{editFarmId && ( <div className="fixed inset-0 bg-black/40 flex items-center justify-center z-50"> <div className="bg-white rounded-xl p-6 w-[400px] shadow-lg"> <h2 className="text-lg font-semibold mb-4">Edit Farm</h2>
{/* Farm Name */} <div className="mb-4"> <label className="text-sm font-medium">Farm Name *</label> <input value={editName} onChange={(e) => setEditName(e.target.value)} className="w-full mt-1 p-2 border rounded-md" placeholder="Enter farm name" /> </div>
{/* Farm Location */} <div className="mb-4"> <label className="text-sm font-medium">Farm Location *</label> <input value={editLocation} onChange={(e) => setEditLocation(e.target.value)} className="w-full mt-1 p-2 border rounded-md" placeholder="Enter location" /> </div>
{/* Actions */} <div className="flex justify-end gap-2"> <button onClick={() => setEditFarmId(null)} className="px-3 py-1 text-sm bg-gray-200 rounded-md hover:bg-gray-300 transition" > Cancel </button>
{/* <button onClick={handleEditFarm} disabled={submitting} className="px-4 py-2 bg-[#088395] text-white rounded-md text-sm hover:bg-[#0A4D68] transition" > {submitting ? "Updating..." : "Update Farm Details"} </button> */} </div> </div> </div> )}
{/* ✅ DELETE MODAL */} {deleteFarmId && ( <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50"> <div className="bg-white rounded-2xl p-8 w-[420px] shadow-xl"> <h2 className="text-xl font-semibold text-gray-900 mb-4"> Are you sure you want to delete this farm? </h2>
<p className="text-gray-500 mb-6"> This will delete this farm permanently. You cannot undo this action. </p>
<div className="flex justify-between gap-4"> <button onClick={() => setDeleteFarmId(null)} className="w-full border border-gray-300 rounded-lg py-2 text-gray-700 hover:bg-gray-100 transition" > Cancel </button>
<button onClick={confirmDeleteFarm} className="w-full bg-red-600 text-white rounded-lg py-2 hover:bg-red-700 transition" > Delete </button> </div> </div> </div> )}
{/* Farms Grid */} <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> {loading ? ( <p className="text-gray-500 italic">Loading farms...</p> ) : ( farms.map((farm) => ( <Card key={farm.id} className="bg-white shadow-sm hover:shadow-md transition relative" > <div className="absolute top-1/2 right-3 -translate-y-1/2 flex gap-3"> {/* Edit */} {/* <button onClick={() => openEditFarm(farm)} className="text-blue-500 hover:text-blue-700 transition" > <Pencil size={20} /> </button> */}
{/* Delete */} <button onClick={() => handleDeleteFarm(farm.id)} className="text-red-500 hover:text-red-700 transition" > <Trash size={20} /> </button> </div> <CardHeader className="pb-3"> <div> <CardTitle className="text-lg font-bold text-[#0A4D68]"> <Icon iconNode={barn} /> Farm Name:{" "} <span style={{ color: "#DB1A1A", fontWeight: "bolder" }}> {farm.name} </span> </CardTitle>
<p className="text-sm text-gray-600 mt-2"> <span style={{ color: "#0A4D68", fontWeight: "bolder" }}> Farm Location:{" "} </span> <span style={{ color: "#DB1A1A", fontWeight: "bolder" }}> {farm.location || "Location not provided"} </span> </p>
<p className="text-[10px] text-gray-400 font-mono" style={{ color: "#04b13d" }} > <span style={{ color: "#000000", fontWeight: "bolder" }}> Farm ID:{" "} </span> {farm.id?.split("-")[0]} </p> </div> </CardHeader> </Card> )) )} </div> </div> );}1export { default } from './FishTypeManagementEnhanced';12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745import { useEffect, useMemo, useState } from "react";import { Badge } from "./ui/badge";import { Button } from "./ui/button";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle,} from "./ui/dialog";import { Input } from "./ui/input";import { Label } from "./ui/label";import { Switch } from "./ui/switch";import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";import { Textarea } from "./ui/textarea";import { AlertCircle, Fish, Loader2, Plus, RefreshCcw, Trash2, Wheat,} from "lucide-react";import { Farm, User } from "../types";import { FishGradePricingRecord, getPricingByFishType,} from "../services/harvestApi";import { ExpectedGradeDistributionEntry, FeedingRateMatrix, FeedingRateResult, FishTypeRecord, FishTypeUpsertPayload, FoodTypeOption, ProteinRequirementResult, ProteinRequirementRule, createFishType, getFeedingRate, getFishTypeById, getFishTypes, getFoodTypes, getProteinRequirement, updateFishType,} from "../services/fishTypesApi";import Pagination from "@mui/material/Pagination";interface FishTypeManagementProps { user: User; selectedFarm: Farm | null;}
type FormTab = "basic" | "water" | "feeding" | "protein" | "food";
interface FishTypeFormState { name: string; scientificName: string; arabicName: string; description: string; tempMin: number; tempMax: number; doMin: number; doMax: number; phMin: number; phMax: number; nh3Min: number; nh3Max: number; no2Min: number; no2Max: number; turbidityMin: number; turbidityMax: number; fcrMin: number; fcrMax: number; survivalRate: number; targetSGR: number; targetWeightForHarvest: number; defaultMarketPrice: number; criticalParameters: string[]; feedingRateMatrix: FeedingRateMatrix; proteinRequirements: ProteinRequirementRule[]; expectedGradeDistribution: ExpectedGradeDistributionEntry[]; notes: string; allowedFoodTypeIds: string[]; isActive: boolean;}
const CRITICAL_PARAMETER_OPTIONS = [ "Temperature", "Dissolved Oxygen", "pH", "Ammonia", "Nitrite", "Turbidity",];
const createDefaultFeedingRateMatrix = (): FeedingRateMatrix => ({ weight_ranges: [ { min: 10, max: 15 }, { min: 15, max: 20 }, { min: 20, max: 30 }, ], temperatures: [18, 23, 26, 30], rates: [ [2.0, 3.0, 4.25, 4.5], [2.0, 2.75, 4.0, 4.25], [1.8, 2.5, 3.75, 4.0], ],});
// Meal defaults removed
const createDefaultProteinRequirements = (): ProteinRequirementRule[] => [ { minWeight: 0, maxWeight: 10, proteinPercentage: 35 }, { minWeight: 10, maxWeight: 50, proteinPercentage: 32 }, { minWeight: 50, maxWeight: 200, proteinPercentage: 30 }, { minWeight: 200, maxWeight: null, proteinPercentage: 28 },];
const cloneFeedingRateMatrix = ( matrix: FeedingRateMatrix,): FeedingRateMatrix => ({ weight_ranges: matrix.weight_ranges.map((range) => ({ min: range.min, max: range.max, })), temperatures: [...matrix.temperatures], rates: matrix.rates.map((row) => [...row]),});
const normalizeFeedingRateMatrix = ( matrix: FeedingRateMatrix,): FeedingRateMatrix => { const temperatures = matrix.temperatures.length > 0 ? [...matrix.temperatures] : [20, 24, 28]; const weightRanges = matrix.weight_ranges.length > 0 ? matrix.weight_ranges.map((range) => ({ min: range.min ?? 0, max: range.max ?? 0, })) : [{ min: 0, max: 10 }];
const rates = weightRanges.map((_, rowIndex) => temperatures.map((_, colIndex) => { const value = matrix.rates[rowIndex]?.[colIndex]; return Number.isFinite(value) ? value : 0; }), );
return { weight_ranges: weightRanges, temperatures, rates, };};
const getDefaultFormState = (): FishTypeFormState => ({ name: "", scientificName: "", arabicName: "", description: "", tempMin: 20, tempMax: 32, doMin: 3, doMax: 8, phMin: 6.5, phMax: 8.5, nh3Min: 0, nh3Max: 0.05, no2Min: 0, no2Max: 0.2, turbidityMin: 0, turbidityMax: 10, fcrMin: 1.2, fcrMax: 1.8, survivalRate: 85, targetSGR: 2, targetWeightForHarvest: 0, defaultMarketPrice: 0, criticalParameters: ["DO", "NH3", "Temperature"], feedingRateMatrix: createDefaultFeedingRateMatrix(), proteinRequirements: createDefaultProteinRequirements(), expectedGradeDistribution: [], notes: "", allowedFoodTypeIds: [], isActive: true,});
const toFormState = (fishType: FishTypeRecord): FishTypeFormState => ({ name: fishType.name, scientificName: fishType.scientificName, arabicName: fishType.arabicName || "", description: fishType.description || "", tempMin: fishType.tempMin, tempMax: fishType.tempMax, doMin: fishType.doMin, doMax: fishType.doSafe || 0, phMin: fishType.phMin, phMax: fishType.phMax, nh3Min: fishType.nh3Safe || 0, nh3Max: fishType.nh3Critical || 0, no2Min: 0, no2Max: fishType.no2Max, turbidityMin: fishType.turbidityMin || 0, turbidityMax: fishType.turbidityMax || 0, fcrMin: fishType.fcrMin, fcrMax: fishType.fcrMax, survivalRate: fishType.survivalRate, targetSGR: fishType.targetSGR ?? 0, targetWeightForHarvest: fishType.targetWeightForHarvest ?? 0, defaultMarketPrice: fishType.defaultMarketPrice ?? 0, criticalParameters: fishType.criticalParameters, feedingRateMatrix: normalizeFeedingRateMatrix(fishType.feedingRateMatrix), proteinRequirements: fishType.proteinRequirements.length > 0 ? fishType.proteinRequirements.map((rule) => ({ minWeight: rule.minWeight, maxWeight: rule.maxWeight, proteinPercentage: rule.proteinPercentage, })) : createDefaultProteinRequirements(), expectedGradeDistribution: fishType.expectedGradeDistribution || [], notes: fishType.notes || "", allowedFoodTypeIds: fishType.allowedFoodTypeIds, isActive: fishType.isActive,});
const toNumber = (value: string): number => { const parsed = Number(value); return Number.isFinite(parsed) ? parsed : 0;};
const toNullableNumber = (value: string): number | null => { const normalized = value.trim(); if (!normalized) { return null; }
const parsed = Number(normalized); if (!Number.isFinite(parsed)) { return null; }
return parsed;};
const calculateDistributionTotal = ( entries: ExpectedGradeDistributionEntry[],): number => entries.reduce( (sum, entry) => sum + (Number.isFinite(entry.percentage) ? entry.percentage : 0), 0, );
const validateForm = (form: FishTypeFormState): string | null => { if (!form.name.trim() || !form.scientificName.trim()) { return "Name and scientific name are required."; }
if ( form.feedingRateMatrix.weight_ranges.length === 0 || form.feedingRateMatrix.temperatures.length === 0 ) { return "Feeding matrix must include at least one weight range and one temperature."; }
const invalidRange = form.feedingRateMatrix.weight_ranges.find( (range) => range.min === null || range.max === null || range.max <= range.min, ); if (invalidRange) { return "Each feeding weight range must have a maximum greater than minimum."; }
const invalidRateShape = form.feedingRateMatrix.rates.some( (row) => row.length !== form.feedingRateMatrix.temperatures.length, ); if ( invalidRateShape || form.feedingRateMatrix.rates.length !== form.feedingRateMatrix.weight_ranges.length ) { return "Feeding matrix rates must align with all weight ranges and temperatures."; }
// Meal validation removed
const invalidProtein = form.proteinRequirements.some( (rule) => !Number.isFinite(rule.proteinPercentage) || rule.proteinPercentage <= 0, ); if (invalidProtein) { return "Each protein requirement rule must have protein percentage greater than 0."; }
if (form.expectedGradeDistribution.length > 0) { const invalidDistributionRow = form.expectedGradeDistribution.some( (row) => !row.gradePricingId.trim() || !Number.isFinite(row.percentage) || row.percentage <= 0, ); if (invalidDistributionRow) { return "Each expected grade distribution row needs grade pricing id and percentage > 0."; }
const total = calculateDistributionTotal(form.expectedGradeDistribution); if (Math.abs(total - 100) > 0.01) { return "Expected grade distribution percentages must sum to 100."; } }
return null;};
const toUpsertPayload = (form: FishTypeFormState): FishTypeUpsertPayload => ({ name: form.name.trim(), scientificName: form.scientificName.trim(), arabicName: form.arabicName.trim() || undefined, description: form.description.trim() || undefined, tempMin: form.tempMin, tempOptimal: (form.tempMin + form.tempMax) / 2, tempMax: form.tempMax, doMin: form.doMin, doSafe: form.doMax, phMin: form.phMin, phMax: form.phMax, nh3Safe: form.nh3Min, nh3Critical: form.nh3Max, no2Max: form.no2Max, turbidityMin: form.turbidityMin, turbidityMax: form.turbidityMax, fcrMin: form.fcrMin, fcrMax: form.fcrMax, survivalRate: form.survivalRate, targetSGR: form.targetSGR, targetWeightForHarvest: form.targetWeightForHarvest, defaultMarketPrice: form.defaultMarketPrice, feedingRateMatrix: cloneFeedingRateMatrix(form.feedingRateMatrix), proteinRequirements: form.proteinRequirements.map((rule) => ({ minWeight: rule.minWeight, maxWeight: rule.maxWeight, proteinPercentage: rule.proteinPercentage, })), criticalParameters: form.criticalParameters, expectedGradeDistribution: form.expectedGradeDistribution.length > 0 ? form.expectedGradeDistribution.map((row) => ({ gradePricingId: row.gradePricingId.trim(), percentage: row.percentage, })) : undefined, notes: form.notes.trim() || undefined, allowedFoodTypeIds: form.allowedFoodTypeIds.length > 0 ? form.allowedFoodTypeIds : undefined, isActive: form.isActive,});
export default function FishTypeManagementEnhanced({ user, selectedFarm,}: FishTypeManagementProps) { const [fishTypes, setFishTypes] = useState<FishTypeRecord[]>([]); const [foodTypes, setFoodTypes] = useState<FoodTypeOption[]>([]); const [isLoading, setIsLoading] = useState(true); const [isRefreshing, setIsRefreshing] = useState(false); const [isLoadingFoodTypes, setIsLoadingFoodTypes] = useState(false); const [isLoadingGradePricing, setIsLoadingGradePricing] = useState(false); const [errorMessage, setErrorMessage] = useState<string | null>(null); const [gradePricingError, setGradePricingError] = useState<string | null>( null, ); const [foodTypePage, setFoodTypePage] = useState(0); const [isModalOpen, setIsModalOpen] = useState(false); const [activeFormTab, setActiveFormTab] = useState<FormTab>("basic"); const [editingFishTypeId, setEditingFishTypeId] = useState<string | null>( null, ); const [isSaving, setIsSaving] = useState(false); const [formError, setFormError] = useState<string | null>(null); const [formState, setFormState] = useState<FishTypeFormState>( getDefaultFormState(), ); const [gradePricingOptions, setGradePricingOptions] = useState< FishGradePricingRecord[] >([]);
const [calculatorFishTypeId, setCalculatorFishTypeId] = useState(""); const [calculatorWeight, setCalculatorWeight] = useState(45); const [calculatorTemperature, setCalculatorTemperature] = useState(27); const [isRunningCalculator, setIsRunningCalculator] = useState(false); const [calculatorError, setCalculatorError] = useState<string | null>(null); const [feedingRateResult, setFeedingRateResult] = useState<FeedingRateResult | null>(null); // Meal frequency state removed const [proteinRequirementResult, setProteinRequirementResult] = useState<ProteinRequirementResult | null>(null);
const currentFarmLabel = selectedFarm?.name || "Current Farm";
const distributionTotal = useMemo( () => calculateDistributionTotal(formState.expectedGradeDistribution), [formState.expectedGradeDistribution], );
const loadFishTypes = async (silent = false) => { if (silent) { setIsRefreshing(true); } else { setIsLoading(true); } setErrorMessage(null);
try { const list = await getFishTypes(false); setFishTypes(list); if (!calculatorFishTypeId && list.length > 0) { setCalculatorFishTypeId(list[0].id); } } catch (error) { setErrorMessage( error instanceof Error ? error.message : "Failed to load fish types.", ); setFishTypes([]); } finally { setIsLoading(false); setIsRefreshing(false); } };
const loadFoodTypes = async () => { setIsLoadingFoodTypes(true); try { const list = await getFoodTypes(); setFoodTypes(list); } catch (error) { setErrorMessage( error instanceof Error ? error.message : "Failed to load food types.", ); setFoodTypes([]); } finally { setIsLoadingFoodTypes(false); } };
useEffect(() => { void Promise.all([loadFishTypes(), loadFoodTypes()]); }, []);
const openCreateModal = () => { setEditingFishTypeId(null); setFormError(null); setActiveFormTab("basic"); setFormState(getDefaultFormState()); setGradePricingOptions([]); setGradePricingError(null); setFoodTypePage(0); setIsModalOpen(true); };
const openEditModal = async (fishTypeId: string) => { setEditingFishTypeId(fishTypeId); setFormError(null); setGradePricingError(null); setGradePricingOptions([]); setActiveFormTab("basic"); setIsModalOpen(true); setFoodTypePage(0); setIsSaving(true); setIsLoadingGradePricing(true); try { const [detail, pricing] = await Promise.all([ getFishTypeById(fishTypeId), getPricingByFishType(fishTypeId).catch((error) => { setGradePricingError( error instanceof Error ? error.message : "Failed to load grade pricing.", ); return []; }), ]); setFormState(toFormState(detail)); setGradePricingOptions(pricing.filter((entry) => entry.isActive)); } catch (error) { setFormError( error instanceof Error ? error.message : "Failed to load fish type details.", ); } finally { setIsSaving(false); setIsLoadingGradePricing(false); } };
const toggleAllowedFoodType = (foodTypeId: string, checked: boolean) => { setFormState((previous) => { const nextSet = new Set(previous.allowedFoodTypeIds); if (checked) { nextSet.add(foodTypeId); } else { nextSet.delete(foodTypeId); } return { ...previous, allowedFoodTypeIds: Array.from(nextSet) }; }); };
const toggleCriticalParameter = (parameter: string) => { setFormState((previous) => { const hasParameter = previous.criticalParameters.includes(parameter); return { ...previous, criticalParameters: hasParameter ? previous.criticalParameters.filter((item) => item !== parameter) : [...previous.criticalParameters, parameter], }; }); };
const updateFeedingMatrix = ( updater: (matrix: FeedingRateMatrix) => void, ) => { setFormState((previous) => { const nextMatrix = cloneFeedingRateMatrix(previous.feedingRateMatrix); updater(nextMatrix); return { ...previous, feedingRateMatrix: nextMatrix }; }); };
const addFeedingTemperature = () => { updateFeedingMatrix((matrix) => { const nextTemperature = matrix.temperatures.length > 0 ? matrix.temperatures[matrix.temperatures.length - 1] + 2 : 24; matrix.temperatures.push(nextTemperature); matrix.rates = matrix.rates.map((row) => [...row, 0]); }); };
const removeFeedingTemperature = (index: number) => { updateFeedingMatrix((matrix) => { if (matrix.temperatures.length <= 1) { return; } matrix.temperatures = matrix.temperatures.filter( (_, tempIndex) => tempIndex !== index, ); matrix.rates = matrix.rates.map((row) => row.filter((_, tempIndex) => tempIndex !== index), ); }); };
const addWeightRange = () => { updateFeedingMatrix((matrix) => { matrix.weight_ranges.push({ min: 0, max: 0 }); matrix.rates.push(new Array(matrix.temperatures.length).fill(0)); }); };
const removeWeightRange = (index: number) => { updateFeedingMatrix((matrix) => { if (matrix.weight_ranges.length <= 1) { return; } matrix.weight_ranges = matrix.weight_ranges.filter( (_, rangeIndex) => rangeIndex !== index, ); matrix.rates = matrix.rates.filter((_, rowIndex) => rowIndex !== index); }); };
// Meal frequency handlers removed
const updateProteinRequirement = ( index: number, field: keyof ProteinRequirementRule, value: number | null, ) => { setFormState((previous) => ({ ...previous, proteinRequirements: previous.proteinRequirements.map( (rule, ruleIndex) => ruleIndex === index ? { ...rule, [field]: value } : rule, ), })); };
const addProteinRequirement = () => { setFormState((previous) => ({ ...previous, proteinRequirements: [ ...previous.proteinRequirements, { minWeight: 0, maxWeight: null, proteinPercentage: 30 }, ], })); };
const removeProteinRequirement = (index: number) => { setFormState((previous) => ({ ...previous, proteinRequirements: previous.proteinRequirements.length === 1 ? previous.proteinRequirements : previous.proteinRequirements.filter( (_, ruleIndex) => ruleIndex !== index, ), })); };
const addExpectedDistributionRow = () => { setFormState((previous) => ({ ...previous, expectedGradeDistribution: [ ...previous.expectedGradeDistribution, { gradePricingId: "", percentage: 0 }, ], })); };
const removeExpectedDistributionRow = (index: number) => { setFormState((previous) => ({ ...previous, expectedGradeDistribution: previous.expectedGradeDistribution.filter( (_, rowIndex) => rowIndex !== index, ), })); };
const updateExpectedDistributionRow = ( index: number, field: keyof ExpectedGradeDistributionEntry, value: string | number, ) => { setFormState((previous) => ({ ...previous, expectedGradeDistribution: previous.expectedGradeDistribution.map( (row, rowIndex) => rowIndex === index ? { ...row, [field]: value } : row, ), })); };
const saveFishType = async () => { setFormError(null);
const validationError = validateForm(formState); if (validationError) { setFormError(validationError); return; }
const payload = toUpsertPayload(formState);
setIsSaving(true); try { if (editingFishTypeId) { await updateFishType(editingFishTypeId, payload); } else { await createFishType(payload); } setIsModalOpen(false); await loadFishTypes(true); } catch (error) { setFormError( error instanceof Error ? error.message : "Failed to save fish type.", ); } finally { setIsSaving(false); } };
const runCalculators = async () => { if (!calculatorFishTypeId) { setCalculatorError("Select a fish type first."); return; }
setCalculatorError(null); setIsRunningCalculator(true); try { const [feedingRate, proteinRequirement] = await Promise.all([ getFeedingRate( calculatorFishTypeId, calculatorWeight, calculatorTemperature, ), getProteinRequirement(calculatorFishTypeId, calculatorWeight), ]);
setFeedingRateResult(feedingRate); setProteinRequirementResult(proteinRequirement); } catch (error) { setCalculatorError( error instanceof Error ? error.message : "Failed to run calculators.", ); } finally { setIsRunningCalculator(false); } }; const isTechnician = user.role.toLowerCase() === "technician"; return ( <div className="w-full min-h-screen bg-[#F9FAFB] flex flex-col"> <div className="bg-[#0A4D68] text-white px-6 py-4"> <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> <Fish className="w-6 h-6" /> <span className="text-xl font-semibold">Fish Type Management</span> </div> <div className="flex items-center gap-4"> <span className="text-sm">{currentFarmLabel}</span> <div className="w-10 h-10 rounded-full bg-[#088395] flex items-center justify-center font-semibold"> {user.name .split(" ") .map((part) => part[0]) .join("") .toUpperCase()} </div> </div> </div> </div>
<div className="flex-1 p-6 space-y-6 overflow-auto"> {errorMessage && ( <Card className="border-red-200 bg-red-50"> <CardContent className="py-3 text-sm text-red-700"> {errorMessage} </CardContent> </Card> )}
<div className="flex items-center justify-between"> <div> <h2 className="text-2xl font-semibold">Fish Species Database</h2> <p className="text-gray-600 text-sm mt-1"> Live backend integration for fish type profiles and calculators </p> </div> <div className="flex gap-2"> <Button variant="outline" onClick={() => void loadFishTypes(true)} disabled={isRefreshing} > {isRefreshing ? ( <Loader2 className="w-4 h-4 mr-2 animate-spin" /> ) : ( <RefreshCcw className="w-4 h-4 mr-2" /> )} Refresh </Button> {isTechnician && ( <Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={openCreateModal} > <Plus className="w-4 h-4 mr-2" /> Add Fish Type </Button> )} </div> </div>
{isLoading ? ( <Card> <CardContent className="py-10 flex items-center gap-2 text-gray-600"> <Loader2 className="w-4 h-4 animate-spin" /> Loading fish types... </CardContent> </Card> ) : fishTypes.length === 0 ? ( <Card> <CardContent className="py-10 text-sm text-gray-600"> No fish types found. </CardContent> </Card> ) : ( <div className="grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4"> {fishTypes.map((fishType) => ( <Card key={fishType.id} className="bg-white shadow-sm"> <CardHeader> <div className="flex items-start justify-between"> <div> <CardTitle className="text-lg">{fishType.name}</CardTitle> <p className="text-sm text-gray-600 italic mt-1"> {fishType.scientificName} </p> {fishType.arabicName ? ( <p className="text-sm text-gray-500 mt-1"> {fishType.arabicName} </p> ) : null} </div> <Badge className={ fishType.isActive ? "bg-[#10B981] text-white" : "bg-gray-500 text-white" } > {fishType.isActive ? "Active" : "Inactive"} </Badge> </div> </CardHeader> <CardContent className="space-y-3 text-sm"> <p> Temp: {fishType.tempMin} - {fishType.tempMax} °C </p> <p> DO: {fishType.doMin} - {fishType.doSafe} mg/L </p> <p> FCR Target: {fishType.fcrMin} - {fishType.fcrMax} </p> <p>Survival Rate: {fishType.survivalRate}%</p> {isTechnician && ( <Button variant="outline" className="w-full" onClick={() => void openEditModal(fishType.id)} > Edit </Button> )} </CardContent> </Card> ))} </div> )}
<Card> <CardHeader> <CardTitle>Fish Type Calculators</CardTitle> </CardHeader> <CardContent className="space-y-4"> {calculatorError ? ( <div className="text-sm text-red-700 flex items-center gap-2"> <AlertCircle className="w-4 h-4" /> {calculatorError} </div> ) : null} <div className="grid grid-cols-1 md:grid-cols-4 gap-3"> <div className="md:col-span-2"> <Label>Fish Type</Label> <select className="mt-1 w-full h-9 border rounded-md px-3 bg-white" value={calculatorFishTypeId} onChange={(event) => setCalculatorFishTypeId(event.target.value) } > <option value="">Select fish type</option> {fishTypes.map((fishType) => ( <option key={fishType.id} value={fishType.id}> {fishType.name} </option> ))} </select> </div> <div> <Label>Weight (g)</Label> <Input type="number" value={calculatorWeight} onChange={(event) => setCalculatorWeight(Number(event.target.value) || 0) } /> </div> <div> <Label>Temperature (°C)</Label> <Input type="number" value={calculatorTemperature} onChange={(event) => setCalculatorTemperature(Number(event.target.value) || 0) } /> </div> </div> <Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => void runCalculators()} disabled={isRunningCalculator} > {isRunningCalculator ? ( <Loader2 className="w-4 h-4 mr-2 animate-spin" /> ) : null} Run Calculators </Button> <div className="grid grid-cols-1 md:grid-cols-3 gap-4"> <Card className="bg-gray-50"> <CardHeader className="pb-2"> <CardTitle className="text-sm">Feeding Rate</CardTitle> </CardHeader> <CardContent className="text-sm"> {feedingRateResult ? `${feedingRateResult.feedingRatePercentage}% body weight/day` : "Run calculator"} </CardContent> </Card>
<Card className="bg-gray-50"> <CardHeader className="pb-2"> <CardTitle className="text-sm">Protein Requirement</CardTitle> </CardHeader> <CardContent className="text-sm"> {proteinRequirementResult ? `${proteinRequirementResult.proteinPercentage}% protein` : "Run calculator"} </CardContent> </Card> </div> </CardContent> </Card> </div>
<Dialog open={isModalOpen} onOpenChange={(open) => { if (!open && !isSaving) { setFormError(null); } setIsModalOpen(open); }} > <DialogContent className="max-w-[95vw] w-[860px] max-h-[95vh] overflow-y-auto p-0 bg-white border border-[#BFD2DA] shadow-2xl"> <div className="px-6 pt-6 pb-4 border-b border-[#C8D9E0] bg-white sticky top-0 z-10"> <DialogHeader className="gap-0"> <DialogTitle className="text-2xl font-bold text-[#1F2937]"> {editingFishTypeId ? "Edit Fish Type" : "Create New Fish Type"} </DialogTitle> <DialogDescription className="sr-only"> Configure fish type profile, water quality, feeding matrix, protein rules, and food compatibility. </DialogDescription> </DialogHeader> {formError && ( <div className="mt-4 p-3 bg-red-50 border border-red-200 rounded-md text-sm text-red-700 flex items-center gap-2"> <AlertCircle className="w-4 h-4 flex-shrink-0" /> {formError} </div> )} </div>
<Tabs value={activeFormTab} onValueChange={(value) => setActiveFormTab(value as FormTab)} className="px-6 py-5 space-y-5" > <TabsList className="grid w-full grid-cols-3 rounded-xl bg-[#E4EDF1] p-1 h-auto gap-1 border border-[#C7D8DF]"> <TabsTrigger value="basic" style={ activeFormTab === "basic" ? { backgroundColor: "#1591DC", color: "#fff" } : undefined } className="h-auto min-h-10 whitespace-normal text-center leading-tight py-2 px-2 text-sm font-semibold rounded-lg border border-transparent text-[#2C4250] data-[state=active]:bg-[#1591DC] data-[state=active]:text-white data-[state=active]:border-[#1591DC] data-[state=active]:shadow-sm" > Basic Info </TabsTrigger> <TabsTrigger value="water" style={ activeFormTab === "water" ? { backgroundColor: "#1591DC", color: "#fff" } : undefined } className="h-auto min-h-10 whitespace-normal text-center leading-tight py-2 px-2 text-sm font-semibold rounded-lg border border-transparent text-[#2C4250] data-[state=active]:bg-[#1591DC] data-[state=active]:text-white data-[state=active]:border-[#1591DC] data-[state=active]:shadow-sm" > Water Quality </TabsTrigger> <TabsTrigger value="feeding" style={ activeFormTab === "feeding" ? { backgroundColor: "#1591DC", color: "#fff" } : undefined } className="h-auto min-h-10 whitespace-normal text-center leading-tight py-2 px-2 text-sm font-semibold rounded-lg border border-transparent text-[#2C4250] data-[state=active]:bg-[#1591DC] data-[state=active]:text-white data-[state=active]:border-[#1591DC] data-[state=active]:shadow-sm" > Feeding Rates </TabsTrigger> <TabsTrigger value="protein" style={ activeFormTab === "protein" ? { backgroundColor: "#1591DC", color: "#fff" } : undefined } className="h-auto min-h-10 whitespace-normal text-center leading-tight py-2 px-2 text-sm font-semibold rounded-lg border border-transparent text-[#2C4250] data-[state=active]:bg-[#1591DC] data-[state=active]:text-white data-[state=active]:border-[#1591DC] data-[state=active]:shadow-sm" > Protein </TabsTrigger> <TabsTrigger value="food" style={ activeFormTab === "food" ? { backgroundColor: "#1591DC", color: "#fff" } : undefined } className="h-auto min-h-10 whitespace-normal text-center leading-tight py-2 px-2 text-sm font-semibold rounded-lg border border-transparent text-[#2C4250] data-[state=active]:bg-[#1591DC] data-[state=active]:text-white data-[state=active]:border-[#1591DC] data-[state=active]:shadow-sm" > Food Types </TabsTrigger> </TabsList>
<TabsContent value="basic" className="space-y-4 mt-0 border border-[#D3E1E8] rounded-lg bg-white p-4" > <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div> <Label htmlFor="fish-type-name" className="text-sm font-medium" > Name * </Label> <Input id="fish-type-name" placeholder="e.g., Tilapia" value={formState.name} onChange={(event) => setFormState((previous) => ({ ...previous, name: event.target.value, })) } /> </div> <div> <Label htmlFor="fish-type-scientific-name" className="text-sm font-medium" > Scientific Name * </Label> <Input id="fish-type-scientific-name" placeholder="e.g., Oreochromis niloticus" value={formState.scientificName} onChange={(event) => setFormState((previous) => ({ ...previous, scientificName: event.target.value, })) } /> </div> <div> <Label className="text-sm font-medium">Arabic Name</Label> <Input placeholder="e.g., البلطي" value={formState.arabicName} onChange={(event) => setFormState((previous) => ({ ...previous, arabicName: event.target.value, })) } /> </div> <div> <Label className="text-sm font-medium"> Target SGR (%/day) </Label> <Input type="number" step="0.1" min="0" value={formState.targetSGR} onChange={(event) => setFormState((previous) => ({ ...previous, targetSGR: toNumber(event.target.value), })) } /> </div> </div>
<div> <Label className="text-sm font-medium">Description</Label> <Textarea rows={3} placeholder="Additional details about this fish type..." value={formState.description} onChange={(event) => setFormState((previous) => ({ ...previous, description: event.target.value, })) } /> </div>
<div> <Label className="mb-2 block">Critical Parameters</Label> <div className="grid grid-cols-2 sm:grid-cols-4 gap-2"> {CRITICAL_PARAMETER_OPTIONS.map((parameter) => { const selected = formState.criticalParameters.includes(parameter); return ( <button type="button" key={parameter} className={`px-3 py-2 rounded-lg border text-sm text-left ${ selected ? "bg-[#E0F4F5] border-[#088395] text-[#0A4D68]" : "bg-white border-gray-300" }`} onClick={() => toggleCriticalParameter(parameter)} > {parameter} </button> ); })} </div> </div> </TabsContent>
<TabsContent value="water" className="space-y-6 mt-0 border border-[#D3E1E8] rounded-lg bg-white p-4" > <div> <h3 className="text-lg font-semibold text-[#1F2937] mb-4"> Water Quality Thresholds (Min - Max) </h3>
<div className="grid grid-cols-1 md:grid-cols-2 gap-6"> {[ { label: "Temperature (°C)", minKey: "tempMin", maxKey: "tempMax", step: "0.1", }, { label: "Dissolved Oxygen (mg/L)", minKey: "doMin", maxKey: "doMax", step: "0.1", }, { label: "pH", minKey: "phMin", maxKey: "phMax", step: "0.1", }, { label: "Ammonia (mg/L)", minKey: "nh3Min", maxKey: "nh3Max", step: "0.01", }, { label: "Nitrite (mg/L)", minKey: "no2Min", maxKey: "no2Max", step: "0.01", }, { label: "Turbidity (NTU)", minKey: "turbidityMin", maxKey: "turbidityMax", step: "0.1", }, ].map(({ label, minKey, maxKey, step }) => ( <div key={label} className="p-3 border rounded-lg bg-gray-50/50 space-y-3" > <h4 className="text-sm font-bold text-[#0A4D68] border-b pb-1"> {label} </h4> <div className="grid grid-cols-2 gap-4"> <div> <Label className="text-xs font-medium text-gray-500 mb-1 block"> Minimum </Label> <Input type="number" step={step} value={ formState[ minKey as keyof FishTypeFormState ] as number } onChange={(e) => setFormState((prev) => ({ ...prev, [minKey]: toNumber(e.target.value), })) } className="h-9 bg-white" /> </div> <div> <Label className="text-xs font-medium text-gray-500 mb-1 block"> Maximum </Label> <Input type="number" step={step} value={ formState[ maxKey as keyof FishTypeFormState ] as number } onChange={(e) => setFormState((prev) => ({ ...prev, [maxKey]: toNumber(e.target.value), })) } className="h-9 bg-white" /> </div> </div> </div> ))} </div> </div>
<div> <h3 className="text-lg font-semibold text-[#1F2937] mb-4"> Performance Benchmarks </h3> <div className="space-y-3"> <div className="grid grid-cols-1 sm:grid-cols-3 gap-3"> {[ { key: "fcrMin", label: "FCR Minimum (Best)" }, { key: "fcrMax", label: "FCR Maximum (Acceptable)" }, { key: "survivalRate", label: "Expected Survival Rate (%)", }, ].map(({ key, label }) => ( <div key={key}> <Label className="text-xs font-medium text-gray-700"> {label} </Label> <Input type="number" step={key === "survivalRate" ? "1" : "0.1"} value={ formState[key as keyof FishTypeFormState] as number } onChange={(event) => setFormState((previous) => ({ ...previous, [key]: toNumber(event.target.value), })) } /> </div> ))} </div> <div className="grid grid-cols-1 sm:grid-cols-2 gap-3"> {[ { key: "targetWeightForHarvest", label: "Target Weight For Harvest (kg)", }, { key: "defaultMarketPrice", label: "Default Market Price (EGP/kg)", }, ].map(({ key, label }) => ( <div key={key}> <Label className="text-xs font-medium text-gray-700"> {label} </Label> <Input type="number" step="0.1" value={ formState[key as keyof FishTypeFormState] as number } onChange={(event) => setFormState((previous) => ({ ...previous, [key]: toNumber(event.target.value), })) } /> </div> ))} </div> </div> </div> </TabsContent>
<TabsContent value="feeding" className="space-y-4 mt-0 border border-[#D3E1E8] rounded-lg bg-white p-4" > <div className="flex flex-wrap gap-2 justify-between items-center"> <h3 className="text-base font-semibold">Feeding Rate Matrix</h3> <div className="flex gap-2"> <Button type="button" variant="outline" size="sm" onClick={addFeedingTemperature} > <Plus className="w-3 h-3 mr-1" /> Temperature </Button> <Button type="button" variant="outline" size="sm" onClick={addWeightRange} > <Plus className="w-3 h-3 mr-1" /> Weight Range </Button> </div> </div>
<Card className="bg-white border border-[#D3E1E8]"> <CardContent className="pt-4 space-y-3"> <p className="text-sm font-medium text-gray-700"> Temperature Columns (°C) </p> <div className="flex flex-wrap gap-2"> {formState.feedingRateMatrix.temperatures.map( (temperature, index) => ( <div key={`temperature-${index}`} className="flex items-center gap-1 border rounded-md bg-gray-50 px-2 py-1" > <Input type="number" className="w-20 h-8 bg-white" value={temperature} onChange={(event) => updateFeedingMatrix((matrix) => { matrix.temperatures[index] = toNumber( event.target.value, ); }) } /> <span className="text-xs text-gray-600">°C</span> <Button type="button" variant="ghost" size="sm" className="h-8 w-8 p-0 hover:bg-red-50 hover:text-red-600" onClick={() => removeFeedingTemperature(index)} disabled={ formState.feedingRateMatrix.temperatures.length <= 1 } > <Trash2 className="w-3 h-3" /> </Button> </div> ), )} </div> </CardContent> </Card>
<div className="overflow-x-auto border rounded-lg bg-white"> <table className="w-full min-w-[720px] text-sm"> <thead className="bg-gray-50"> <tr> <th className="px-3 py-2 text-left border-b"> Weight Range (g) </th> {formState.feedingRateMatrix.temperatures.map( (temperature, index) => ( <th key={`rate-head-${index}`} className="px-3 py-2 text-center border-b" > {temperature}°C </th> ), )} <th className="px-3 py-2 text-center border-b">Action</th> </tr> </thead> <tbody> {formState.feedingRateMatrix.weight_ranges.map( (range, weightIndex) => ( <tr key={`weight-range-${weightIndex}`} className="text-gray-900" > <td className="px-3 py-2 border-b"> <div className="flex items-center gap-2"> <Input type="number" className="h-8 w-24 shrink-0 bg-white text-gray-900 font-medium" value={range.min ?? 0} onChange={(event) => updateFeedingMatrix((matrix) => { matrix.weight_ranges[weightIndex].min = toNumber(event.target.value); }) } /> <span>-</span> <Input type="number" className="h-8 w-24 shrink-0 bg-white text-gray-900 font-medium" value={range.max ?? 0} onChange={(event) => updateFeedingMatrix((matrix) => { matrix.weight_ranges[weightIndex].max = toNumber(event.target.value); }) } /> </div> </td> {formState.feedingRateMatrix.temperatures.map( (_, temperatureIndex) => ( <td key={`rate-cell-${weightIndex}-${temperatureIndex}`} className="px-3 py-2 border-b" > <Input type="number" step="0.01" className="h-8 w-20 shrink-0 bg-white text-gray-900 font-medium" value={ formState.feedingRateMatrix.rates[ weightIndex ]?.[temperatureIndex] ?? 0 } onChange={(event) => updateFeedingMatrix((matrix) => { matrix.rates[weightIndex][ temperatureIndex ] = toNumber(event.target.value); }) } /> </td> ), )} <td className="px-3 py-2 border-b text-center"> <Button type="button" variant="ghost" size="sm" onClick={() => removeWeightRange(weightIndex)} disabled={ formState.feedingRateMatrix.weight_ranges .length <= 1 } > <Trash2 className="w-4 h-4" /> </Button> </td> </tr> ), )} </tbody> </table> </div> </TabsContent>
<TabsContent value="protein" className="space-y-4 mt-0 border border-[#D3E1E8] rounded-lg bg-white p-4" > <Card className="bg-white border border-[#D3E1E8]"> <CardHeader className="pb-3"> <CardTitle className="text-sm flex items-center justify-between"> <span className="font-semibold">Protein Requirements</span> <Button type="button" size="sm" variant="outline" onClick={addProteinRequirement} > <Plus className="w-3 h-3 mr-1" /> Add Rule </Button> </CardTitle> </CardHeader> <CardContent className="space-y-2"> {formState.proteinRequirements.length === 0 ? ( <p className="text-sm text-gray-500"> No rules configured. </p> ) : ( formState.proteinRequirements.map((rule, index) => ( <div key={`protein-rule-${index}`} className="grid grid-cols-1 sm:grid-cols-[1fr_1fr_1fr_auto] gap-2 items-end p-2 border rounded-md bg-gray-50" > <div> <Label className="text-xs font-medium text-gray-700"> Min Weight (g) </Label> <Input type="number" value={rule.minWeight ?? ""} onChange={(event) => updateProteinRequirement( index, "minWeight", toNullableNumber(event.target.value), ) } /> </div> <div> <Label className="text-xs font-medium text-gray-700"> Max Weight (g) </Label> <Input type="number" value={rule.maxWeight ?? ""} placeholder="Leave empty for no max" onChange={(event) => updateProteinRequirement( index, "maxWeight", toNullableNumber(event.target.value), ) } /> </div> <div> <Label className="text-xs font-medium text-gray-700"> Protein % </Label> <Input type="number" min="0" value={rule.proteinPercentage} onChange={(event) => updateProteinRequirement( index, "proteinPercentage", Math.max(0, toNumber(event.target.value)), ) } /> </div> <Button type="button" variant="ghost" size="sm" className="hover:bg-red-50 hover:text-red-600" onClick={() => removeProteinRequirement(index)} disabled={formState.proteinRequirements.length <= 1} > <Trash2 className="w-4 h-4" /> </Button> </div> )) )} </CardContent> </Card> </TabsContent>
<TabsContent value="food" className="space-y-4 mt-0 border border-[#D3E1E8] rounded-lg bg-white p-4" > <Card className="bg-white border border-[#D3E1E8]"> <CardHeader className="pb-3"> <CardTitle className="text-sm font-semibold"> Allowed Food Types </CardTitle> </CardHeader> <CardContent className="space-y-2"> {isLoadingFoodTypes ? ( <div className="flex items-center gap-2 text-sm text-gray-600"> <Loader2 className="w-4 h-4 animate-spin" /> Loading food types... </div> ) : foodTypes.length === 0 ? ( <p className="text-sm text-gray-600"> No food types available. </p> ) : ( (() => { const selectedFoodTypes = foodTypes.filter((foodType) => formState.allowedFoodTypeIds.includes(foodType.id), ); const nonSelectedFoodTypes = foodTypes.filter( (foodType) => !formState.allowedFoodTypeIds.includes(foodType.id), );
const FOOD_TYPES_PER_PAGE = 6; const pageCount = Math.ceil( nonSelectedFoodTypes.length / FOOD_TYPES_PER_PAGE, ); const safePage = Math.min( foodTypePage, Math.max(pageCount - 1, 0), ); const pagedNonSelected = nonSelectedFoodTypes.slice( safePage * FOOD_TYPES_PER_PAGE, safePage * FOOD_TYPES_PER_PAGE + FOOD_TYPES_PER_PAGE, );
const renderFoodTypeOption = ( foodType: FoodTypeOption, checked: boolean, ) => ( <label key={foodType.id} className={`border rounded-md p-3 text-sm flex items-center justify-between cursor-pointer transition-colors ${checked ? "bg-[#DCF4F7] border-[#0D8FA3]" : "bg-white border-[#C8D7DF] hover:border-[#0D8FA3]"}`} > <span className="flex items-center gap-2"> <Wheat className="w-4 h-4 text-[#0D8FA3]" /> {foodType.name} </span> <input type="checkbox" checked={checked} onChange={(event) => toggleAllowedFoodType( foodType.id, event.target.checked, ) } className="w-4 h-4 cursor-pointer" /> </label> );
return ( <div className="space-y-4"> <div> <p className="text-xs font-semibold text-[#0A4D68] mb-2"> Selected ({selectedFoodTypes.length}) </p> {selectedFoodTypes.length === 0 ? ( <p className="text-sm text-gray-500 border rounded-md p-3 bg-gray-50"> No selected food types. </p> ) : ( <div className="grid grid-cols-1 md:grid-cols-2 gap-2"> {selectedFoodTypes.map((foodType) => renderFoodTypeOption(foodType, true), )} </div> )} </div>
<div> <p className="text-xs font-semibold text-gray-600 mb-2"> Not Selected ({nonSelectedFoodTypes.length}) </p> {nonSelectedFoodTypes.length === 0 ? ( <p className="text-sm text-gray-500 border rounded-md p-3 bg-gray-50"> All food types are selected. </p> ) : ( <> <div className="grid grid-cols-1 md:grid-cols-2 gap-2"> {pagedNonSelected.map((foodType) => renderFoodTypeOption(foodType, false), )} </div> {pageCount > 1 && ( <div className="flex justify-center pt-3"> <Pagination count={pageCount} page={safePage + 1} onChange={(_, page) => setFoodTypePage(page - 1) } color="primary" size="small" /> </div> )} </> )} </div> </div> ); })() )} </CardContent> </Card>
<Card className="bg-white border border-[#D3E1E8]"> <CardContent className="pt-4 space-y-4"> {" "} <div> <Label className="text-sm font-medium">Notes</Label> <Textarea rows={3} placeholder="Additional notes..." value={formState.notes} onChange={(event) => setFormState((previous) => ({ ...previous, notes: event.target.value, })) } /> </div> </CardContent> </Card> </TabsContent>
<div className="border-t border-[#C8D9E0] pt-4 flex flex-col sm:flex-row gap-3"> <Button variant="outline" className="flex-1 h-11" onClick={() => setIsModalOpen(false)} disabled={isSaving} > Cancel </Button> <Button className="flex-1 h-11 bg-[#0D8FA3] hover:bg-[#0A6F83] border border-[#0A6F83] text-black" onClick={() => void saveFishType()} disabled={isSaving} > {isSaving ? ( <Loader2 className="w-4 h-4 mr-2 animate-spin" /> ) : null} {editingFishTypeId ? "Update Fish Type" : "Create Fish Type"} </Button> </div> </Tabs> </DialogContent> </Dialog> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500// ============================================================// FoodTypeManagement.tsx – Updated by Ziad (Clean Version)// ============================================================
import { useState, useEffect, useCallback, useMemo } from "react";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Button } from "./ui/button";import { Input } from "./ui/input";import { Label } from "./ui/label";import { Textarea } from "./ui/textarea";import { Dialog, DialogContent, DialogHeader, DialogTitle } from "./ui/dialog";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "./ui/select";import { Badge } from "./ui/badge";import { Wheat, Plus, Edit, Trash2, RefreshCw, Loader2, BellRing,} from "lucide-react";import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,} from "./ui/alert-dialog";import Pagination from "@mui/material/Pagination";import { User, Farm, BuoyancyType, ManufacturingProcess, GrowthStage,} from "../types";import { mockFarms } from "../mockData";import { apiGet, apiPost, apiPut, apiDelete } from "../api";import { toast } from "sonner";
interface FoodTypeManagementProps { user: User; selectedFarm: Farm | null;}
export default function FoodTypeManagement({ user, selectedFarm,}: FoodTypeManagementProps) { const currentFarm = selectedFarm || mockFarms[0]; const [showCreateModal, setShowCreateModal] = useState(false); const [editingId, setEditingId] = useState<string | null>(null); const [saving, setSaving] = useState(false); const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
const [foodTypes, setFoodTypes] = useState<any[]>([]); const [loading, setLoading] = useState(true); const [error, setError] = useState<string | null>(null);
const [currentPage, setCurrentPage] = useState(0); const ITEMS_PER_PAGE = 6;
const [formData, setFormData] = useState({ name: "", arabicName: "", proteinPercentage: 30, fatPercentage: 6, fiberPercentage: 4, moisturePercentage: 10, ashPercentage: 12, pelletSizeMm: 3, buoyancyType: "FLOATING" as BuoyancyType, manufacturingProcess: "EXTRUDED" as ManufacturingProcess, applicableStages: [] as GrowthStage[], minFishWeightGrams: 0, maxFishWeightGrams: 0, shelfLifeDays: 180, storageInstructions: "", waterStabilityMinutes: 30, isActive: true, notes: "", lowStockThreshold: 100, });
const fetchFoodTypes = useCallback(async () => { setLoading(true); setError(null); try { const res = await apiGet<any>("/aquaculture/food-types?limit=100"); const rawData = res.data || res || []; const normalizedData = Array.isArray(rawData) ? rawData.map((item: any) => ({ ...item, id: item.id || item._id, })) : []; setFoodTypes(normalizedData); setCurrentPage(0); } catch (err) { setError((err as Error).message); } finally { setLoading(false); } }, []);
useEffect(() => { fetchFoodTypes(); }, [fetchFoodTypes]);
const foodTypePages = useMemo(() => { const pages = [];
for (let i = 0; i < foodTypes.length; i += ITEMS_PER_PAGE) { pages.push(foodTypes.slice(i, i + ITEMS_PER_PAGE)); }
return pages; }, [foodTypes]);
const currentFoodTypes = foodTypePages[currentPage] || [];
const handleEdit = (foodType: any) => { setFormData({ ...foodType, lowStockThreshold: foodType.lowStockThreshold || 100, }); setEditingId(foodType.id); setShowCreateModal(true); };
const handleDelete = async () => { if (!deleteConfirmId) return; try { await apiDelete(`/aquaculture/food-types/${deleteConfirmId}`); toast.success("Food type deleted"); fetchFoodTypes(); } catch (err) { toast.error("Failed to delete: " + (err as Error).message); } finally { setDeleteConfirmId(null); } };
const handleSave = async () => { if (!formData.name || !formData.arabicName) { toast.error("الاسم والاسم العربي مطلوبين"); return; }
setSaving(true); const { id, createdAt, updatedAt, deletedAt, ...submissionData } = formData as any;
try { if (editingId) { await apiPut(`/aquaculture/food-types/${editingId}`, submissionData); } else { await apiPost("/aquaculture/food-types", submissionData); } toast.success("تم الحفظ بنجاح عبر الـ API"); fetchFoodTypes(); } catch (err) { console.warn("API Error - Switching to Mock Data:", err); const mockItem = { ...formData, id: editingId || Math.random().toString(36).substr(2, 9), }; if (editingId) { setFoodTypes((prev) => prev.map((item) => (item.id === editingId ? mockItem : item)), ); } else { setFoodTypes((prev) => [...prev, mockItem]); } toast.info("تمت الإضافة محلياً"); } finally { setSaving(false); setShowCreateModal(false); setEditingId(null); setFormData({ name: "", arabicName: "", proteinPercentage: 30, fatPercentage: 6, fiberPercentage: 4, moisturePercentage: 10, ashPercentage: 12, pelletSizeMm: 3, buoyancyType: "FLOATING", manufacturingProcess: "EXTRUDED", applicableStages: [], minFishWeightGrams: 0, maxFishWeightGrams: 0, shelfLifeDays: 180, storageInstructions: "", waterStabilityMinutes: 30, isActive: true, notes: "", lowStockThreshold: 100, }); } }; const isTechnician = user.role.toLowerCase() === "technician"; return ( <div className="min-h-screen bg-[#F9FAFB]"> <div className="bg-[#0A4D68] text-white px-6 py-4"> <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> <Wheat className="w-6 h-6" /> <span className="text-xl font-semibold">Food Type Management</span> </div> </div> </div>
<div className="p-6 space-y-6"> <div className="flex justify-between items-center"> <div> <h2 className="text-2xl font-semibold">Fish Feed Products</h2> <p className="text-sm text-gray-500"> Manage nutritional composition and inventory alert levels </p> </div> <div className="flex items-center gap-3"> <Button variant="outline" size="sm" onClick={() => fetchFoodTypes()} disabled={loading} > <RefreshCw className={`w-4 h-4 mr-1 ${loading ? "animate-spin" : ""}`} /> Refresh </Button> {isTechnician && ( <Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => { setEditingId(null); setShowCreateModal(true); }} > <Plus className="w-4 h-4 mr-2" /> Add Food Type </Button> )} </div> </div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> {loading ? ( <div className="col-span-full py-20 flex justify-center"> <Loader2 className="animate-spin text-[#088395]" /> </div> ) : foodTypes.length === 0 ? ( <div className="col-span-full py-20 bg-white border border-dashed rounded-xl flex flex-col items-center justify-center text-gray-400"> <Plus className="w-10 h-10 mb-4 opacity-20" /> <p>No feed types registered yet.</p> <Button variant="link" onClick={() => setShowCreateModal(true)}> Add your first food type </Button> </div> ) : ( currentFoodTypes.map((foodType) => ( <Card key={foodType.id} className="bg-white shadow-sm border-t-4 border-[#088395]" > <CardHeader className="pb-2"> <div className="flex justify-between items-start"> <div> <CardTitle className="text-lg">{foodType.name}</CardTitle> <p className="text-xs text-gray-400"> {foodType.arabicName} </p> </div> <Badge variant="secondary" className="bg-[#088395]/10 text-[#088395] border-none flex gap-1 items-center" > <BellRing className="w-3 h-3" /> {foodType.lowStockThreshold || 100} kg </Badge> </div> </CardHeader> <CardContent className="space-y-4"> <div className="flex gap-2 flex-wrap"> <Badge variant="outline" className="text-[10px]"> {foodType.proteinPercentage}% Protein </Badge> <Badge variant="outline" className="text-[10px]"> {foodType.pelletSizeMm}mm </Badge> <Badge variant="outline" className="text-[10px]"> {foodType.buoyancyType} </Badge> </div> {isTechnician && ( <div className="flex gap-2 pt-2 border-t"> <Button size="sm" variant="outline" className="flex-1" onClick={() => handleEdit(foodType)} > <Edit className="w-3 h-3 mr-1" /> Edit </Button> <Button size="sm" variant="outline" className="text-red-500 hover:bg-red-50" onClick={() => setDeleteConfirmId(foodType.id)} > <Trash2 className="w-3 h-3" /> </Button> </div> )} </CardContent> </Card> )) )} </div>
{!loading && foodTypePages.length > 1 && ( <div className="flex justify-center py-4"> <Pagination count={foodTypePages.length} page={currentPage + 1} onChange={(_, page) => setCurrentPage(page - 1)} color="primary" showFirstButton showLastButton /> </div> )} </div>
<Dialog open={showCreateModal} onOpenChange={setShowCreateModal}> <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto"> <div className="space-y-6 pt-4"> <div className="space-y-4"> <h3 className="text-sm font-bold text-gray-900 uppercase tracking-wider border-b pb-2"> Basic Information </h3> <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="space-y-2"> <Label>Name *</Label> <Input placeholder="English Name" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value }) } /> </div> <div className="space-y-2"> <Label>Arabic Name *</Label> <Input placeholder="الاسم بالعربي" value={formData.arabicName} onChange={(e) => setFormData({ ...formData, arabicName: e.target.value }) } /> </div> </div> </div>
<div className="space-y-4"> <h3 className="text-sm font-bold text-gray-900 uppercase tracking-wider border-b pb-2"> Inventory Settings </h3> <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-end"> <div className="space-y-2"> <Label className="flex items-center gap-2"> <BellRing className="w-4 h-4 text-[#088395]" /> Low Stock Threshold (kg) </Label> <Input type="number" placeholder="e.g. 100" value={formData.lowStockThreshold} onChange={(e) => setFormData({ ...formData, lowStockThreshold: parseInt(e.target.value) || 0, }) } /> </div> <p className="text-[11px] text-gray-400 pb-2 italic"> Systems will alert when stock levels fall below this value. </p> </div> </div>
<div className="space-y-4"> <h3 className="text-sm font-bold text-gray-900 uppercase tracking-wider border-b pb-2"> Composition & Size </h3> <div className="grid grid-cols-3 gap-4"> <div className="space-y-2"> <Label>Protein %</Label> <Input type="number" value={formData.proteinPercentage} onChange={(e) => setFormData({ ...formData, proteinPercentage: parseFloat(e.target.value), }) } /> </div> <div className="space-y-2"> <Label>Fat %</Label> <Input type="number" value={formData.fatPercentage} onChange={(e) => setFormData({ ...formData, fatPercentage: parseFloat(e.target.value), }) } /> </div> <div className="space-y-2"> <Label>Pellet Size (mm)</Label> <Input type="number" step="0.1" value={formData.pelletSizeMm} onChange={(e) => setFormData({ ...formData, pelletSizeMm: parseFloat(e.target.value), }) } /> </div> </div> </div>
<div className="flex gap-3 pt-4 border-t"> <Button variant="outline" className="flex-1" onClick={() => setShowCreateModal(false)} > Cancel </Button> <Button className="flex-1 bg-[#088395] hover:bg-[#0A4D68]" onClick={handleSave} disabled={saving} > {saving ? "Saving..." : editingId ? "Update Product" : "Create Product"} </Button> </div> </div> </DialogContent> </Dialog>
<AlertDialog open={!!deleteConfirmId} onOpenChange={() => setDeleteConfirmId(null)} > <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>Delete Product?</AlertDialogTitle> </AlertDialogHeader> <AlertDialogDescription> This action will remove the feed type from the catalogue permanently. </AlertDialogDescription> <AlertDialogFooter> <AlertDialogCancel>Cancel</AlertDialogCancel> <AlertDialogAction onClick={handleDelete} className="bg-red-600"> Delete </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </div> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492import { useEffect, useMemo, useState } from "react";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Button } from "./ui/button";import { Input } from "./ui/input";import { Label } from "./ui/label";import { Textarea } from "./ui/textarea";import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";import { Badge } from "./ui/badge";import { Fish, Loader2, Plus, RefreshCcw, Scissors, TrendingUp, AlertTriangle, CheckCircle2,} from "lucide-react";import { toast } from "sonner";import { AddHarvestGradingPayload, CompleteHarvestPayload, CreateFishGradePricingPayload, FishGradePricingRecord, HarvestActiveTankRecord, HarvestCondition, HarvestEventRecord, HarvestGradingRecord, HarvestTankRecord, TankBatchRecord, TankBatchesResponse, addHarvestGradingRecord, completeHarvestEvent, createFishGradePricing, getActiveHarvestTanks, getHarvestEvents, getHarvestEventsByTank, getHarvestGradings, getHarvestTanks, getPricingByFishType, getTankBatches, startHarvestEvent, updateFishGradePricing,} from "../services/harvestApi";import { HarvestTypeValue } from "../services/harvestConstants";import { getMetadata, resolveHarvestTypeOptions } from "../services/metaApi";import { FishTypeRecord, getFishTypes } from "../services/fishTypesApi";import { TaskItem, getFarmTasks, getMyTasks } from "../services/taskApi";import { HarvestDashboard } from "./harvest/HarvestDashboard";import { apiGet } from "../api";
interface HarvestManagementProps { farmId: string; userRole?: string;}
type WorkflowStep = 1 | 2 | 3 | 4;
interface PricingDraft { gradeName: string; minWeight: number; maxWeight: number; numOfFishInKilo: number; pricePerKg: number; isWaste: boolean; isActive: boolean;}
const DEFAULT_PRICING_DRAFT: PricingDraft = { gradeName: "", minWeight: 0, maxWeight: 0, numOfFishInKilo: 0, pricePerKg: 0, isWaste: false, isActive: true,};
const CONDITION_OPTIONS: HarvestCondition[] = [ "EXCELLENT", "GOOD", "ACCEPTABLE", "DAMAGED",];
const formatDate = (value?: string): string => { if (!value) { return "N/A"; } const date = new Date(value); if (Number.isNaN(date.getTime())) { return value; } return date.toLocaleString();};
const formatNumber = (value: number): string => value.toLocaleString(undefined, { maximumFractionDigits: 2 });const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
const eventMatchesFarm = ( event: HarvestEventRecord, activeTanks: HarvestActiveTankRecord[], knownTanks: HarvestTankRecord[],): boolean => { if (!event.tankId) { return true; }
const activeMatch = activeTanks.some( (activeTank) => activeTank.tankId === event.tankId, ); const tankMatch = knownTanks.some((tank) => tank.id === event.tankId); return activeMatch || tankMatch || knownTanks.length === 0;};
const canAccessDashboard = (role?: string): boolean => { const normalizedRole = String(role || "") .trim() .toLowerCase(); return normalizedRole === "admin" || normalizedRole === "manager";};
export const HarvestManagement = ({ farmId, userRole,}: HarvestManagementProps) => { const [activeTab, setActiveTab] = useState("dashboard"); const [workflowStep, setWorkflowStep] = useState<WorkflowStep>(1); const [isBootstrapping, setIsBootstrapping] = useState(true); const [isRefreshing, setIsRefreshing] = useState(false); const [globalError, setGlobalError] = useState<string | null>(null);
const [harvestEvents, setHarvestEvents] = useState<HarvestEventRecord[]>([]); const [activeTanks, setActiveTanks] = useState<HarvestActiveTankRecord[]>([]); const [availableTanks, setAvailableTanks] = useState<HarvestTankRecord[]>([]); const [fishTypes, setFishTypes] = useState<FishTypeRecord[]>([]); const [historyTankId, setHistoryTankId] = useState(""); const [historyEvents, setHistoryEvents] = useState<HarvestEventRecord[]>([]); const [isLoadingHistory, setIsLoadingHistory] = useState(false);
const [harvestTypeOptions, setHarvestTypeOptions] = useState( resolveHarvestTypeOptions(null), );
const [selectedTankId, setSelectedTankId] = useState(""); const [tankBatches, setTankBatches] = useState<TankBatchesResponse>({ summary: null, batches: [], }); const [selectedBatchId, setSelectedBatchId] = useState(""); const [selectedHarvestType, setSelectedHarvestType] = useState<HarvestTypeValue>("FULL"); const [currentEvent, setCurrentEvent] = useState<HarvestEventRecord | null>( null, ); const [currentGradings, setCurrentGradings] = useState< HarvestGradingRecord[] >([]); const [harvestTasks, setHarvestTasks] = useState<TaskItem[]>([]); const [selectedFishTypeId, setSelectedFishTypeId] = useState(""); const [pricingList, setPricingList] = useState<FishGradePricingRecord[]>([]); const [selectedPricingId, setSelectedPricingId] = useState(""); const [gradingWeightKg, setGradingWeightKg] = useState(""); const [gradingCondition, setGradingCondition] = useState<HarvestCondition>("GOOD"); const [isSubmittingStepAction, setIsSubmittingStepAction] = useState(false);
const [completionPayload, setCompletionPayload] = useState<CompleteHarvestPayload>({ notes: "" }); const [completedEvent, setCompletedEvent] = useState<HarvestEventRecord | null>(null);
const [pricingFishTypeId, setPricingFishTypeId] = useState(""); const [pricingDraft, setPricingDraft] = useState<PricingDraft>( DEFAULT_PRICING_DRAFT, ); const [editingPricingId, setEditingPricingId] = useState<string | null>(null); const [pricingError, setPricingError] = useState<string | null>(null); const [isSavingPricing, setIsSavingPricing] = useState(false); const [isLoadingPricing, setIsLoadingPricing] = useState(false); const [dashSummary, setDashSummary] = useState<any>(null); const [isDashLoading, setIsDashLoading] = useState(false);
const activeEventCount = useMemo( () => harvestEvents.filter( (event) => event.status !== "COMPLETED" && event.status !== "CANCELLED", ).length, [harvestEvents], ); const completedEventCount = useMemo( () => harvestEvents.filter((event) => event.status === "COMPLETED").length, [harvestEvents], ); const totalGradedWeight = useMemo( () => currentGradings.reduce((sum, grading) => sum + grading.weightKg, 0), [currentGradings], ); const totalGradingRevenue = useMemo( () => currentGradings.reduce((sum, grading) => sum + grading.totalValue, 0), [currentGradings], );
const selectedBatch = useMemo( () => tankBatches.batches.find((batch) => batch.id === selectedBatchId) || null, [tankBatches.batches, selectedBatchId], );
const currentFarmEvents = useMemo( () => harvestEvents.filter((event) => eventMatchesFarm(event, activeTanks, availableTanks), ), [harvestEvents, activeTanks, availableTanks], );
const loadBootstrapData = async (silent = false) => { if (silent) { setIsRefreshing(true); setGlobalError(null); } else { setIsBootstrapping(true); setGlobalError(null); }
try { const [ events, activeTankList, tankList, fishTypeList, metadata, dashRes, ] = await Promise.all([ getHarvestEvents(), getActiveHarvestTanks(), getHarvestTanks(), getFishTypes(false), getMetadata(), canAccessDashboard(userRole) ? apiGet<any>("/dashboard") : Promise.resolve(null), ]);
setHarvestEvents(events); setActiveTanks(activeTankList); setAvailableTanks(tankList); setFishTypes(fishTypeList); setHarvestTypeOptions(resolveHarvestTypeOptions(metadata)); setDashSummary(dashRes?.data || null); void loadHarvestTasks();
if (!historyTankId && tankList.length > 0) { setHistoryTankId(tankList[0].id); } if (!pricingFishTypeId && fishTypeList.length > 0) { setPricingFishTypeId(fishTypeList[0].id); } } catch (error) { setGlobalError( error instanceof Error ? error.message : "Failed to load harvest data.", ); } finally { setIsBootstrapping(false); setIsRefreshing(false); } };
const loadHarvestTasks = async () => { try { let data: TaskItem[] = []; try { data = await getFarmTasks(); } catch { data = await getMyTasks(); } setHarvestTasks(data); } catch { setHarvestTasks([]); } };
const loadPricingForFishType = async (fishTypeId: string) => { if (!fishTypeId) { setPricingList([]); return; }
setIsLoadingPricing(true); setPricingError(null); try { const pricing = await getPricingByFishType(fishTypeId); setPricingList(pricing); } catch (error) { setPricingError( error instanceof Error ? error.message : "Failed to load pricing list.", ); setPricingList([]); } finally { setIsLoadingPricing(false); } };
const loadHistoryForTank = async (tankId: string) => { if (!tankId) { setHistoryEvents([]); return; } setIsLoadingHistory(true); setGlobalError(null); try { const events = await getHarvestEventsByTank(tankId); setHistoryEvents(events); } catch (error) { setGlobalError( error instanceof Error ? error.message : "Failed to load tank history.", ); setHistoryEvents([]); } finally { setIsLoadingHistory(false); } };
useEffect(() => { void loadBootstrapData(); }, [farmId]);
useEffect(() => { if (!historyTankId && availableTanks.length > 0) { setHistoryTankId(availableTanks[0].id); return; } if (historyTankId) { void loadHistoryForTank(historyTankId); } }, [historyTankId, availableTanks]);
useEffect(() => { if (!pricingFishTypeId && fishTypes.length > 0) { setPricingFishTypeId(fishTypes[0].id); return; } if (pricingFishTypeId) { void loadPricingForFishType(pricingFishTypeId); } }, [pricingFishTypeId, fishTypes]);
useEffect(() => { if (!selectedTankId) { setTankBatches({ summary: null, batches: [] }); setSelectedBatchId(""); return; }
let cancelled = false; const loadBatches = async () => { setGlobalError(null); try { const response = await getTankBatches(selectedTankId); if (!cancelled) { setTankBatches(response); setSelectedBatchId(response.batches[0]?.id || ""); } } catch (error) { if (!cancelled) { setGlobalError( error instanceof Error ? error.message : "Failed to load tank batches.", ); setTankBatches({ summary: null, batches: [] }); setSelectedBatchId(""); } } };
void loadBatches(); return () => { cancelled = true; }; }, [selectedTankId]);
useEffect(() => { if (selectedBatch?.fishType) { console.log( "[SyncFishType] Selected Batch FishType:", selectedBatch.fishType, ); const ft = fishTypes.find( (f) => f.name.toLowerCase() === selectedBatch.fishType?.toLowerCase(), ); if (ft) { console.log("[SyncFishType] Found matching fishType ID:", ft.id); if (ft.id !== selectedFishTypeId) { setSelectedFishTypeId(ft.id); } } else { console.warn( "[SyncFishType] No matching fishType found for name:", selectedBatch.fishType, ); } } }, [selectedBatch, fishTypes]);
// Sync fish type from tank if no batch is selected or batch has no type useEffect(() => { if (selectedTankId && !selectedBatch?.fishType) { const tank = availableTanks.find((t) => t.id === selectedTankId); console.log( "[SyncFishType] Selected Tank:", tank?.name, "FishType:", tank?.fishType, ); if (tank?.fishType) { const ft = fishTypes.find( (f) => f.name.toLowerCase() === tank.fishType?.toLowerCase(), ); if (ft) { console.log( "[SyncFishType] Found matching fishType ID from tank:", ft.id, ); if (ft.id !== selectedFishTypeId) { setSelectedFishTypeId(ft.id); } } } } }, [selectedTankId, selectedBatch, availableTanks, fishTypes]);
useEffect(() => { if (!selectedFishTypeId) { setPricingList([]); setSelectedPricingId(""); return; }
let cancelled = false; const loadStepPricing = async () => { setIsLoadingPricing(true); setPricingError(null); try { const pricing = await getPricingByFishType(selectedFishTypeId); if (!cancelled) { setPricingList(pricing); // Always reset or pick the first one when fish type changes setSelectedPricingId(pricing[0]?.id || ""); } } catch (error) { if (!cancelled) { setPricingError( error instanceof Error ? error.message : "Failed to load pricing.", ); setPricingList([]); setSelectedPricingId(""); } } finally { if (!cancelled) { setIsLoadingPricing(false); } } };
void loadStepPricing(); return () => { cancelled = true; }; }, [selectedFishTypeId]);
// While on the grading step, refresh tasks now and poll every few seconds so // the grading lock clears automatically within a few seconds of the harvest // task being marked Done — no manual refresh needed. useEffect(() => { if (workflowStep !== 2) { return; } void loadHarvestTasks(); const intervalId = window.setInterval(() => { void loadHarvestTasks(); }, 4000); return () => window.clearInterval(intervalId); }, [workflowStep, currentEvent?.id]);
// Lock grading while any harvest task is still open (OPEN/IN_PROGRESS). // It unlocks as soon as that task is marked Done. const isHarvestTaskPending = useMemo( () => harvestTasks.some((task) => { const isHarvest = `${task.templateId || ""} ${task.title || ""} ${task.description || ""}` .toLowerCase() .includes("harvest"); return ( isHarvest && (task.status === "OPEN" || task.status === "IN_PROGRESS") ); }), [harvestTasks], );
const refreshEventsAndActiveTanks = async () => { const [events, activeTankList] = await Promise.all([ getHarvestEvents(), getActiveHarvestTanks(), ]); setHarvestEvents(events); setActiveTanks(activeTankList); };
const handleStartHarvest = async () => { if (!selectedTankId || !selectedBatchId) { setGlobalError("Select tank and batch before starting harvest."); return; }
setIsSubmittingStepAction(true); setGlobalError(null); try { const event = await startHarvestEvent({ tankId: selectedTankId, harvestType: selectedHarvestType, });
setCurrentEvent(event); setCurrentGradings([]);
const tank = availableTanks.find((t) => t.id === selectedTankId); if (tank?.fishType) { const ft = fishTypes.find( (f) => f.name.toLowerCase() === tank.fishType?.toLowerCase(), ); if (ft) setSelectedFishTypeId(ft.id); }
setWorkflowStep(2); await refreshEventsAndActiveTanks(); } catch (error: any) { // Handle 409 Conflict: If a harvest is already started for this tank, find it and resume if ( error?.status === 409 || (error?.message && error.message.includes("409")) ) { const existingEvent = harvestEvents.find( (e) => e.tankId === selectedTankId && e.status !== "COMPLETED" && e.status !== "CANCELLED", );
if (existingEvent) { setCurrentEvent(existingEvent); const gradings = await getHarvestGradings(existingEvent.id); setCurrentGradings(gradings);
// Set fish type based on tank if available const tank = availableTanks.find((t) => t.id === selectedTankId); if (tank?.fishType) { const ft = fishTypes.find( (f) => f.name.toLowerCase() === tank.fishType?.toLowerCase(), ); if (ft) setSelectedFishTypeId(ft.id); }
setWorkflowStep(2); return; } } setGlobalError( error instanceof Error ? error.message : "Failed to start harvest.", ); } finally { setIsSubmittingStepAction(false); } };
const handleAddGrading = async () => { if (!currentEvent || !selectedPricingId || !selectedFishTypeId) { setGlobalError("Harvest event, fish type, and grade are required."); return; } if (!selectedBatchId) { setGlobalError("Source batch is required for grading."); return; } if (!UUID_PATTERN.test(selectedPricingId)) { setGlobalError( "Selected pricing is invalid. Please choose a valid grade.", ); return; } if (!UUID_PATTERN.test(selectedBatchId)) { setGlobalError("Selected batch is invalid. Please reselect tank batch."); return; }
const parsedWeight = Number(gradingWeightKg); if (!Number.isFinite(parsedWeight) || parsedWeight <= 0) { setGlobalError("Enter a valid grading weight."); return; } const payload: AddHarvestGradingPayload = { fishTypeId: selectedFishTypeId, pricingId: selectedPricingId, sourceBatchId: selectedBatchId, weightKg: parsedWeight, condition: gradingCondition, };
console.log("[handleAddGrading] Submitting grading", { selectedFishTypeId, selectedPricingId, selectedBatchId, payload, });
setIsSubmittingStepAction(true); setGlobalError(null); try { const createdGrading = await addHarvestGradingRecord( currentEvent.id, payload, ); toast.success("Grading record added successfully"); await refreshEventsAndActiveTanks(); const gradings = await getHarvestGradings(currentEvent.id); if (gradings.length > 0) { setCurrentGradings(gradings); } else { setCurrentGradings((previous) => { const exists = previous.some((item) => item.id === createdGrading.id); return exists ? previous : [createdGrading, ...previous]; }); } setGradingWeightKg(""); // Removed automatic step jump to allow multiple gradings } catch (error) { const msg = error instanceof Error ? error.message : "Failed to add grading record."; setGlobalError(msg); toast.error(msg); } finally { setIsSubmittingStepAction(false); } };
const handleCompleteHarvest = async () => { if (!currentEvent) { setGlobalError("No active harvest to complete."); return; }
setIsSubmittingStepAction(true); setGlobalError(null); try { const persistedGradings = await getHarvestGradings(currentEvent.id); if (persistedGradings.length === 0) { throw new Error( "No grading records persisted on server yet. Please add grading again and retry.", ); } setCurrentGradings(persistedGradings);
const completed = await completeHarvestEvent( currentEvent.id, completionPayload, ); toast.success("Harvest event completed successfully"); setCompletedEvent(completed); setWorkflowStep(4); await refreshEventsAndActiveTanks(); } catch (error) { try { // Backend may return 500 while completion is still persisted asynchronously. for (let attempt = 0; attempt < 6; attempt += 1) { if (attempt > 0) { await sleep(1000); } const latestEvents = await getHarvestEvents(); const latest = latestEvents.find( (event) => event.id === currentEvent.id, ); if (latest?.status === "COMPLETED") { setCompletedEvent(latest); setWorkflowStep(4); toast.success("Harvest completed successfully"); await refreshEventsAndActiveTanks(); return; } } } catch { // Ignore recovery lookup failure and show original error. }
const message = error instanceof Error ? error.message.toLowerCase() : ""; if ( (message.includes("internal server error") || message.includes("500")) && currentGradings.length > 0 ) { setGlobalError(null); setCompletedEvent({ ...currentEvent, status: "COMPLETED", }); setWorkflowStep(4); toast.success("Harvest completed successfully"); return; }
const msg = error instanceof Error ? error.message : "Failed to complete harvest."; setGlobalError(msg); toast.error(msg); } finally { setIsSubmittingStepAction(false); } };
const handleContinueHarvest = async (harvest: any) => { const event = harvestEvents.find((e) => e.id === harvest.id); if (!event) { toast.error("Harvest event not found"); return; }
try { setIsDashLoading(true); const gradings = await getHarvestGradings(event.id); setCurrentEvent(event); setCurrentGradings(gradings); setSelectedTankId(event.tankId);
// Try to find the batch ID from the event's source batches or metadata // For now, setting step 2 is the most important setWorkflowStep(2); setActiveTab("workflow"); toast.info(`Resuming harvest for ${harvest.tankName}`); } catch (error) { toast.error("Failed to load harvest details"); } finally { setIsDashLoading(false); } };
const handleResetWorkflow = () => { setWorkflowStep(1); setCurrentEvent(null); setCurrentGradings([]); setCompletedEvent(null); setSelectedPricingId(""); setGradingWeightKg(""); setCompletionPayload({ notes: "" }); setSelectedBatchId(""); };
const handleSavePricing = async () => { if (!pricingFishTypeId || !pricingDraft.gradeName.trim()) { setPricingError("Fish type and grade name are required."); return; } setIsSavingPricing(true); setPricingError(null);
const payload: CreateFishGradePricingPayload = { fishTypeId: pricingFishTypeId, gradeName: pricingDraft.gradeName.trim(), minWeight: pricingDraft.minWeight, maxWeight: pricingDraft.maxWeight, numOfFishInKilo: pricingDraft.numOfFishInKilo, pricePerKg: pricingDraft.pricePerKg, isWaste: pricingDraft.isWaste, isActive: pricingDraft.isActive, };
try { if (editingPricingId) { await updateFishGradePricing(editingPricingId, payload); } else { await createFishGradePricing(payload); } setPricingDraft(DEFAULT_PRICING_DRAFT); setEditingPricingId(null); await loadPricingForFishType(pricingFishTypeId); } catch (error) { setPricingError( error instanceof Error ? error.message : "Failed to save pricing.", ); } finally { setIsSavingPricing(false); } };
const startEditingPricing = (pricing: FishGradePricingRecord) => { setEditingPricingId(pricing.id); setPricingDraft({ gradeName: pricing.gradeName, minWeight: pricing.minWeight, maxWeight: pricing.maxWeight, numOfFishInKilo: pricing.numOfFishInKilo, pricePerKg: pricing.pricePerKg, isWaste: pricing.isWaste, isActive: pricing.isActive, }); };
if (isBootstrapping) { return ( <div className="p-6"> <Card> <CardContent className="py-10 flex items-center justify-center gap-2 text-gray-600"> <Loader2 className="w-5 h-5 animate-spin" /> Loading harvest module... </CardContent> </Card> </div> ); }
return ( <div className="w-full min-h-screen bg-[#F9FAFB] flex flex-col"> <div className="bg-[#0A4D68] text-white px-6 py-4"> <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> <Scissors className="w-6 h-6" /> <span className="text-xl font-semibold">Harvest Management</span> </div> <Button variant="outline" className="text-white border-white/30 bg-transparent hover:bg-white/10 hover:text-white" onClick={() => void loadBootstrapData(true)} disabled={isRefreshing} > {isRefreshing ? ( <Loader2 className="w-4 h-4 mr-2 animate-spin" /> ) : ( <RefreshCcw className="w-4 h-4 mr-2" /> )} Refresh </Button> </div> </div>
<div className="p-6 space-y-6"> {globalError && ( <Card className="border-red-200 bg-red-50"> <CardContent className="py-3 text-sm text-red-700"> {globalError} </CardContent> </Card> )}
<Tabs value={activeTab} onValueChange={setActiveTab}> <TabsList className="grid w-full grid-cols-3"> <TabsTrigger value="dashboard">Dashboard</TabsTrigger> <TabsTrigger value="workflow">Harvest</TabsTrigger> <TabsTrigger value="pricing">Grading</TabsTrigger> </TabsList>
<TabsContent value="dashboard" className="space-y-4"> <HarvestDashboard farmId={farmId} onStartHarvest={() => setActiveTab("workflow")} onViewTankPerformance={(tid) => { // Since history is gone, maybe just stay on dashboard or do nothing console.log("View performance for", tid); }} onContinueHarvest={handleContinueHarvest} loading={isBootstrapping} kpis={{ activeHarvests: activeEventCount, thisMonthHarvested: dashSummary?.fishSummary?.totalBiomassKg || 0, thisMonthRevenue: dashSummary?.predictedRevenue?.totalProjectedRevenue || 0, }} activeHarvests={harvestEvents .filter( (e) => e.status !== "COMPLETED" && e.status !== "CANCELLED", ) .map((e) => ({ id: e.id, tankId: e.tankId, tankName: availableTanks.find((t) => t.id === e.tankId)?.name || e.tankId, batchNumber: e.harvestTypeLabel, type: e.harvestType, started: formatDate(e.harvestDate), status: e.status === "STARTED" ? "DRAFT" : e.status, progress: e.estimatedWeight > 0 ? Math.min( 100, Math.round( ((e.actualTotalWeight || 0) / e.estimatedWeight) * 100, ), ) : e.status === "GRADING" ? 50 : 10, estimatedWeight: e.estimatedWeight, gradedWeight: e.actualTotalWeight || 0, }))} completedHarvests={harvestEvents .filter((e) => e.status === "COMPLETED") .slice(0, 5) .map((e) => ({ id: e.id, tankName: availableTanks.find((t) => t.id === e.tankId)?.name || e.tankId, date: formatDate(e.harvestDate), type: e.harvestType, weight: e.actualTotalWeight, revenue: e.totalRevenue, status: "✅", }))} /> </TabsContent>
<TabsContent value="workflow" className="space-y-4"> <Card> <CardHeader> <CardTitle>Harvest Step {workflowStep} / 4</CardTitle> </CardHeader> <CardContent className="space-y-6"> {workflowStep === 1 && ( <div className="space-y-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div> <Label htmlFor="workflow-tank">Tank</Label> <select id="workflow-tank" className="mt-1 w-full h-9 border rounded-md px-3 bg-white" value={selectedTankId} onChange={(event) => setSelectedTankId(event.target.value) } > <option value="">Select tank</option> {availableTanks.map((tank) => ( <option key={tank.id} value={tank.id}> {tank.name} ({tank.status}) </option> ))} </select> </div>
<div> <Label htmlFor="workflow-batch">Batch</Label> <select id="workflow-batch" className="mt-1 w-full h-9 border rounded-md px-3 bg-white" value={selectedBatchId} onChange={(event) => setSelectedBatchId(event.target.value) } disabled={!selectedTankId} > <option value="">Select batch</option> {tankBatches.batches.map((batch) => ( <option key={batch.id} value={batch.id}> {batch.id}{" "} {batch.fishType ? `- ${batch.fishType}` : ""} </option> ))} </select> </div> </div>
<div> <Label>Harvest Type</Label> <div className="mt-1 flex items-center gap-2 px-3 h-9 border rounded-md bg-gray-50 text-sm font-medium"> <Badge className="bg-purple-100 text-purple-700 border-purple-300"> 🟣 Full </Badge> </div> </div>
<Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => void handleStartHarvest()} disabled={ isSubmittingStepAction || !selectedTankId || !selectedBatchId } > {isSubmittingStepAction ? ( <Loader2 className="w-4 h-4 mr-2 animate-spin" /> ) : activeTanks.some( (t) => t.tankId === selectedTankId, ) ? ( <TrendingUp className="w-4 h-4 mr-2" /> ) : ( <Plus className="w-4 h-4 mr-2" /> )} {activeTanks.some((t) => t.tankId === selectedTankId) ? "Resume Active Harvest" : "Start Harvest Event"} </Button> </div> )}
{workflowStep === 2 && ( <div className="space-y-4"> <div className="grid grid-cols-1 md:grid-cols-3 gap-4"> <div> <Label htmlFor="workflow-fish-type">Fish Type</Label> <select id="workflow-fish-type" className="mt-1 w-full h-9 border rounded-md px-3 bg-white disabled:bg-gray-100 disabled:cursor-not-allowed" value={selectedFishTypeId} onChange={(event) => setSelectedFishTypeId(event.target.value) } disabled={!!currentEvent} > <option value="">Select fish type</option> {fishTypes.map((fishType) => ( <option key={fishType.id} value={fishType.id}> {fishType.name} </option> ))} </select> </div> <div> <Label htmlFor="workflow-pricing">Pricing</Label> <select id="workflow-pricing" className="mt-1 w-full h-9 border rounded-md px-3 bg-white" value={selectedPricingId} onChange={(event) => setSelectedPricingId(event.target.value) } disabled={isLoadingPricing} > <option value="">Select pricing</option> {pricingList.map((pricing) => ( <option key={pricing.id} value={pricing.id}> {pricing.gradeName} ({pricing.minWeight}- {pricing.maxWeight}g, {pricing.pricePerKg} EGP/kg) </option> ))} </select> {pricingList.length === 0 && ( <p className="text-xs text-amber-700 mt-1"> No pricing found. Configure pricing in the Pricing tab. </p> )} </div> <div> <Label htmlFor="workflow-condition">Condition</Label> <select id="workflow-condition" className="mt-1 w-full h-9 border rounded-md px-3 bg-white" value={gradingCondition} onChange={(event) => setGradingCondition( event.target.value as HarvestCondition, ) } > {CONDITION_OPTIONS.map((condition) => ( <option key={condition} value={condition}> {condition} </option> ))} </select> </div> </div>
<div className="grid grid-cols-1 gap-4"> <div> <Label htmlFor="workflow-weight-kg">Weight (kg)</Label> <Input id="workflow-weight-kg" type="number" min="0.01" step="0.01" value={gradingWeightKg} onChange={(event) => setGradingWeightKg(event.target.value) } placeholder="Enter harvested weight in kg" /> </div> </div>
{isHarvestTaskPending && ( <div className="flex flex-wrap items-center justify-between gap-3 rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800"> <span className="flex items-center gap-2"> <AlertTriangle className="w-4 h-4 shrink-0" /> Grading is locked until the harvest task for this tank is marked Done. </span> <Button size="sm" variant="outline" onClick={() => void loadHarvestTasks()} > <RefreshCcw className="w-4 h-4 mr-1" /> Recheck </Button> </div> )}
<div className="flex gap-2"> <Button className="bg-[#088395] hover:bg-[#0A4D68] disabled:opacity-50 disabled:cursor-not-allowed" onClick={() => void handleAddGrading()} disabled={ isSubmittingStepAction || isHarvestTaskPending || !selectedFishTypeId || !selectedPricingId || !selectedBatchId || !gradingWeightKg } > {isSubmittingStepAction ? ( <Loader2 className="w-4 h-4 mr-2 animate-spin" /> ) : null} Add Grading </Button> <Button variant="outline" onClick={() => setWorkflowStep(3)} disabled={currentGradings.length === 0} > Continue to Completion </Button> <Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => setWorkflowStep(3)} disabled={currentGradings.length === 0} > Next Step </Button> </div>
{/* Recorded Gradings history box removed as requested */} </div> )}
{workflowStep === 3 && ( <div className="space-y-4"> <Card className="bg-gray-50"> <CardContent className="py-3 text-sm space-y-1"> <p className="font-semibold text-gray-700"> Harvest Summary </p> <p>Harvest Event: {currentEvent?.id}</p> <p> Graded Weight: {formatNumber(totalGradedWeight)} kg </p> <p> Estimated Revenue: {formatNumber(totalGradingRevenue)}{" "} EGP </p> </CardContent> </Card>
<div className="space-y-3"> <Label className="text-base font-semibold"> Grading History </Label> <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4"> {currentGradings.map((grading) => ( <Card key={grading.id} className="overflow-hidden border-blue-100 shadow-sm" > <CardHeader className="bg-blue-50/50 py-2 px-4 border-b"> <CardTitle className="text-sm font-bold flex justify-between items-center"> <span> {grading.gradeName || "Grading Record"} </span> <Badge variant="outline" className="bg-white"> {grading.condition} </Badge> </CardTitle> </CardHeader> <CardContent className="p-4 space-y-2"> <div className="flex justify-between text-sm"> <span className="text-gray-600">Weight:</span> <span className="font-semibold"> {formatNumber(grading.weightKg)} kg </span> </div> <div className="flex justify-between text-sm"> <span className="text-gray-600"> Price at Harvest: </span> <span className="font-semibold"> {formatNumber(grading.pricePerKg)} EGP/kg </span> </div> <div className="border-t pt-2 flex justify-between font-bold text-blue-800"> <span>Total Value:</span> <span> {formatNumber(grading.totalValue)} EGP </span> </div> </CardContent> </Card> ))} </div> </div>
<div> <Label htmlFor="completion-notes">Completion Notes</Label> <Textarea id="completion-notes" rows={4} placeholder="Add optional completion notes..." value={completionPayload.notes || ""} onChange={(event) => setCompletionPayload({ notes: event.target.value, }) } /> </div>
<div className="flex gap-2"> <Button variant="outline" onClick={() => setWorkflowStep(2)} > Back to Grading </Button> <Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => void handleCompleteHarvest()} disabled={isSubmittingStepAction} > {isSubmittingStepAction ? ( <Loader2 className="w-4 h-4 mr-2 animate-spin" /> ) : null} Complete Harvest </Button> </div> </div> )}
{workflowStep === 4 && ( <div className="space-y-4"> <Card className="border-green-200 bg-green-50"> <CardHeader> <CardTitle className="text-green-800"> Harvest Completed </CardTitle> </CardHeader> <CardContent className="space-y-2 text-sm"> <p> Event ID: {completedEvent?.id || currentEvent?.id} </p> <p>Status: {completedEvent?.status || "COMPLETED"}</p> <p> Total Graded Weight: {formatNumber(totalGradedWeight)}{" "} kg </p> {completionPayload.notes?.trim() ? ( <p>Notes: {completionPayload.notes}</p> ) : null} </CardContent> </Card>
<Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={handleResetWorkflow} > Start Another Harvest </Button> </div> )} </CardContent> </Card> </TabsContent>
<TabsContent value="pricing" className="space-y-4"> <Card> <CardHeader> <CardTitle>Fish Grade Management</CardTitle> </CardHeader> <CardContent className="space-y-4"> <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div> <Label htmlFor="pricing-fish-type">Fish Type</Label> <select id="pricing-fish-type" className="mt-1 w-full h-9 border rounded-md px-3 bg-white" value={pricingFishTypeId} onChange={(event) => { setPricingFishTypeId(event.target.value); setEditingPricingId(null); setPricingDraft(DEFAULT_PRICING_DRAFT); }} > <option value="">Select fish type</option> {fishTypes.map((fishType) => ( <option key={fishType.id} value={fishType.id}> {fishType.name} </option> ))} </select> </div>
<div className="flex items-end"> <Button variant="outline" onClick={() => void loadPricingForFishType(pricingFishTypeId) } disabled={!pricingFishTypeId} > <RefreshCcw className="w-4 h-4 mr-2" /> Reload Grading </Button> </div> </div>
{pricingError && ( <p className="text-sm text-red-700">{pricingError}</p> )}
{isLoadingPricing ? ( <div className="flex items-center gap-2 text-sm text-gray-600"> <Loader2 className="w-4 h-4 animate-spin" /> Loading grading... </div> ) : pricingList.length === 0 ? ( <p className="text-sm text-gray-600"> No grading found for selected fish type. </p> ) : ( <div className="space-y-2"> {pricingList.map((pricing) => ( <div key={pricing.id} className="border rounded-md p-3 flex items-center justify-between" > <div className="text-sm"> <p className="font-medium">{pricing.gradeName}</p> <p className="text-gray-600"> {pricing.minWeight}-{pricing.maxWeight} g,{" "} {pricing.numOfFishInKilo} fish/kg </p> {formatNumber(pricing.pricePerKg)} EGP/kg </div> <Button variant="outline" onClick={() => startEditingPricing(pricing)} > Edit </Button> </div> ))} </div> )}
<Card className="bg-gray-50"> <CardHeader className="pb-2"> <CardTitle className="text-sm"> {editingPricingId ? "Edit Grading" : "Create Grading"} </CardTitle> </CardHeader> <CardContent className="space-y-3"> <div className="grid grid-cols-1 md:grid-cols-2 gap-3"> <div> <Label htmlFor="pricing-grade-name">Grade Name</Label> <Input id="pricing-grade-name" value={pricingDraft.gradeName} onChange={(event) => setPricingDraft((prev) => ({ ...prev, gradeName: event.target.value, })) } placeholder="Grade 1" /> </div> <div> <Label htmlFor="pricing-price-per-kg"> Grading Value Per Kg </Label> <Input id="pricing-price-per-kg" type="number" value={pricingDraft.pricePerKg} onChange={(event) => setPricingDraft((prev) => ({ ...prev, pricePerKg: Number(event.target.value) || 0, })) } /> </div> <div> <Label htmlFor="pricing-min-weight"> Min Weight (g) </Label> <Input id="pricing-min-weight" type="number" value={pricingDraft.minWeight} onChange={(event) => setPricingDraft((prev) => ({ ...prev, minWeight: Number(event.target.value) || 0, })) } /> </div> <div> <Label htmlFor="pricing-max-weight"> Max Weight (g) </Label> <Input id="pricing-max-weight" type="number" value={pricingDraft.maxWeight} onChange={(event) => setPricingDraft((prev) => ({ ...prev, maxWeight: Number(event.target.value) || 0, })) } /> </div> <div> <Label htmlFor="pricing-fish-in-kilo"> Fish In Kilo </Label> <Input id="pricing-fish-in-kilo" type="number" value={pricingDraft.numOfFishInKilo} onChange={(event) => setPricingDraft((prev) => ({ ...prev, numOfFishInKilo: Number(event.target.value) || 0, })) } /> </div> </div>
<div className="flex gap-2"> <Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => void handleSavePricing()} disabled={isSavingPricing || !pricingFishTypeId} > {isSavingPricing ? ( <Loader2 className="w-4 h-4 mr-2 animate-spin" /> ) : null} {editingPricingId ? "Update Grading" : "Create Grading"} </Button> {editingPricingId && ( <Button variant="outline" onClick={() => { setEditingPricingId(null); setPricingDraft(DEFAULT_PRICING_DRAFT); }} > Cancel Edit </Button> )} </div> </CardContent> </Card> </CardContent> </Card> </TabsContent> </Tabs> </div> </div> );};1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507import { useEffect, useMemo, useState } from "react";import { AlertTriangle, Book, CheckCircle2, Heart, Layers3, Plus, RefreshCw, Save, Search, ShieldCheck, Stethoscope, Trash2,} from "lucide-react";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Input } from "./ui/input";import { Badge } from "./ui/badge";import { Button } from "./ui/button";import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";import { User, Farm } from "../types";import { apiGet } from "../api";import { getHealthTemplateByKey, resolveHealthReportTemplate,} from "../services/healthKnowledgeBase";import { fetchAllTankHealthOverviews, TankHealthOverview,} from "../services/tankHealthOverview";import { RobotHealthReport } from "./health/RobotHealthReport";import { formatHealthStatus, getHealthStatusColor,} from "../services/healthCheckApi";import { createHealthLibraryConfiguration, createDefaultRiskLevel, DEFAULT_CONDITION_ID, deleteHealthLibraryConfiguration, getConfigurableDiseaseLibraryTemplates, getDefaultRiskLevelsForTemplate, getDiseaseConditionId, getHealthLibraryConditionId, getHealthLibraryConfigId, HealthLibraryConfiguration, HealthLibraryRiskLevel, listHealthLibraryConfigurations, mergeHealthLibraryConfigurationsWithDefaults, normalizeHealthLibraryRiskLevels, updateHealthLibraryConfiguration,} from "../services/healthLibraryApi";import { toast } from "sonner";
interface HealthLibraryProps { user: User; selectedFarm: Farm | null;}const formatDate = (value?: string) => { if (!value) return "Unknown"; const date = new Date(value); if (Number.isNaN(date.getTime())) return value; return date.toLocaleString(undefined, { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", });};
const getBatchLabel = (batch: any) => batch?.batchNumber ? `Batch ${batch.batchNumber}` : `Batch ${String(batch?.id || "").slice(0, 8)}`;
const normalizeTextList = (items?: string[], fallback?: string[]) => { const source = Array.isArray(items) && items.length > 0 ? items : fallback || [""]; return source.map((item) => String(item || ""));};
const compactTextList = (items: string[]) => items.map((item) => item.trim()).filter(Boolean);
export default function HealthLibrary({ user, selectedFarm,}: HealthLibraryProps) { const [searchQuery, setSearchQuery] = useState(""); const [selectedTemplateKey, setSelectedTemplateKey] = useState<string>(""); const [selectedActiveTankId, setSelectedActiveTankId] = useState<string>(""); const [selectedRecoveredTankId, setSelectedRecoveredTankId] = useState<string>(""); const [loading, setLoading] = useState(true); const [overviews, setOverviews] = useState<TankHealthOverview[]>([]); const [libraryConfigs, setLibraryConfigs] = useState< HealthLibraryConfiguration[] >([]); const [loadingConfigs, setLoadingConfigs] = useState(true); const [savingConfig, setSavingConfig] = useState(false); const [selectedConfigId, setSelectedConfigId] = useState<string>(""); const [configConditionId, setConfigConditionId] = useState(DEFAULT_CONDITION_ID); const [configLevels, setConfigLevels] = useState<HealthLibraryRiskLevel[]>( normalizeHealthLibraryRiskLevels(), ); const [configMedicineId, setConfigMedicineId] = useState(""); const [configMedicineName, setConfigMedicineName] = useState(""); const [medicineOptions, setMedicineOptions] = useState< { id: string; name: string }[] >([]); const [configSummary, setConfigSummary] = useState(""); const [configSymptoms, setConfigSymptoms] = useState<string[]>([""]); const [configFeedingGuidance, setConfigFeedingGuidance] = useState<string[]>([ "", ]); const [configRecoveryChecklist, setConfigRecoveryChecklist] = useState< string[] >([""]); const [configPreventiveMeasures, setConfigPreventiveMeasures] = useState< string[] >([""]); const [configQuarantineAdvice, setConfigQuarantineAdvice] = useState("");
const isAdmin = user.role === "admin";
const loadHealthData = async () => { setLoading(true); try { const result = await fetchAllTankHealthOverviews(); setOverviews(result.overviews); } catch (error) { toast.error(`Failed to load health library: ${(error as Error).message}`); } finally { setLoading(false); } };
const loadHealthLibraryConfigs = async ( preferredConditionId = configConditionId, ) => { setLoadingConfigs(true); try { const configs = mergeHealthLibraryConfigurationsWithDefaults( await listHealthLibraryConfigurations(), ); setLibraryConfigs(configs); const targetConditionId = preferredConditionId || DEFAULT_CONDITION_ID; const matchingConfig = configs.find( (config) => getHealthLibraryConditionId(config) === targetConditionId, );
if (matchingConfig) { setSelectedConfigId(getHealthLibraryConfigId(matchingConfig)); setConfigConditionId(getHealthLibraryConditionId(matchingConfig)); setConfigLevels( normalizeHealthLibraryRiskLevels( matchingConfig.levels, getDefaultRiskLevelsForTemplate(selectedTemplate), ), ); setConfigDetails(matchingConfig, selectedTemplate); return; }
const selectedStillExists = selectedConfigId ? configs.some( (config) => getHealthLibraryConfigId(config) === selectedConfigId, ) : false; if (!selectedStillExists) { setSelectedConfigId(""); setConfigConditionId(targetConditionId); setConfigLevels( normalizeHealthLibraryRiskLevels( undefined, getDefaultRiskLevelsForTemplate(selectedTemplate), ), ); setConfigDetails(undefined, selectedTemplate); } } catch (error) { toast.error( `Failed to load health library configurations: ${(error as Error).message}`, ); } finally { setLoadingConfigs(false); } };
const loadMedicineTypes = async () => { try { const res = await apiGet<any>("/inventory/medicine-types"); const data = res?.data ?? res; const items = Array.isArray(data) ? 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 }; }) .filter(Boolean) : []; setMedicineOptions(items); } catch { setMedicineOptions([]); } };
useEffect(() => { void loadHealthData(); void loadMedicineTypes(); }, []);
useEffect(() => { if (isAdmin) { void loadHealthLibraryConfigs(); } }, [isAdmin]);
const filteredOverviews = useMemo(() => { if (!selectedFarm) return overviews; return overviews.filter((overview) => { const farmId = overview.tank?.farmId || overview.tank?.farm?.id || overview.tank?.farm?.farmId; return !farmId || farmId === selectedFarm.id; }); }, [overviews, selectedFarm]);
const templates = useMemo(() => getConfigurableDiseaseLibraryTemplates(), []);
const filteredTemplates = useMemo( () => templates.filter((template) => { const query = searchQuery.trim().toLowerCase(); if (!query) return true; return ( template.title.toLowerCase().includes(query) || template.aliases.some((alias) => alias.includes(query)) || template.symptoms.some((symptom) => symptom.toLowerCase().includes(query), ) ); }), [searchQuery, templates], );
useEffect(() => { const fallbackKey = filteredTemplates[0]?.key || templates[0]?.key || ""; setSelectedTemplateKey((previous) => previous && filteredTemplates.some((template) => template.key === previous) ? previous : fallbackKey, ); }, [filteredTemplates, templates]);
const activeOverviews = useMemo( () => filteredOverviews.filter((overview) => overview.requiresAttention), [filteredOverviews], ); const recoveredOverviews = useMemo( () => filteredOverviews.filter((overview) => overview.isRecovered), [filteredOverviews], );
useEffect(() => { const fallbackTankId = activeOverviews[0]?.tank.id || ""; setSelectedActiveTankId((previous) => previous && activeOverviews.some((overview) => overview.tank.id === previous) ? previous : fallbackTankId, ); }, [activeOverviews]);
useEffect(() => { const fallbackTankId = recoveredOverviews[0]?.tank.id || ""; setSelectedRecoveredTankId((previous) => previous && recoveredOverviews.some((overview) => overview.tank.id === previous) ? previous : fallbackTankId, ); }, [recoveredOverviews]);
const selectedTemplate = getHealthTemplateByKey( selectedTemplateKey || templates[0]?.key, ); const selectedActiveOverview = activeOverviews.find( (overview) => overview.tank.id === selectedActiveTankId, ) || activeOverviews[0] || null; const selectedRecoveredOverview = recoveredOverviews.find( (overview) => overview.tank.id === selectedRecoveredTankId, ) || recoveredOverviews[0] || null; const selectedActiveRecord = selectedActiveOverview?.latestActiveRecord || selectedActiveOverview?.latestRecord || null; const selectedRecoveredRecord = selectedRecoveredOverview?.latestHealthyRecord || selectedRecoveredOverview?.latestRecord || null; const selectedActiveTemplate = resolveHealthReportTemplate( selectedActiveRecord?.bacterialType, ); const selectedRecoveredTemplate = resolveHealthReportTemplate( selectedRecoveredOverview?.latestActiveRecord?.bacterialType || selectedRecoveredRecord?.bacterialType, ); const selectedTemplateConditionId = getDiseaseConditionId(selectedTemplate); const totalReports = filteredOverviews.reduce( (sum, overview) => sum + overview.healthChecks.length, 0, ); const monitoredBatches = filteredOverviews.reduce( (sum, overview) => sum + overview.batches.length, 0, ); const previewLevel = configLevels[0] || createDefaultRiskLevel(); const previewRecommendations = compactTextList( previewLevel.recommendations || [], ); const adminPreviewRecommendation = isAdmin ? { conditionId: configConditionId, level: previewLevel.level, status: previewLevel.status || "Draft", risk: previewLevel.risk, medicineId: configMedicineId.trim() || undefined, medicineName: configMedicineName.trim() || undefined, summary: configSummary.trim() || selectedTemplate.summary, symptoms: compactTextList(configSymptoms).length ? compactTextList(configSymptoms) : selectedTemplate.symptoms, feedingGuidance: compactTextList(configFeedingGuidance).length ? compactTextList(configFeedingGuidance) : selectedTemplate.feedingGuidance, recoveryChecklist: compactTextList(configRecoveryChecklist).length ? compactTextList(configRecoveryChecklist) : selectedTemplate.recoveryChecklist, preventiveMeasures: compactTextList(configPreventiveMeasures).length ? compactTextList(configPreventiveMeasures) : selectedTemplate.preventiveMeasures, quarantineAdvice: configQuarantineAdvice.trim() || selectedTemplate.quarantineAdvice, recommendations: previewRecommendations, } : null;
const setConfigDetails = ( config?: HealthLibraryConfiguration, template = selectedTemplate, ) => { setConfigMedicineId(String(config?.medicineId || "")); setConfigMedicineName(String(config?.medicineName || "")); setConfigSummary(String(config?.summary || template.summary || "")); setConfigSymptoms(normalizeTextList(config?.symptoms, template.symptoms)); setConfigFeedingGuidance( normalizeTextList(config?.feedingGuidance, template.feedingGuidance), ); setConfigRecoveryChecklist( normalizeTextList(config?.recoveryChecklist, template.recoveryChecklist), ); setConfigPreventiveMeasures( normalizeTextList( config?.preventiveMeasures, template.preventiveMeasures, ), ); setConfigQuarantineAdvice( String(config?.quarantineAdvice || template.quarantineAdvice || ""), ); };
const startNewConfig = () => { setSelectedConfigId(""); setConfigConditionId(selectedTemplateConditionId || DEFAULT_CONDITION_ID); setConfigLevels( normalizeHealthLibraryRiskLevels( undefined, getDefaultRiskLevelsForTemplate(selectedTemplate), ), ); setConfigMedicineId(""); setConfigDetails(undefined, selectedTemplate); };
const selectConfig = (config: HealthLibraryConfiguration) => { setSelectedConfigId(getHealthLibraryConfigId(config)); setConfigConditionId(getHealthLibraryConditionId(config)); setConfigLevels( normalizeHealthLibraryRiskLevels( config.levels, getDefaultRiskLevelsForTemplate(selectedTemplate), ), ); setConfigDetails(config, selectedTemplate); };
const handleConditionSelection = (conditionId: string) => { const existingConfig = libraryConfigs.find( (config) => getHealthLibraryConditionId(config) === conditionId, ); if (existingConfig) { selectConfig(existingConfig); return; }
setSelectedConfigId(""); setConfigConditionId(conditionId); setConfigLevels( normalizeHealthLibraryRiskLevels( undefined, getDefaultRiskLevelsForTemplate(selectedTemplate), ), ); setConfigDetails(undefined, selectedTemplate); };
useEffect(() => { if (isAdmin && selectedTemplateConditionId) { handleConditionSelection(selectedTemplateConditionId); } }, [isAdmin, selectedTemplateConditionId, libraryConfigs]);
const updateLevelField = ( index: number, field: "level" | "status" | "risk", value: string, ) => { setConfigLevels((levels) => levels.map((level, levelIndex) => levelIndex === index ? { ...level, [field]: value } : level, ), ); };
const updateLevelRange = ( index: number, field: "min" | "max", value: string, ) => { const numericValue = Number(value); setConfigLevels((levels) => levels.map((level, levelIndex) => levelIndex === index ? { ...level, range: { ...level.range, [field]: Number.isFinite(numericValue) ? numericValue : 0, }, } : level, ), ); };
const updateRecommendation = ( levelIndex: number, recommendationIndex: number, value: string, ) => { setConfigLevels((levels) => levels.map((level, currentLevelIndex) => currentLevelIndex === levelIndex ? { ...level, recommendations: level.recommendations.map( (recommendation, currentRecommendationIndex) => currentRecommendationIndex === recommendationIndex ? value : recommendation, ), } : level, ), ); };
const addRecommendation = (levelIndex: number) => { setConfigLevels((levels) => levels.map((level, currentLevelIndex) => currentLevelIndex === levelIndex ? { ...level, recommendations: [...level.recommendations, ""] } : level, ), ); };
const removeRecommendation = ( levelIndex: number, recommendationIndex: number, ) => { setConfigLevels((levels) => levels.map((level, currentLevelIndex) => currentLevelIndex === levelIndex ? { ...level, recommendations: level.recommendations.filter( (_, currentRecommendationIndex) => currentRecommendationIndex !== recommendationIndex, ), } : level, ), ); };
const addRiskLevel = () => { setConfigLevels((levels) => [...levels, createDefaultRiskLevel()]); };
const removeRiskLevel = (index: number) => { setConfigLevels((levels) => levels.filter((_, levelIndex) => levelIndex !== index), ); };
const updateListItem = ( setter: React.Dispatch<React.SetStateAction<string[]>>, index: number, value: string, ) => { setter((items) => items.map((item, itemIndex) => (itemIndex === index ? value : item)), ); };
const addListItem = ( setter: React.Dispatch<React.SetStateAction<string[]>>, ) => { setter((items) => [...items, ""]); };
const removeListItem = ( setter: React.Dispatch<React.SetStateAction<string[]>>, index: number, ) => { setter((items) => items.length === 1 ? items : items.filter((_, itemIndex) => itemIndex !== index), ); };
const handleSaveConfig = async () => { setSavingConfig(true); try { const payload: HealthLibraryConfiguration = { condition_id: configConditionId.trim(), conditionId: configConditionId.trim(), condition: configConditionId.trim(), name: selectedTemplate.title, description: `AI health library configuration for ${selectedTemplate.title}`, diseaseKey: selectedTemplate.key, medicineId: configMedicineId.trim() || undefined, medicineName: configMedicineName.trim() || undefined, summary: configSummary.trim(), symptoms: compactTextList(configSymptoms), feedingGuidance: compactTextList(configFeedingGuidance), recoveryChecklist: compactTextList(configRecoveryChecklist), preventiveMeasures: compactTextList(configPreventiveMeasures), quarantineAdvice: configQuarantineAdvice.trim(), levels: configLevels.map((level) => ({ level: level.level.trim(), range: { min: Number(level.range.min), max: Number(level.range.max), }, status: level.status.trim(), risk: level.risk.trim(), recommendations: level.recommendations .map((item) => item.trim()) .filter(Boolean), })), };
if (!payload.condition_id) { throw new Error("condition_id is required."); }
if (!payload.levels?.length) { throw new Error("At least one risk level is required."); }
const invalidLevel = payload.levels.find( (level) => !level.level || !level.status || !Number.isFinite(level.range.min) || !Number.isFinite(level.range.max) || level.range.min > level.range.max, );
if (invalidLevel) { throw new Error( "Each level needs a name, status, valid min, and valid max.", ); }
let savedConfig: HealthLibraryConfiguration; if (selectedConfigId) { savedConfig = await updateHealthLibraryConfiguration( selectedConfigId, payload, ); toast.success("Update health library"); } else { savedConfig = await createHealthLibraryConfiguration(payload); toast.success( savedConfig.savedLocally ? "health library created" : "Health library configuration created.", ); }
const savedId = getHealthLibraryConfigId(savedConfig); if (savedId) setSelectedConfigId(savedId); await loadHealthLibraryConfigs(payload.condition_id); } catch (error) { toast.error(`Failed to save configuration: ${(error as Error).message}`); } finally { setSavingConfig(false); } };
const handleDeleteConfig = async () => { if (!selectedConfigId) return; setSavingConfig(true); try { await deleteHealthLibraryConfiguration(selectedConfigId); toast.success("Health library configuration deleted."); startNewConfig(); await loadHealthLibraryConfigs( selectedTemplateConditionId || DEFAULT_CONDITION_ID, ); } catch (error) { toast.error( `Failed to delete configuration: ${(error as Error).message}`, ); } finally { setSavingConfig(false); } };
return ( <div className="space-y-5 p-6"> <div className="rounded-lg border border-[#B9E0E7] bg-[#F4FBFC] p-5"> <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between"> <div> <div className="mb-2 inline-flex items-center gap-2 rounded-lg border border-[#B9E0E7] bg-white px-3 py-1 text-xs font-semibold text-[#0A4D68]"> <Book className="h-3.5 w-3.5" /> Health Library </div> <h1 className="text-2xl font-semibold text-slate-950"> Health protocol workspace </h1> <p className="mt-1 max-w-3xl text-sm text-slate-600"> Manage disease rules, AI confidence ranges, medicine guidance, active cases, and recovered tanks from one clear workflow. </p> </div> <Button variant="outline" className="bg-white" onClick={() => void loadHealthData()} disabled={loading} > <RefreshCw className={`mr-2 h-4 w-4 ${loading ? "animate-spin" : ""}`} /> Refresh Data </Button> </div> </div>
<div className="grid grid-cols-1 gap-3 md:grid-cols-4"> <Card className="border-slate-200 shadow-sm"> <CardHeader className="flex flex-row items-center justify-between pb-2"> <CardTitle className="text-sm">Active Cases</CardTitle> <AlertTriangle className="h-4 w-4 text-rose-600" /> </CardHeader> <CardContent> <div className="text-2xl font-bold">{activeOverviews.length}</div> <p className="mt-1 text-xs text-gray-600">Tanks needing action</p> </CardContent> </Card> <Card className="border-slate-200 shadow-sm"> <CardHeader className="flex flex-row items-center justify-between pb-2"> <CardTitle className="text-sm">Recovered Tanks</CardTitle> <CheckCircle2 className="h-4 w-4 text-emerald-600" /> </CardHeader> <CardContent> <div className="text-2xl font-bold"> {recoveredOverviews.length} </div> <p className="mt-1 text-xs text-gray-600">Treatment completed</p> </CardContent> </Card> <Card className="border-slate-200 shadow-sm"> <CardHeader className="flex flex-row items-center justify-between pb-2"> <CardTitle className="text-sm">Saved Reports</CardTitle> <Stethoscope className="h-4 w-4 text-[#088395]" /> </CardHeader> <CardContent> <div className="text-2xl font-bold">{totalReports}</div> <p className="mt-1 text-xs text-gray-600">Across monitored tanks</p> </CardContent> </Card> <Card className="border-slate-200 shadow-sm"> <CardHeader className="flex flex-row items-center justify-between pb-2"> <CardTitle className="text-sm">Monitored Batches</CardTitle> <Heart className="h-4 w-4 text-violet-600" /> </CardHeader> <CardContent> <div className="text-2xl font-bold">{monitoredBatches}</div> <p className="mt-1 text-xs text-gray-600"> With tank health context </p> </CardContent> </Card> </div>
<Tabs defaultValue="library" className="space-y-4"> <TabsList className="grid h-auto w-full grid-cols-3 gap-1 rounded-lg border border-slate-200 bg-white p-1 lg:w-auto"> <TabsTrigger value="library"> <Book className="mr-2 h-4 w-4" /> Disease Library </TabsTrigger> <TabsTrigger value="active"> <AlertTriangle className="mr-2 h-4 w-4" /> Active Cases </TabsTrigger> <TabsTrigger value="recovered"> <ShieldCheck className="mr-2 h-4 w-4" /> Recovered Tanks </TabsTrigger> </TabsList>
<TabsContent value="library" className="space-y-4"> <Card className="border-slate-200 shadow-sm"> <CardHeader className="border-b border-slate-200"> <div className="flex flex-col gap-4 lg:flex-row lg:items-center lg:justify-between"> <div> <CardTitle className="text-lg"> Disease rules and AI levels </CardTitle> <p className="mt-1 text-sm text-slate-500"> Choose a disease, review the fixed protocol, then tune the exact Health Library rules used by AI reports. </p> </div> <div className="relative w-full max-w-xl"> <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" /> <Input placeholder="Search disease name, alias, or symptom..." value={searchQuery} onChange={(event) => setSearchQuery(event.target.value)} className="h-11 bg-white pl-10" /> </div> </div> </CardHeader> <CardContent className="p-4"> <div className="grid gap-4 lg:grid-cols-[340px_1fr]"> <div className="space-y-3 rounded-lg border border-slate-200 bg-slate-50 p-3"> <div className="flex items-center justify-between gap-3 px-1"> <div> <p className="text-sm font-semibold text-slate-900"> Disease protocols </p> <p className="text-xs text-slate-500"> {filteredTemplates.length} available protocols </p> </div> <Layers3 className="h-4 w-4 text-[#088395]" /> </div> {filteredTemplates.map((template) => ( <button key={template.key} onClick={() => setSelectedTemplateKey(template.key)} className={`w-full rounded-lg border p-3 text-left transition-colors ${ selectedTemplateKey === template.key ? "border-[#088395] bg-white shadow-sm" : "border-transparent bg-white/70 hover:border-slate-200" }`} > <div className="flex items-start justify-between gap-3"> <div className="min-w-0"> <p className="truncate font-semibold text-slate-900"> {template.title} </p> <p className="mt-1 text-xs text-slate-500"> {template.symptoms.length} key signs </p> </div> <Badge variant="outline" className={getHealthStatusColor( template.defaultHealthStatus, )} > {formatHealthStatus(template.defaultHealthStatus)} </Badge> </div> <p className="mt-2 line-clamp-2 text-xs leading-5 text-slate-500"> {template.summary} </p> </button> ))} </div> <div className="min-w-0 space-y-4"> <RobotHealthReport template={selectedTemplate} healthStatus={selectedTemplate.defaultHealthStatus} title="Fixed Health Protocol" compact={false} libraryRecommendation={adminPreviewRecommendation} requireLibraryRecommendation={isAdmin} />
{isAdmin && ( <Card className="border-[#B9E0E7] bg-white"> <CardHeader className="flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between"> <div> <CardTitle className="text-lg"> Level Controls for {selectedTemplate.title} </CardTitle> <p className="mt-1 text-sm text-slate-500"> These are the exact ranges and recommendations used after AI analysis detects this disease. </p> <p className="mt-2 text-xs text-slate-500"> Condition key:{" "} <span className="font-mono text-slate-700"> {configConditionId} </span> </p> </div> <div className="flex flex-wrap gap-2"> <Button variant="outline" onClick={() => void loadHealthLibraryConfigs( selectedTemplateConditionId, ) } disabled={loadingConfigs} > <RefreshCw className={`mr-2 h-4 w-4 ${loadingConfigs ? "animate-spin" : ""}`} /> Refresh </Button> <Button variant="outline" onClick={startNewConfig}> Reset Defaults </Button> <Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={handleSaveConfig} disabled={savingConfig} > <Save className="mr-2 h-4 w-4" /> {savingConfig ? "Saving..." : selectedConfigId ? "Update Levels" : "Save Levels"} </Button> <Button variant="outline" onClick={handleDeleteConfig} disabled={!selectedConfigId || savingConfig} className="text-rose-700 hover:text-rose-800" > <Trash2 className="mr-2 h-4 w-4" /> Delete </Button> </div> </CardHeader> <CardContent className="space-y-4"> <div className="rounded-lg border border-[#D7E9EE] bg-[#F7FCFD] p-4"> <p className="text-sm font-semibold text-slate-900"> Report content controlled by admin </p> <p className="mt-1 text-xs text-slate-500"> These fields replace the fixed protocol text in the AI report for this disease. </p> <div className="mt-4 grid gap-3 md:grid-cols-2"> <div className="space-y-2"> <label className="text-xs font-semibold text-slate-600" htmlFor="library-medicine-name" > Medicine </label> <select id="library-medicine-name" value={configMedicineId} onChange={(event) => { const selectedId = event.target.value; setConfigMedicineId(selectedId); const selected = medicineOptions.find( (m) => m.id === selectedId, ); setConfigMedicineName( selected ? selected.name : "", ); }} className="flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50" > <option value="">-- اختر الدواء --</option> {medicineOptions.map((med) => ( <option key={med.id} value={med.id}> {med.name} </option> ))} </select> </div> <div className="space-y-2 md:col-span-2"> <label className="text-xs font-semibold text-slate-600" htmlFor="library-summary" > Diagnosis summary </label> <Input id="library-summary" value={configSummary} onChange={(event) => setConfigSummary(event.target.value) } placeholder="اكتب ملخص التشخيص" /> </div> <div className="space-y-2 md:col-span-2"> <label className="text-xs font-semibold text-slate-600" htmlFor="library-quarantine" > Prevention and quarantine note </label> <Input id="library-quarantine" value={configQuarantineAdvice} onChange={(event) => setConfigQuarantineAdvice(event.target.value) } placeholder="اكتب ملاحظات الوقاية أو العزل" /> </div> </div> </div>
{[ { title: "Observed signs", items: configSymptoms, setter: setConfigSymptoms, placeholder: "اكتب علامة مرضية", }, { title: "Feeding guidance", items: configFeedingGuidance, setter: setConfigFeedingGuidance, placeholder: "اكتب إرشاد التغذية", }, { title: "Recovery checklist", items: configRecoveryChecklist, setter: setConfigRecoveryChecklist, placeholder: "اكتب شرط التعافي", }, { title: "Preventive measures", items: configPreventiveMeasures, setter: setConfigPreventiveMeasures, placeholder: "اكتب إجراء وقائي", }, ].map((section) => ( <div key={section.title} className="rounded-lg border border-slate-200 bg-white p-4" > <div className="mb-3 flex items-center justify-between gap-3"> <p className="text-sm font-semibold text-slate-900"> {section.title} </p> <Button variant="outline" size="sm" onClick={() => addListItem(section.setter)} > <Plus className="mr-2 h-3.5 w-3.5" /> Add </Button> </div> <div className="space-y-2"> {section.items.map((item, itemIndex) => ( <div key={`${section.title}-${itemIndex}`} className="flex gap-2" > <Input value={item} onChange={(event) => updateListItem( section.setter, itemIndex, event.target.value, ) } placeholder={section.placeholder} /> <Button variant="outline" onClick={() => removeListItem(section.setter, itemIndex) } disabled={section.items.length === 1} className="shrink-0 text-rose-700 hover:text-rose-800" > <Trash2 className="h-4 w-4" /> </Button> </div> ))} </div> </div> ))}
<div className="flex flex-col gap-3 rounded-lg border border-[#D7E9EE] bg-[#F7FCFD] p-4 md:flex-row md:items-center md:justify-between"> <div> <p className="text-sm font-semibold text-slate-900"> Disease percentage levels </p> <p className="mt-1 text-xs text-slate-500"> The AI confidence percentage is matched with these ranges. The matching recommendation is shown in the AI report. </p> </div> <Button variant="outline" onClick={addRiskLevel}> <Plus className="mr-2 h-4 w-4" /> Add Level </Button> </div>
<div className="space-y-4"> {configLevels.map((level, levelIndex) => ( <div key={`disease-level-${levelIndex}`} className="rounded-lg border border-slate-200 bg-slate-50 p-4" > <div className="mb-4 flex flex-col gap-3 md:flex-row md:items-center md:justify-between"> <div> <p className="text-sm font-semibold text-slate-900"> Level {levelIndex + 1} </p> <p className="text-xs text-slate-500"> This is one disease-library level used directly after AI analysis. </p> </div> <Button variant="outline" onClick={() => removeRiskLevel(levelIndex)} disabled={configLevels.length === 1} className="text-rose-700 hover:text-rose-800" > <Trash2 className="mr-2 h-4 w-4" /> Remove Level </Button> </div>
<div className="grid gap-3 md:grid-cols-2 xl:grid-cols-5"> <div className="space-y-2"> <label className="text-xs font-semibold text-slate-600" htmlFor={`library-level-${levelIndex}`} > Level key </label> <Input id={`library-level-${levelIndex}`} value={level.level} onChange={(event) => updateLevelField( levelIndex, "level", event.target.value, ) } placeholder="low" /> </div> <div className="space-y-2"> <label className="text-xs font-semibold text-slate-600" htmlFor={`library-min-${levelIndex}`} > Min % </label> <Input id={`library-min-${levelIndex}`} type="number" min={0} max={100} value={level.range.min} onChange={(event) => updateLevelRange( levelIndex, "min", event.target.value, ) } /> </div> <div className="space-y-2"> <label className="text-xs font-semibold text-slate-600" htmlFor={`library-max-${levelIndex}`} > Max % </label> <Input id={`library-max-${levelIndex}`} type="number" min={0} max={100} value={level.range.max} onChange={(event) => updateLevelRange( levelIndex, "max", event.target.value, ) } /> </div> <div className="space-y-2"> <label className="text-xs font-semibold text-slate-600" htmlFor={`library-status-${levelIndex}`} > Status </label> <Input id={`library-status-${levelIndex}`} value={level.status} onChange={(event) => updateLevelField( levelIndex, "status", event.target.value, ) } placeholder="آمن" /> </div> <div className="space-y-2"> <label className="text-xs font-semibold text-slate-600" htmlFor={`library-risk-${levelIndex}`} > Risk </label> <Input id={`library-risk-${levelIndex}`} value={level.risk} onChange={(event) => updateLevelField( levelIndex, "risk", event.target.value, ) } placeholder="لا يوجد خطر واضح" /> </div> </div>
<div className="mt-4 space-y-2"> <div className="flex items-center justify-between gap-3"> <p className="text-xs font-semibold text-slate-600"> Recommendations shown after AI analysis </p> <Button variant="outline" size="sm" onClick={() => addRecommendation(levelIndex) } > <Plus className="mr-2 h-3.5 w-3.5" /> Add Recommendation </Button> </div> <div className="space-y-2"> {level.recommendations.map( (recommendation, recommendationIndex) => ( <div key={`${levelIndex}-${recommendationIndex}`} className="flex gap-2" > <Input value={recommendation} onChange={(event) => updateRecommendation( levelIndex, recommendationIndex, event.target.value, ) } placeholder="اكتب التوصية هنا" /> <Button variant="outline" onClick={() => removeRecommendation( levelIndex, recommendationIndex, ) } disabled={ level.recommendations.length === 1 } className="shrink-0 text-rose-700 hover:text-rose-800" > <Trash2 className="h-4 w-4" /> </Button> </div> ), )} </div> </div> </div> ))} </div> </CardContent> </Card> )} </div> </div> </CardContent> </Card> </TabsContent>
<TabsContent value="active" className="space-y-4"> <Card> <CardContent className="p-4"> {activeOverviews.length === 0 ? ( <div className="flex min-h-[280px] items-center justify-center rounded-lg border border-dashed border-slate-300 bg-slate-50 text-sm text-slate-500"> No active health alerts right now. </div> ) : ( <div className="grid gap-4 lg:grid-cols-[320px_1fr]"> <div className="space-y-2 rounded-lg border border-slate-200 bg-slate-50 p-3"> {activeOverviews.map((overview) => ( <button key={overview.tank.id} onClick={() => setSelectedActiveTankId(overview.tank.id) } className={`w-full rounded-lg border p-3 text-left transition-colors ${ selectedActiveOverview?.tank.id === overview.tank.id ? "border-[#088395] bg-white shadow-sm" : "border-transparent bg-white/70 hover:border-slate-200" }`} > <div className="flex items-center justify-between gap-3"> <div> <p className="font-semibold text-slate-900"> {overview.tank.name} </p> <p className="mt-1 text-xs text-slate-500"> {overview.currentDiseaseLabel} </p> </div> {overview.latestRecord && ( <Badge variant="outline" className={getHealthStatusColor( overview.latestRecord.healthStatus, )} > {formatHealthStatus( overview.latestRecord.healthStatus, )} </Badge> )} </div> <p className="mt-2 text-xs text-slate-500"> { overview.batchOverviews.filter( (batch) => batch.requiresAttention, ).length }{" "} affected batch {overview.batchOverviews.filter( (batch) => batch.requiresAttention, ).length === 1 ? "" : "es"} </p> </button> ))} </div>
{selectedActiveOverview && selectedActiveRecord ? ( <div className="space-y-4"> <Card> <CardHeader> <CardTitle className="text-lg"> {selectedActiveOverview.tank.name} </CardTitle> <p className="text-sm text-slate-500"> Latest alert on{" "} {formatDate(selectedActiveRecord.checkedAt)} </p> </CardHeader> <CardContent className="grid gap-4 md:grid-cols-3"> <div className="rounded-lg border border-slate-200 bg-slate-50 p-4"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500"> Latest disease </p> <p className="mt-2 text-sm font-semibold text-slate-900"> {selectedActiveRecord.bacterialType} </p> </div> <div className="rounded-lg border border-slate-200 bg-slate-50 p-4"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500"> Affected batches </p> <p className="mt-2 text-sm font-semibold text-slate-900"> {selectedActiveOverview.batchOverviews .filter((batch) => batch.requiresAttention) .map((batch) => getBatchLabel(batch.batch)) .join(", ") || "N/A"} </p> </div> <div className="rounded-lg border border-slate-200 bg-slate-50 p-4"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500"> Saved reports </p> <p className="mt-2 text-sm font-semibold text-slate-900"> {selectedActiveOverview.healthChecks.length} </p> </div> </CardContent> </Card>
<RobotHealthReport template={selectedActiveTemplate} healthStatus={selectedActiveRecord.healthStatus} confidencePercent={ selectedActiveRecord.bacterialLoadPercentage ?? null } checkedAt={selectedActiveRecord.checkedAt} batchLabel={getBatchLabel( selectedActiveOverview.batchOverviews.find( (batch) => batch.latestRecord?.id === selectedActiveRecord.id, )?.batch, )} topPredictionLabel={selectedActiveRecord.bacterialType} title="Current Tank Health Alert" /> </div> ) : null} </div> )} </CardContent> </Card> </TabsContent>
<TabsContent value="recovered" className="space-y-4"> <Card> <CardContent className="p-4"> {recoveredOverviews.length === 0 ? ( <div className="flex min-h-[280px] items-center justify-center rounded-lg border border-dashed border-slate-300 bg-slate-50 text-sm text-slate-500"> No recovered tanks recorded yet. </div> ) : ( <div className="grid gap-4 lg:grid-cols-[320px_1fr]"> <div className="space-y-2 rounded-lg border border-slate-200 bg-slate-50 p-3"> {recoveredOverviews.map((overview) => ( <button key={overview.tank.id} onClick={() => setSelectedRecoveredTankId(overview.tank.id) } className={`w-full rounded-lg border p-3 text-left transition-colors ${ selectedRecoveredOverview?.tank.id === overview.tank.id ? "border-emerald-500 bg-white shadow-sm" : "border-transparent bg-white/70 hover:border-slate-200" }`} > <div className="flex items-center justify-between gap-3"> <div> <p className="font-semibold text-slate-900"> {overview.tank.name} </p> <p className="mt-1 text-xs text-slate-500"> Recovered from{" "} {overview.latestActiveRecord?.bacterialType || overview.currentDiseaseLabel} </p> </div> <Badge className="bg-emerald-100 text-emerald-700"> Recovered </Badge> </div> <p className="mt-2 text-xs text-slate-500"> {formatDate(overview.recoveredAt)} </p> </button> ))} </div>
{selectedRecoveredOverview && selectedRecoveredRecord ? ( <div className="space-y-4"> <Card> <CardHeader> <CardTitle className="text-lg"> Recovered Tank Record </CardTitle> </CardHeader> <CardContent className="grid gap-4 md:grid-cols-3"> <div className="rounded-lg border border-slate-200 bg-slate-50 p-4"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500"> Tank </p> <p className="mt-2 text-sm font-semibold text-slate-900"> {selectedRecoveredOverview.tank.name} </p> </div> <div className="rounded-lg border border-slate-200 bg-slate-50 p-4"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500"> Recovered from </p> <p className="mt-2 text-sm font-semibold text-slate-900"> {selectedRecoveredOverview.latestActiveRecord ?.bacterialType || selectedRecoveredOverview.currentDiseaseLabel} </p> </div> <div className="rounded-lg border border-slate-200 bg-slate-50 p-4"> <p className="text-xs font-semibold uppercase tracking-wide text-slate-500"> Recovery date </p> <p className="mt-2 text-sm font-semibold text-slate-900"> {formatDate( selectedRecoveredOverview.recoveredAt, )} </p> </div> </CardContent> </Card>
<RobotHealthReport template={selectedRecoveredTemplate} healthStatus={selectedRecoveredRecord.healthStatus} confidencePercent={ selectedRecoveredRecord.bacterialLoadPercentage ?? null } checkedAt={selectedRecoveredRecord.checkedAt} batchLabel={getBatchLabel( selectedRecoveredOverview.batchOverviews.find( (batch) => batch.latestRecord?.id === selectedRecoveredRecord.id, )?.batch, )} topPredictionLabel={ selectedRecoveredOverview.latestActiveRecord ?.bacterialType || selectedRecoveredRecord.bacterialType } title="Recovered Tank Report" /> </div> ) : null} </div> )} </CardContent> </Card> </TabsContent> </Tabs> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562import { 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<FishInventoryBatch[]>([]);
// Allocation modal const [selectedBatch, setSelectedBatch] = useState<FishInventoryBatch | null>( null, ); const [showAllocateModal, setShowAllocateModal] = useState(false);
// Feed inventory - API-driven const [feedInventory, setFeedInventory] = useState<FeedItem[]>([]); const [medicineInventory, setMedicineInventory] = useState< MedicineInventoryBatch[] >([]); const [medicineTotals, setMedicineTotals] = useState<MedicineTotalItem[]>([]);
// Tanks for allocation const [tanks, setTanks] = useState<any[]>([]); const [isTanksLoading, setIsTanksLoading] = useState(false);
// Food Types + Add Resources const [foodTypes, setFoodTypes] = useState<any[]>([]); const [medicineTypes, setMedicineTypes] = useState<MedicineTypeItem[]>([]); 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<any>(null); const [selectedMedicineBatch, setSelectedMedicineBatch] = useState<MedicineInventoryBatch | null>(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<MedicineInventoryBatch[]> => { 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<any>("/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<any>("/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<any>("/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<unknown>): 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<string> => { 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<string, unknown>; 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<string, unknown> => { const payload: Record<string, unknown> = { 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 ( <Badge className="bg-green-100 text-green-800" variant="outline"> <CheckCircle className="w-3 h-3 mr-1" /> Ready to Stock </Badge> ); case "QUARANTINE": return ( <Badge className="bg-yellow-100 text-yellow-800" variant="outline"> <Clock className="w-3 h-3 mr-1" /> Quarantine </Badge> ); case "DEPLETED": return ( <Badge className="bg-gray-100 text-gray-800" variant="outline"> <XCircle className="w-3 h-3 mr-1" /> Depleted </Badge> ); case "IN_STOCK": return ( <Badge className="bg-blue-100 text-blue-800" variant="outline"> <Package className="w-3 h-3 mr-1" /> In Stock </Badge> ); case "AVAILABLE": return ( <Badge className="bg-blue-100 text-blue-800" variant="outline"> <Package className="w-3 h-3 mr-1" /> Available </Badge> ); default: return <Badge variant="outline">{normalized || "UNKNOWN"}</Badge>; } };
const getHealthCheckBadge = (status: string) => { switch (status) { case "PASSED": return ( <Badge className="bg-green-100 text-green-800" variant="outline"> <CheckCircle className="w-3 h-3 mr-1" /> Passed </Badge> ); case "PENDING": return ( <Badge className="bg-yellow-100 text-yellow-800" variant="outline"> <Clock className="w-3 h-3 mr-1" /> Pending </Badge> ); case "FAILED": return ( <Badge className="bg-red-100 text-red-800" variant="outline"> <XCircle className="w-3 h-3 mr-1" /> Failed </Badge> ); default: return <Badge variant="outline">{status}</Badge>; } };
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 ( <Badge variant="outline" className="bg-red-100 text-red-800 border-red-200" > Critical </Badge> ); } if (status === "low") { return ( <Badge variant="outline" className="bg-orange-100 text-orange-800 border-orange-200" > Low </Badge> ); } return ( <Badge variant="outline" className="bg-green-100 text-green-800 border-green-200" > Healthy </Badge> ); };
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 | null>, ): ComboboxItem[] => { const seen = new Set<string>(); 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 ( <> {" "} <div className="bg-[#0A4D68] px-6 py-4 text-white"> <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> <Droplet className="h-6 w-6" /> <span className="text-xl font-semibold">Inventory Management</span> </div> <div className="flex items-center gap-4"> <span className="text-sm">{currentFarm?.name}</span> <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#088395] font-semibold"> {user.name .split(" ") .map((segment) => segment[0]) .join("") .toUpperCase()} </div> </div> </div> </div> <div className="p-6 space-y-6"> <div className="flex items-center justify-between"> <div> <p className="mt-1 text-md text-black-600"> Track and manage your stock levels </p> </div>
{isWarehouse && ( <Button onClick={() => setIsAddResourcesOpen(true)} className="bg-[#088395] hover:bg-[#0A4D68]" > <Plus className="mr-2 h-4 w-4" /> Add Resources </Button> )} </div>
{/* Main Tabs */} <Tabs defaultValue="fish-stock" className="w-full"> <TabsList className="grid w-full grid-cols-5"> <TabsTrigger value="fish-stock"> <Fish className="w-4 h-4 mr-2" /> Fish Stock </TabsTrigger> <TabsTrigger value="allocate"> <Plus className="w-4 h-4 mr-2" /> Allocate to Tank </TabsTrigger> <TabsTrigger value="feed-stock"> <Package className="w-4 h-4 mr-2" /> Feed Stock </TabsTrigger> <TabsTrigger value="harvested-fish"> <Fish className="w-4 h-4 mr-2" /> Harvested Fish </TabsTrigger> <TabsTrigger value="medicine"> <Pill className="w-4 h-4 mr-2" /> Medicine </TabsTrigger> </TabsList>
{/* Fish Stock Tab */} <TabsContent value="fish-stock" className="mt-4"> <Card> <CardHeader className="flex flex-row items-center justify-between"> <div> <CardTitle>Fish Inventory Batches</CardTitle> <p className="text-sm text-gray-600 mt-1"> Manage fish from purchase orders to tank stocking </p> </div> <Button size="icon" variant="ghost" className="text-gray-400 hover:text-[#0A4D68]" onClick={loadBatches} > <RefreshCw className="w-4 h-4" /> </Button> </CardHeader> <CardContent> <div className="overflow-x-auto"> <table className="w-full text-sm text-left border-collapse"> <thead className="bg-[#f8fafc] text-[#64748b] font-bold uppercase text-[10px] tracking-widest border-b border-[#e2e8f0]"> <tr> <th className="px-4 py-4">Batch Identity</th> <th className="px-4 py-4">Status</th> <th className="px-4 py-4">Quantity</th> </tr> </thead> <tbody className="divide-y divide-[#f1f5f9]"> {fishStockBatches.map((batch) => ( <tr key={batch.id} className="hover:bg-[#f8fafc] transition-colors group" > <td className="px-4 py-4"> <div className="flex items-center gap-3"> <div className="bg-blue-50 p-2 rounded-lg group-hover:bg-blue-100 transition-colors"> <Fish className="w-4 h-4 text-[#0A4D68]" /> </div> <div> <div className="font-bold text-gray-900"> {batch.fishTypeName || batch.species || "Unknown Batch"} </div> <div className="text-[10px] text-gray-400 font-mono"> ID: {batch.id?.split("-")[0] ?? batch.id} </div> {batch.purchaseOrderId && ( <div className="text-[10px] text-gray-500 mt-1"> PO: {batch.purchaseOrderId.substring(0, 8)} ... </div> )} </div> </div> </td> <td className="px-4 py-4"> {getStatusBadge(batch.status)} </td> <td className="px-4 py-4"> <div className="space-y-1"> <div className="font-bold text-gray-900"> {(batch.quantity ?? 0).toLocaleString()} fish </div> <div className="text-[10px] text-gray-500"> of{" "} {(batch.initialQuantity ?? 0).toLocaleString()}{" "} stocked </div> <Progress value={ ((batch.quantity ?? 0) / (batch.initialQuantity || 1)) * 100 } className="h-1 w-24 [&>div]:bg-[#0A4D68]" /> </div> </td> </tr> ))} </tbody> </table> </div>
{fishStockBatches.length === 0 && ( <div className="text-center py-12"> <Fish className="w-12 h-12 text-gray-400 mx-auto mb-3" /> <p className="text-gray-600">No fish inventory found</p> <p className="text-sm text-gray-500 mt-1"> Purchase orders will appear here </p> </div> )} </CardContent> </Card> </TabsContent>
{/* Allocate to Tank Tab */} <TabsContent value="allocate" className="mt-4"> <Card> <CardHeader className="flex flex-row items-center justify-between"> <div> <CardTitle>Allocate Fish to Tank</CardTitle> <p className="text-sm text-gray-600 mt-1"> Choose any ready batch and allocate it directly to a tank </p> </div> <Button size="icon" variant="ghost" className="text-gray-400 hover:text-[#0A4D68]" onClick={loadBatches} > <RefreshCw className="w-4 h-4" /> </Button> </CardHeader> <CardContent className="space-y-3"> {readyToAllocateBatches.length === 0 && ( <div className="text-center py-10 border border-dashed rounded-lg bg-gray-50"> <Fish className="w-10 h-10 text-gray-400 mx-auto mb-2" /> <p className="text-sm text-gray-600"> No batches are ready to stock right now. </p> </div> )}
{readyToAllocateBatches.map((batch) => ( <div key={batch.id} className="flex flex-col gap-3 rounded-lg border p-4 md:flex-row md:items-center md:justify-between" > <div> <p className="font-semibold text-[#0A4D68]"> {batch.fishTypeName || batch.species || "Fish Batch"} </p> <p className="text-xs text-gray-500 mt-1"> Batch ID: {batch.id?.split("-")[0] ?? batch.id} </p> <div className="mt-2 flex flex-wrap gap-2 text-xs text-gray-600"> <span> Qty:{" "} <span className="font-medium"> {(batch.quantity ?? 0).toLocaleString()} fish </span> </span> </div> </div> <div className="flex items-center gap-2"> {getStatusBadge(batch.status)} {isTechnican && ( <Button className="bg-[#0A4D68] hover:bg-[#083d52]" onClick={() => { setSelectedBatch(batch); setShowAllocateModal(true); }} > <Plus className="w-4 h-4 mr-2" /> Allocate to Tank </Button> )} </div> </div> ))} </CardContent> </Card> </TabsContent>
{/* Feed Stock Tab */} <TabsContent value="feed-stock" className="mt-4"> {/* Summary Cards */} <div className="grid grid-cols-1 md:grid-cols-4 gap-4 mb-6"> <Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Feed Batches</CardTitle> </CardHeader> <CardContent> <div className="text-2xl font-bold"> {feedStockInventory.length} </div> <p className="text-xs text-gray-600 mt-1"> Feed records in inventory </p> </CardContent> </Card> <Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Low Stock</CardTitle> </CardHeader> <CardContent> <div className="text-2xl text-orange-600 font-bold"> {lowFeedStockCount} </div> <p className="text-xs text-gray-600 mt-1">Need reordering</p> </CardContent> </Card>
<Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Expiring Soon</CardTitle> </CardHeader> <CardContent> <div className="text-2xl text-red-600 font-bold"> { expiringItems.filter((i: any) => { const days = getDaysUntilExpiry(i.expiryDate); return days !== null && days <= 30; }).length } </div> <p className="text-xs text-gray-600 mt-1">Within 30 days</p> </CardContent> </Card> </div>
{/* Search and Filter */} <Card> <CardHeader> <div className="flex flex-col md:flex-row gap-4 items-center justify-between"> <div className="flex-1 relative w-full md:w-auto"> <Search className="absolute left-3 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" /> <Input placeholder="Search feed stock..." value={searchQuery} onChange={(e) => setSearchQuery(e.target.value)} className="pl-10 h-9" /> </div> <div className="flex flex-wrap items-center gap-2 w-full md:w-auto"> <Button variant="outline" size="icon" className="h-9 w-9 text-gray-400 hover:text-[#0A4D68]" onClick={() => { loadFeed(); loadFoodTypes(); }} > <RefreshCw className="w-4 h-4" /> </Button> </div> </div> </CardHeader> <CardContent> <div className="space-y-3"> {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 ( <div key={item.id} className="p-4 border rounded-lg hover:bg-gray-50 transition-all group" > <div className="flex items-start justify-between mb-3"> <div className="flex items-start gap-3 flex-1"> <div className="bg-gray-100 p-2 rounded-lg"> <Icon className="w-5 h-5 text-gray-600" /> </div> <div className="flex-1 min-w-0"> <div className="flex items-center gap-2 mb-1"> <div className="flex items-center gap-2"> <p className="font-semibold text-[#0A4D68]"> {itemName} </p> {stockWarning && ( <Badge className={stockWarning.className}> {stockWarning.text} </Badge> )} {expiryWarning && ( <Badge className={expiryWarning.className}> {expiryWarning.text} </Badge> )} </div> </div> <p className="text-xs text-gray-600"> {item.supplier ? `Supplier: ${item.supplier}` : "Stock available in storage"} </p> <p className="text-xs text-gray-700 mt-1"> Stock level:{" "} <span className="font-semibold"> {quantity.toLocaleString()} {item.unit} </span> </p> {reorderLevel > 0 && ( <p className="text-xs text-gray-600"> Reorder level: {reorderLevel.toLocaleString()}{" "} {item.unit} </p> )} <Progress value={stockLevelPercent} className={stockProgressClass} /> {item.expiryDate && ( <p className={`text-xs mt-1 ${ daysUntilExpiry && daysUntilExpiry <= 30 ? "text-red-600" : daysUntilExpiry && daysUntilExpiry <= 90 ? "text-orange-600" : "text-gray-600" }`} > Expires:{" "} {new Date( item.expiryDate, ).toLocaleDateString()} </p> )} </div> </div> <div className="text-right flex flex-col items-end gap-2 text-right"> {isWarehouse && ( <Button size="icon" variant="ghost" className="w-7 h-7 text-red-400 hover:text-red-600 hover:bg-red-50 opacity-0 group-hover:opacity-100 transition-opacity" onClick={(e: React.MouseEvent) => { e.stopPropagation(); handleDeleteFeed(item.id, item.name); }} > <Trash2 className="w-4 h-4" /> </Button> )} </div> </div> </div> ); })} </div>
{finalFilteredInventory.length === 0 && ( <div className="text-center py-12"> <Package className="w-12 h-12 text-gray-400 mx-auto mb-3" /> <p className="text-gray-600">No feed stock found</p> <p className="text-sm text-gray-500 mt-1"> Try adjusting your search or add a new feed resource </p> </div> )} </CardContent> </Card> </TabsContent>
<TabsContent value="harvested-fish" className="mt-4"> <HarvestedInventoryView user={user} selectedFarm={selectedFarm} /> </TabsContent>
<TabsContent value="medicine" className="mt-4 space-y-4"> <div className="grid grid-cols-1 md:grid-cols-4 gap-4"> <Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Medicine Batches</CardTitle> </CardHeader> <CardContent> <div className="text-2xl font-bold"> {medicineInventory.length} </div> <p className="text-xs text-gray-600 mt-1"> Active inventory rows </p> </CardContent> </Card>
<Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Total Quantity</CardTitle> </CardHeader> <CardContent> <div className="text-2xl font-bold"> {totalMedicineStock.toLocaleString()} </div> <p className="text-xs text-gray-600 mt-1"> Across all medicine batches </p> </CardContent> </Card>
<Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Low Stock</CardTitle> </CardHeader> <CardContent> <div className="text-2xl font-bold text-orange-600"> {lowMedicineStockCount} </div> <p className="text-xs text-gray-600 mt-1"> Needs refill soon </p> </CardContent> </Card>
<Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Expired</CardTitle> </CardHeader> <CardContent> <div className="text-2xl font-bold text-red-600"> {expiredMedicineCount} </div> <p className="text-xs text-gray-600 mt-1">Do not use</p> </CardContent> </Card> </div>
<Card> <CardHeader className="flex flex-row items-center justify-between"> <div> <CardTitle>Medicine Inventory List</CardTitle> <p className="text-sm text-gray-600 mt-1"> Table view with quantity status and batch-level controls </p> </div> <Button size="icon" variant="ghost" className="text-gray-400 hover:text-[#0A4D68]" onClick={() => { loadMedicine(); loadMedicineTotals(); }} > <RefreshCw className="w-4 h-4" /> </Button> </CardHeader> <CardContent> {medicineInventory.length === 0 ? ( <div className="text-center py-12 border border-dashed rounded-lg bg-gray-50"> <Pill className="w-10 h-10 text-gray-400 mx-auto mb-2" /> <p className="text-sm text-gray-600"> No medicine inventory found for this farm. </p> <p className="text-xs text-gray-500 mt-1"> Once medicine stock is received, it will appear here. </p> </div> ) : ( <div className="overflow-x-auto"> <table className="w-full text-sm text-left border-collapse"> <thead className="bg-[#f8fafc] text-[#64748b] font-bold uppercase text-[10px] tracking-widest border-b border-[#e2e8f0]"> <tr> <th className="px-4 py-3">Medicine</th> <th className="px-4 py-3">Company</th> <th className="px-4 py-3">Quantity</th> <th className="px-4 py-3">Quantity (ml)</th> <th className="px-4 py-3">Expiry Date</th> <th className="px-4 py-3">Status</th> <th className="px-4 py-3 text-right">Actions</th> </tr> </thead> <tbody className="divide-y divide-[#f1f5f9]"> {medicineInventory.map((batch) => { const status = getMedicineBatchStatus(batch); const expiryWarning = getExpiryWarning( batch.expiryDate, ); return ( <tr key={batch.id} className="hover:bg-[#f8fafc] transition-colors" > <td className="px-4 py-3 font-semibold text-[#0A4D68]"> {batch.medicineName} </td> <td className="px-4 py-3 text-gray-700"> {batch.company || "-"} </td> <td className="px-4 py-3"> {batch.quantity.toLocaleString()} {batch.unit} </td> <td className="px-4 py-3"> {batch.mlPerUnit && batch.mlPerUnit > 0 ? ( batch.quantity * batch.mlPerUnit ).toLocaleString() + " ml" : "—"} </td> <td className="px-4 py-3 text-gray-700"> {batch.expiryDate ? new Date( batch.expiryDate, ).toLocaleDateString() : "-"} </td> <td className="px-4 py-3"> <div className="flex items-center gap-2 flex-wrap"> <Badge variant="outline" className={medicineStatusBadgeClass(status)} > {status.replace(/_/g, " ")} </Badge>
{expiryWarning && ( <Badge className={expiryWarning.className}> {expiryWarning.text} </Badge> )} </div> </td> <td className="px-4 py-3"> <div className="flex items-center justify-end gap-2"> <Button size="sm" variant="outline" onClick={() => openMedicineDetails(batch)} > <Eye className="w-4 h-4 mr-2" /> Details </Button> {isWarehouse && ( <Button size="sm" variant="ghost" className="text-red-600 hover:text-red-700 hover:bg-red-50" onClick={() => handleDeleteMedicine(batch) } disabled={isMedicineDeleting} > <Trash2 className="w-4 h-4" /> </Button> )} </div> </td> </tr> ); })} </tbody> </table> </div> )} </CardContent> </Card> </TabsContent> </Tabs>
{/* Allocate Fish to Tank Modal */} {selectedBatch && ( <AllocateFishToTank isOpen={showAllocateModal} onClose={() => { setShowAllocateModal(false); setSelectedBatch(null); }} batch={selectedBatch!} onAllocate={handleAllocate} farmId={selectedFarm?.id || ""} availableTanks={tanks} /> )} {/* Add Resources Modal */} <Dialog open={isAddResourcesOpen} onOpenChange={(open: boolean) => { setIsAddResourcesOpen(open); if (!open) { resetAddResourcesForm(); } }} > <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto"> <DialogHeader> <DialogTitle className="flex items-center gap-2 text-[#0A4D68]"> <Plus className="w-5 h-5" /> Add resources </DialogTitle> <DialogDescription className="sr-only"> Add inventory resources and select resource type, item, quantity, receive date, and expiry date. </DialogDescription> </DialogHeader> <div className="grid gap-4 py-4"> <div className="grid gap-2"> <Label htmlFor="resourceType">Resource Type</Label> <Select value={newResourceData.resourceType} onValueChange={(value: ResourceType) => { setNewResourceData((previous) => ({ ...previous, resourceType: value, feedItemId: "", medicineItemId: "", medicineCompany: "", fishBatchItemId: "", })); }} > <SelectTrigger id="resourceType"> <SelectValue placeholder="Select resource type" /> </SelectTrigger> <SelectContent> <SelectItem value="feed">Feed</SelectItem> <SelectItem value="medicine">Medicine</SelectItem> <SelectItem value="fish_batch">Fish Batch</SelectItem> </SelectContent> </Select> </div>
<Combobox items={addResourceItemOptions} value={addResourceSelectedItemValue || null} onChange={handleAddResourceItemChange} label={addResourceItemLabel} placeholder={addResourceItemPlaceholder} searchPlaceholder="Search by name or ID..." emptyText={addResourceEmptyText} /> <p className="text-xs text-gray-500"> {addResourceItemOptions.length > 0 ? `${addResourceItemOptions.length} item(s) available` : addResourceEmptyText} </p>
<div className="grid gap-2"> <Label htmlFor="quantityKg">{addResourceQuantityLabel}</Label> <Input id="quantityKg" type="number" min="1" step={addResourceQuantityStep} placeholder={addResourceQuantityPlaceholder} value={newResourceData.quantityKg} onChange={(event) => setNewResourceData((previous) => ({ ...previous, quantityKg: event.target.value, })) } /> </div> {newResourceData.resourceType === "medicine" && ( <div className="grid gap-2"> <Label htmlFor="mlPerUnit">Each unit contains (ml)*</Label> <Input id="mlPerUnit" type="number" min="0.1" step="0.1" placeholder="e.g. 500" value={newResourceData.mlPerUnit} onChange={(event) => setNewResourceData((previous) => ({ ...previous, mlPerUnit: event.target.value, })) } /> </div> )} {newResourceData.resourceType === "medicine" && ( <div className="grid gap-2"> <Label htmlFor="medicineCompany">Company</Label> <Input id="medicineCompany" placeholder="Enter manufacturer or supplier" value={newResourceData.medicineCompany} onChange={(event) => setNewResourceData((previous) => ({ ...previous, medicineCompany: event.target.value, })) } /> </div> )}
<div className="grid gap-2"> <Label htmlFor="receiveDate">Receive Date</Label> <Input id="receiveDate" type="date" value={newResourceData.receiveDate} onChange={(event) => setNewResourceData((previous) => ({ ...previous, receiveDate: event.target.value, })) } /> </div>
{newResourceData.resourceType !== "fish_batch" && ( <div className="grid gap-2"> <Label htmlFor="expiryDate">Expiry Date</Label> <Input id="expiryDate" type="date" value={newResourceData.expiryDate} onChange={(event) => setNewResourceData((previous) => ({ ...previous, expiryDate: event.target.value, })) } /> </div> )} </div> <DialogFooter> <Button onClick={handleAddResourceSubmit} className="bg-[#0A4D68] hover:bg-[#083d52]" > Submit </Button> </DialogFooter> </DialogContent> </Dialog>
<Dialog open={isMedicineDetailsOpen} onOpenChange={(open: boolean) => { setIsMedicineDetailsOpen(open); if (!open) { setSelectedMedicineBatch(null); } }} > <DialogContent className="sm:max-w-[540px]"> <DialogHeader> <DialogTitle className="flex items-center gap-2 text-[#0A4D68]"> <Pill className="w-5 h-5" /> Medicine Details </DialogTitle> </DialogHeader>
{selectedMedicineBatch && ( <div className="space-y-4"> <div className="grid grid-cols-2 gap-3 rounded-lg border p-3 text-sm"> <div> <p className="text-xs text-gray-500">Medicine</p> <p className="font-semibold"> {selectedMedicineBatch.medicineName} </p> </div> <div> <p className="text-xs text-gray-500">Company</p> <p className="font-medium"> {selectedMedicineBatch.company || "-"} </p> </div> <div> <p className="text-xs text-gray-500">Batch</p> <p className="font-mono text-xs"> {selectedMedicineBatch.batchNumber || "-"} </p> </div> <div> <p className="text-xs text-gray-500"> Each unit contains (ml) </p> <p className="font-mono text-xs"> {selectedMedicineBatch.mlPerUnit || "-"} </p> </div> <div> <p className="text-xs text-gray-500">Status</p> <Badge variant="outline" className={medicineStatusBadgeClass( getMedicineBatchStatus(selectedMedicineBatch), )} > {getMedicineBatchStatus(selectedMedicineBatch).replace( /_/g, " ", )} </Badge> </div> <div> <p className="text-xs text-gray-500">Current Quantity</p> <p className="font-semibold"> {selectedMedicineBatch.quantity.toLocaleString()}{" "} {selectedMedicineBatch.unit} </p> </div> <div> <p className="text-xs text-gray-500">Expiry Date</p> <p className="font-medium"> {selectedMedicineBatch.expiryDate ? new Date( selectedMedicineBatch.expiryDate, ).toLocaleDateString() : "-"} </p> </div> </div> </div> )} </DialogContent> </Dialog>
{/* Health Check & Quarantine Modal - Inventory Batch version */} {batchForHealth && ( <BatchHealthModal open={healthModalOpen} onOpenChange={setHealthModalOpen} batch={batchForHealth} mode={healthModalMode} onSuccess={loadBatches} /> )} </div> <Dialog open={deleteConfirmOpen} onOpenChange={(open: boolean) => { if (!open) { setDeleteConfirmOpen(false); setDeleteConfirmItem(null); } }} > <DialogContent className="max-w-[360px]"> <DialogHeader> <DialogTitle className="text-gray-900 font-bold"> {deleteConfirmType === "feed" ? "Delete Feed" : "Delete Medicine"} </DialogTitle> <DialogDescription className="text-gray-600 mt-1"> Are you sure you want to permanently delete{" "} <span className="font-semibold text-gray-800"> {deleteConfirmItem?.name ?? "this item"} </span> ? This action cannot be undone. </DialogDescription> </DialogHeader> <DialogFooter className="mt-2 flex justify-end gap-2"> <Button variant="outline" onClick={() => { setDeleteConfirmOpen(false); setDeleteConfirmItem(null); }} > Cancel </Button> <Button className="bg-red-600 hover:bg-red-700 text-white" onClick={confirmDelete} disabled={isMedicineDeleting} > {deleteConfirmType === "feed" ? "Delete Feed" : "Delete Medicine"} </Button> </DialogFooter> </DialogContent> </Dialog> </> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339import { useState, useEffect } from "react";import { User, Farm, Tank } from "../types";import { apiGet } from "../api";import { registerIotDevice, listIotDevices, unregisterIotDevice, subscribeToTankSensorStream, DeviceRegistration, SensorReadingEvent,} from "../services/iotApi";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue,} from "./ui/select";import { Button } from "./ui/button";import { Badge } from "./ui/badge";import { Input } from "./ui/input";import { Activity, Cpu, Database, RefreshCw, Trash2, Thermometer, Droplets, Link, ShieldCheck,} from "lucide-react";
interface Props { user: User; selectedFarm: Farm | null;}
const SPECIFIC_DEVICE_ID = "44:1D:64:F8:05:F4";
export default function IoTManagement({ user, selectedFarm }: Props) { const [tanks, setTanks] = useState<Tank[]>([]); const [registrations, setRegistrations] = useState<DeviceRegistration[]>([]); const [loading, setLoading] = useState(true); const [selectedTankId, setSelectedTankId] = useState<string>(""); const [deviceIdInput, setDeviceIdInput] = useState<string>(""); const [isRegistering, setIsRegistering] = useState(false); const [liveReading, setLiveReading] = useState<SensorReadingEvent | null>( null, ); const [streamConnected, setStreamConnected] = useState(false);
useEffect(() => { fetchData(); }, [selectedFarm]);
// Subscribe to live stream for selected tank useEffect(() => { if (!selectedTankId) { setLiveReading(null); setStreamConnected(false); return; }
const unsubsribe = subscribeToTankSensorStream({ tankId: selectedTankId, onSensorReading: (evt) => setLiveReading(evt), onConnectionStatusChange: (status) => setStreamConnected(status), onError: (err) => console.error("SSE Error:", err), });
return () => unsubsribe(); }, [selectedTankId]);
const fetchData = async () => { setLoading(true); try { const [tanksRes, regs] = await Promise.all([ apiGet<Tank[] | { data: Tank[] }>("/tanks"), listIotDevices(), ]); const tanksData = Array.isArray(tanksRes) ? tanksRes : tanksRes.data; setTanks(tanksData || []); setRegistrations(regs); } catch (err) { console.error("Failed to fetch IoT data", err); } finally { setLoading(false); } };
const handleRegister = async (e?: React.FormEvent) => { if (e) e.preventDefault(); if (!selectedTankId) { alert("Please select a tank first."); return; } if (!deviceIdInput) { alert("Please enter a device ID."); return; } setIsRegistering(true); try { await registerIotDevice({ device_id: deviceIdInput, tank_id: selectedTankId, }); setDeviceIdInput(""); await fetchData(); alert("Device registered successfully!"); } catch (err) { alert("Failed to register device: " + (err as Error).message); } finally { setIsRegistering(false); } };
const handleUnregister = async (deviceId: string) => { if (!confirm("Are you sure you want to unregister this device?")) return; try { await unregisterIotDevice(deviceId); await fetchData(); } catch (err) { alert("Failed to unregister: " + (err as Error).message); } };
const tanksWithDevices = tanks.filter((t) => registrations.some((r) => r.tank_id === t.id), );
const selectedTank = tanks.find((t) => t.id === selectedTankId); const selectedTankRegs = registrations.filter( (r) => r.tank_id === selectedTankId, );
return ( <div className="p-6 max-w-7xl mx-auto space-y-6 bg-gray-50 min-h-screen"> {/* Header */} <div className="flex justify-between items-center bg-white p-6 rounded-2xl shadow-sm border border-gray-100"> <div> <h1 className="text-3xl font-bold text-gray-900 flex items-center gap-2"> <Activity className="text-blue-600" /> IoT Management </h1> <p className="text-gray-500 mt-1"> Manage your farm's sensors and real-time monitoring </p> </div> <Button variant="outline" onClick={() => fetchData()} disabled={loading} className="rounded-xl border-gray-200" > <RefreshCw className={`w-4 h-4 mr-2 ${loading ? "animate-spin" : ""}`} /> Refresh </Button> </div>
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6"> {/* Registration Section */} <Card className="lg:col-span-1 shadow-sm border-none rounded-2xl overflow-hidden ring-1 ring-gray-200"> <CardHeader className="bg-white border-b border-gray-50"> <CardTitle className="text-lg font-semibold flex items-center gap-2"> <Link className="w-5 h-5 text-blue-500" /> Assign New Device </CardTitle> </CardHeader> <CardContent className="p-6"> <form onSubmit={handleRegister} className="space-y-6"> <div className="space-y-2"> <label className="text-sm font-medium text-gray-700"> Select Tank </label> <Select value={selectedTankId} onValueChange={setSelectedTankId} > <SelectTrigger className="rounded-xl bg-gray-50 border-gray-100"> <SelectValue placeholder="Chose a tank" /> </SelectTrigger> <SelectContent> {tanks.map((t) => ( <SelectItem key={t.id} value={t.id}> {t.name} </SelectItem> ))} </SelectContent> </Select> </div>
<div className="space-y-4"> <div className="space-y-2"> <label className="text-sm font-medium text-gray-700"> Device ID (MAC) </label> <div className="flex gap-2"> <Input placeholder="FF:FF:FF:FF:FF:FF" value={deviceIdInput} onChange={(e) => setDeviceIdInput(e.target.value)} className="rounded-xl bg-gray-50 border-gray-100 font-mono text-sm" /> </div> </div>
<Button type="submit" className="w-full rounded-xl bg-blue-600 hover:bg-blue-700 transition-all font-semibold h-12 text-white shadow-lg" disabled={isRegistering} > {isRegistering ? ( <RefreshCw className="animate-spin mr-2" /> ) : ( <ShieldCheck className="mr-2 w-5 h-5" /> )} Register Device </Button>
<div className="bg-blue-50/50 p-4 rounded-xl border border-blue-100 flex items-center justify-between"> <div> <p className="text-xs font-semibold text-blue-700 uppercase tracking-wider"> Suggested Device </p> <p className="text-sm font-mono mt-1 text-blue-900"> {SPECIFIC_DEVICE_ID} </p> </div> <Button type="button" size="sm" variant="secondary" onClick={() => setDeviceIdInput(SPECIFIC_DEVICE_ID)} className="bg-white text-blue-600 hover:bg-blue-50 rounded-lg shadow-sm border border-blue-100" > Select </Button> </div> </div> </form> </CardContent> </Card>
{/* Live Monitoring & Assigned Devices */} <div className="lg:col-span-2 space-y-6"> {/* Tanks with Devices Table */} <Card className="shadow-sm border-none rounded-2xl overflow-hidden ring-1 ring-gray-200"> <CardHeader className="bg-white border-b border-gray-50 flex flex-row items-center justify-between"> <CardTitle className="text-lg font-semibold flex items-center gap-2"> <Database className="w-5 h-5 text-gray-400" /> Active Device Mappings </CardTitle> </CardHeader> <CardContent className="p-0"> <div className="overflow-x-auto"> <table className="w-full text-left"> <thead className="bg-gray-50 text-gray-500 text-xs font-bold uppercase tracking-wider"> <tr> <th className="px-6 py-4">Tank Name</th> <th className="px-6 py-4">Device ID</th> <th className="px-6 py-4">Assigned At</th> <th className="px-6 py-4 text-right">Actions</th> </tr> </thead> <tbody className="divide-y divide-gray-100"> {tanksWithDevices.length === 0 ? ( <tr> <td colSpan={4} className="px-6 py-12 text-center text-gray-400" > <Cpu className="w-12 h-12 mx-auto mb-4 opacity-20" /> <p className="text-sm font-medium"> No devices currently assigned </p> </td> </tr> ) : ( tanksWithDevices.map((tank) => { const reg = registrations.find( (r) => r.tank_id === tank.id, ); return ( <tr key={tank.id} className="hover:bg-gray-50/50 transition-colors cursor-pointer group" onClick={() => setSelectedTankId(tank.id)} > <td className="px-6 py-4"> <div className="font-semibold text-gray-900"> {tank.name} </div> <div className="text-xs text-gray-500"> Capacity: {tank.capacity}L </div> </td> <td className="px-6 py-4"> <Badge className="bg-white border text-blue-600 font-mono border-blue-100 rounded-lg"> {reg?.device_id} </Badge> </td> <td className="px-6 py-4 text-sm text-gray-500"> {reg?.registered_at ? new Date( reg.registered_at, ).toLocaleDateString() : "N/A"} </td> <td className="px-6 py-4 text-right"> <Button size="sm" variant="ghost" onClick={(e: React.MouseEvent) => { e.stopPropagation(); handleUnregister(reg?.device_id || ""); }} className="text-red-500 hover:text-red-700 hover:bg-red-50 rounded-xl" > <Trash2 className="w-4 h-4" /> </Button> </td> </tr> ); }) )} </tbody> </table> </div> </CardContent> </Card> </div> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324import { FormEvent, useMemo, useState } from "react";import { AlertCircle, Fish, Lock, Mail } from "lucide-react";import { Button } from "./ui/button";import { Input } from "./ui/input";import { Label } from "./ui/label";import { Card, CardContent, CardDescription, CardHeader, CardTitle,} from "./ui/card";import { User } from "../types";import { AuthApiError, login, preLogin } from "../services/authApi";import { mapBackendUserToAppUser, persistAuthSession,} from "../services/authSession";import { AuthLoginResult, FarmInfo } from "../services/authTypes";
interface LoginProps { onLogin: (user: User) => void;}
type LoginStep = "credentials" | "farm-selection" | "otp-required";
const DEFAULT_OTP_MESSAGE = "OTP verification is required for this account. Complete OTP on the backend-supported channel.";const QUICK_LOGIN_PASSWORD = "FishFarm360!2026";const QUICK_LOGIN_PRESETS = [ { key: "admin", email: "admin.test@fishfarm360.local" }, { key: "Warehouse Manager", email: "warehousemanager@fishfarm360.local", }, { key: "Technician", email: "technician.test@fishfarm360.local" }, { key: "Worker", email: "workeraccount@gmail.com" },];
const normalizeErrorMessage = (error: unknown): string => { if (error instanceof AuthApiError) { return error.message; } if (error instanceof Error && error.message.trim()) { return error.message; } return "Unable to sign in right now. Please try again.";};
export default function Login({ onLogin }: LoginProps) { const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [farms, setFarms] = useState<FarmInfo[]>([]); const [selectedFarmId, setSelectedFarmId] = useState(""); const [step, setStep] = useState<LoginStep>("credentials"); const [errorMessage, setErrorMessage] = useState<string | null>(null); const [otpMessage, setOtpMessage] = useState(DEFAULT_OTP_MESSAGE); const [isSubmitting, setIsSubmitting] = useState(false);
const stepDescription = useMemo(() => { if (step === "farm-selection") { return "Select the farm to continue login."; } if (step === "otp-required") { return "OTP verification is required before the session can be finalized."; } return "Sign in with your email and password."; }, [step]);
const completeLogin = (result: AuthLoginResult): void => { if (result.requiresOTP) { setOtpMessage(result.message?.trim() || DEFAULT_OTP_MESSAGE); setStep("otp-required"); return; }
if (!result.user || !result.token) { throw new Error("Login response is incomplete. Please try again."); }
const appUser = mapBackendUserToAppUser(result.user); persistAuthSession(result, appUser); onLogin(appUser); };
const handleCredentialSubmit = async (event: FormEvent<HTMLFormElement>) => { event.preventDefault();
const normalizedEmail = email.trim(); if (!normalizedEmail || !password) { setErrorMessage("Email and password are required."); return; }
setIsSubmitting(true); setErrorMessage(null);
try { const response = await preLogin({ email: normalizedEmail, password, });
if (response.requiresFarmSelection) { if (!response.farms?.length) { throw new Error("No farms are available for this account."); } setFarms(response.farms); setSelectedFarmId(response.farms[0].id); setStep("farm-selection"); return; }
if (!response.loginResult) { throw new Error("Pre-login completed but did not return login data."); }
completeLogin(response.loginResult); } catch (error) { setErrorMessage(normalizeErrorMessage(error)); } finally { setIsSubmitting(false); } };
const handleFarmSubmit = async (event: FormEvent<HTMLFormElement>) => { event.preventDefault();
if (!selectedFarmId) { setErrorMessage("Please select a farm to continue."); return; }
setIsSubmitting(true); setErrorMessage(null);
try { const result = await login({ email: email.trim(), password, farmId: selectedFarmId, });
completeLogin(result); } catch (error) { setErrorMessage(normalizeErrorMessage(error)); } finally { setIsSubmitting(false); } };
const resetToCredentials = () => { setStep("credentials"); setErrorMessage(null); setOtpMessage(DEFAULT_OTP_MESSAGE); };
return ( <div className="min-h-screen flex items-center justify-center bg-gradient-to-br from-[#E0F4F5] via-[#05BFDB]/20 to-[#088395]/30 p-4"> <Card className="w-full max-w-md border-white/40 shadow-xl"> <CardHeader className="space-y-1 text-center"> <div className="flex justify-center mb-4"> <div className="bg-[#0A4D68] p-3 rounded-full"> <Fish className="w-8 h-8 text-white" /> </div> </div> <CardTitle className="text-2xl">FishFarm360</CardTitle> <CardDescription> Smart Aquaculture Management Platform </CardDescription> <p className="text-xs text-gray-600">{stepDescription}</p> </CardHeader>
<CardContent> {errorMessage && ( <div className="mb-4 rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700 flex items-start gap-2"> <AlertCircle className="w-4 h-4 mt-0.5 shrink-0" /> <span>{errorMessage}</span> </div> )}
{step === "credentials" && ( <form onSubmit={handleCredentialSubmit} className="space-y-4" noValidate > <div className="space-y-2"> <Label htmlFor="email">Email Address</Label> <Input id="email" name="email" type="email" placeholder="user@example.com" value={email} onChange={(event) => setEmail(event.target.value)} disabled={isSubmitting} autoComplete="email" required /> </div>
<div className="space-y-2"> <Label htmlFor="password">Password</Label> <Input id="password" name="password" type="password" placeholder="Enter your password" value={password} onChange={(event) => setPassword(event.target.value)} disabled={isSubmitting} autoComplete="current-password" required /> </div>
<Button type="submit" className="w-full bg-[#088395] hover:bg-[#0A4D68]" disabled={isSubmitting} > <Lock className="w-4 h-4 mr-2" /> {isSubmitting ? "Signing in..." : "Sign In"} </Button>
<div className="space-y-2 rounded-md border border-gray-200 bg-gray-50 p-3"> <p className="text-xs font-medium text-gray-700"> Quick Login Presets </p> <p className="text-xs text-gray-500"> Password: {QUICK_LOGIN_PASSWORD} </p> <div className="grid grid-cols-2 gap-2"> {QUICK_LOGIN_PRESETS.map((preset) => ( <Button key={preset.key} type="button" variant="outline" size="sm" className="justify-start" onClick={() => { setEmail(preset.email); setPassword(QUICK_LOGIN_PASSWORD); setErrorMessage(null); }} disabled={isSubmitting} > {preset.key} </Button> ))} </div> </div> </form> )}
{step === "farm-selection" && ( <form onSubmit={handleFarmSubmit} className="space-y-4" noValidate> <div className="space-y-2"> <Label htmlFor="selected-email">Email</Label> <Input id="selected-email" value={email} disabled /> </div>
<div className="space-y-2"> <Label htmlFor="farm">Select Farm</Label> <select id="farm" name="farm" value={selectedFarmId} onChange={(event) => setSelectedFarmId(event.target.value)} disabled={isSubmitting} className="file:text-foreground placeholder:text-muted-foreground selection:bg-primary selection:text-primary-foreground border-input flex h-9 w-full min-w-0 rounded-md border px-3 py-1 text-base bg-input-background transition-[color,box-shadow] outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] disabled:pointer-events-none disabled:cursor-not-allowed disabled:opacity-50 md:text-sm" > {farms.map((farm) => ( <option key={farm.id} value={farm.id}> {farm.name} </option> ))} </select> </div>
<div className="flex gap-2"> <Button type="button" variant="outline" className="flex-1" onClick={resetToCredentials} disabled={isSubmitting} > Back </Button> <Button type="submit" className="flex-1 bg-[#088395] hover:bg-[#0A4D68]" disabled={isSubmitting} > <Mail className="w-4 h-4 mr-2" /> {isSubmitting ? "Finalizing..." : "Sign In to Farm"} </Button> </div> </form> )}
{step === "otp-required" && ( <div className="space-y-4"> <div className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800"> <p className="font-medium">OTP required</p> <p className="mt-1">{otpMessage}</p> </div>
<Button type="button" className="w-full bg-[#088395] hover:bg-[#0A4D68]" onClick={resetToCredentials} > Back to Sign In </Button> </div> )} </CardContent> </Card> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483import { useState, useEffect, useCallback } from "react";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Button } from "./ui/button";import { Input } from "./ui/input";import { Label } from "./ui/label";import { Textarea } from "./ui/textarea";import { Dialog, DialogContent } from "./ui/dialog";import { Badge } from "./ui/badge";import { Pill, Plus, Edit, Trash2, RefreshCw, Loader2, BellRing, Clock,} from "lucide-react";import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,} from "./ui/alert-dialog";import { User, Farm } from "../types";import { apiGet, apiPost, apiPut, apiDelete } from "../api";import { toast } from "sonner";
interface MedicineTypeManagementProps { user: User; selectedFarm: Farm | null;}
export default function MedicineTypeManagement({ user: _user, selectedFarm: _selectedFarm,}: MedicineTypeManagementProps) { const [showCreateModal, setShowCreateModal] = useState(false); const [editingId, setEditingId] = useState<string | null>(null); const [saving, setSaving] = useState(false); const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null);
const [medicineTypes, setMedicineTypes] = useState<any[]>([]); const [loading, setLoading] = useState(true);
const [formData, setFormData] = useState({ name: "", arabicName: "", description: "", category: "", storageInstructions: "", withdrawalPeriodDays: 0, lowStockThreshold: 10, isActive: true, notes: "", });
const fetchMedicineTypes = useCallback(async () => { setLoading(true); try { const res = await apiGet<any>("/inventory/medicine-types"); const rawData = res.data || res || []; const normalizedData = Array.isArray(rawData) ? rawData.map((item: any) => ({ ...item, id: item.id || item._id, })) : []; setMedicineTypes(normalizedData); } catch (err) { console.error("Failed to fetch medicine types:", err); } finally { setLoading(false); } }, []);
useEffect(() => { fetchMedicineTypes(); }, [fetchMedicineTypes]);
const handleEdit = (medicineType: any) => { setFormData({ ...medicineType, description: medicineType.description || "", category: medicineType.category || "", storageInstructions: medicineType.storageInstructions || "", withdrawalPeriodDays: medicineType.withdrawalPeriodDays || 0, lowStockThreshold: medicineType.lowStockThreshold || 10, notes: medicineType.notes || "", isActive: medicineType.isActive ?? true, }); setEditingId(medicineType.id); setShowCreateModal(true); };
const handleDelete = async () => { if (!deleteConfirmId) return; try { await apiDelete(`/inventory/medicine-types/${deleteConfirmId}`); toast.success("Medicine type deleted"); fetchMedicineTypes(); } catch (err) { toast.error("Failed to delete: " + (err as Error).message); } finally { setDeleteConfirmId(null); } };
const handleSave = async () => { if (!formData.name || !formData.arabicName) { toast.error("الاسم والاسم العربي مطلوبين"); return; }
setSaving(true); const { id, createdAt, updatedAt, deletedAt, ...submissionData } = formData as any;
try { if (editingId) { await apiPut(`/inventory/medicine-types/${editingId}`, submissionData); } else { await apiPost("/inventory/medicine-types", submissionData); } toast.success("Medicine type added successfully"); fetchMedicineTypes(); } catch (err) { console.warn("API Error - Switching to Mock Data:", err); const mockItem = { ...formData, id: editingId || Math.random().toString(36).substr(2, 9), }; if (editingId) { setMedicineTypes((prev) => prev.map((item) => (item.id === editingId ? mockItem : item)), ); } else { setMedicineTypes((prev) => [...prev, mockItem]); } toast.info("تمت الإضافة محلياً"); } finally { setSaving(false); setShowCreateModal(false); setEditingId(null); setFormData({ name: "", arabicName: "", description: "", category: "", storageInstructions: "", withdrawalPeriodDays: 0, lowStockThreshold: 10, isActive: true, notes: "", }); } }; const isTechnician = _user.role.toLowerCase() === "technician"; return ( <div className="min-h-screen bg-[#F9FAFB]"> <div className="bg-[#0A4D68] text-white px-6 py-4"> <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> <Pill className="w-6 h-6" /> <span className="text-xl font-semibold"> Medicine Type Management </span> </div> </div> </div>
<div className="p-6 space-y-6"> <div className="flex justify-between items-center"> <div> <h2 className="text-2xl font-semibold">Medicine Catalogue</h2> <p className="text-sm text-gray-500"> Manage medicine classification and inventory alert levels </p> </div> <div className="flex items-center gap-3"> <Button variant="outline" size="sm" onClick={() => fetchMedicineTypes()} disabled={loading} > <RefreshCw className={`w-4 h-4 mr-1 ${loading ? "animate-spin" : ""}`} /> Refresh </Button> {isTechnician && ( <Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => { setEditingId(null); setShowCreateModal(true); }} > <Plus className="w-4 h-4 mr-2" /> Add Medicine Type </Button> )} </div> </div>
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4"> {loading ? ( <div className="col-span-full py-20 flex justify-center"> <Loader2 className="animate-spin text-[#088395]" /> </div> ) : medicineTypes.length === 0 ? ( <div className="col-span-full py-20 bg-white border border-dashed rounded-xl flex flex-col items-center justify-center text-gray-400"> <Plus className="w-10 h-10 mb-4 opacity-20" /> <p>No medicine types registered yet.</p> <Button variant="link" onClick={() => setShowCreateModal(true)}> Add your first medicine type </Button> </div> ) : ( medicineTypes.map((medicineType) => ( <Card key={medicineType.id} className="bg-white shadow-sm border-t-4 border-[#088395]" > <CardHeader className="pb-2"> <div className="flex justify-between items-start gap-3"> <div> <CardTitle className="text-lg"> {medicineType.name} </CardTitle> <p className="text-xs text-gray-400"> {medicineType.arabicName} </p> </div> <Badge variant="secondary" className="bg-[#088395]/10 text-[#088395] border-none flex gap-1 items-center" > <BellRing className="w-3 h-3" /> {medicineType.lowStockThreshold || 10} </Badge> </div> </CardHeader> <CardContent className="space-y-4"> <div className="flex gap-2 flex-wrap"> {medicineType.category && ( <Badge variant="outline" className="text-[10px]"> {medicineType.category} </Badge> )} <Badge variant="outline" className="text-[10px] flex items-center gap-1" > <Clock className="w-3 h-3" /> {medicineType.withdrawalPeriodDays || 0} days </Badge> <Badge variant="outline" className="text-[10px] flex items-center gap-1" > <BellRing className="w-3 h-3" /> {medicineType.lowStockThreshold || 10} </Badge> </div> {medicineType.description && ( <p className="text-sm text-gray-600 line-clamp-3"> {medicineType.description} </p> )} {isTechnician && ( <div className="flex gap-2 pt-2 border-t"> <Button size="sm" variant="outline" className="flex-1" onClick={() => handleEdit(medicineType)} > <Edit className="w-3 h-3 mr-1" /> Edit </Button> <Button size="sm" variant="outline" className="text-red-500 hover:bg-red-50" onClick={() => setDeleteConfirmId(medicineType.id)} > <Trash2 className="w-3 h-3" /> </Button> </div> )} </CardContent> </Card> )) )} </div> </div>
<Dialog open={showCreateModal} onOpenChange={setShowCreateModal}> <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto"> <div className="space-y-6 pt-4"> <div className="space-y-4"> <h3 className="text-sm font-bold text-gray-900 uppercase tracking-wider border-b pb-2"> Basic Information </h3> <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="space-y-2"> <Label>Name *</Label> <Input placeholder="English Name" value={formData.name} onChange={(e) => setFormData({ ...formData, name: e.target.value }) } /> </div> <div className="space-y-2"> <Label>Arabic Name *</Label> <Input placeholder="الاسم بالعربي" value={formData.arabicName} onChange={(e) => setFormData({ ...formData, arabicName: e.target.value }) } /> </div> </div> </div>
<div className="space-y-4"> <h3 className="text-sm font-bold text-gray-900 uppercase tracking-wider border-b pb-2"> Classification & Safety </h3> <div className="grid grid-cols-1 md:grid-cols-2 gap-4"> <div className="space-y-2"> <Label>Category</Label> <Input placeholder="e.g. Antibiotic" value={formData.category} onChange={(e) => setFormData({ ...formData, category: e.target.value }) } /> </div> <div className="space-y-2"> <Label className="flex items-center gap-2"> <Clock className="w-4 h-4 text-[#088395]" /> Withdrawal Period (Days) </Label> <Input type="number" value={formData.withdrawalPeriodDays} onChange={(e) => setFormData({ ...formData, withdrawalPeriodDays: parseInt(e.target.value) || 0, }) } /> </div> <div className="space-y-2 md:col-span-2"> <Label>Description</Label> <Textarea placeholder="Short description" value={formData.description} onChange={(e) => setFormData({ ...formData, description: e.target.value }) } /> </div> <div className="space-y-2 md:col-span-2"> <Label>Storage Instructions</Label> <Textarea placeholder="Storage instructions" value={formData.storageInstructions} onChange={(e) => setFormData({ ...formData, storageInstructions: e.target.value, }) } /> </div> </div> </div>
<div className="space-y-4"> <h3 className="text-sm font-bold text-gray-900 uppercase tracking-wider border-b pb-2"> Inventory Settings </h3> <div className="grid grid-cols-1 md:grid-cols-2 gap-4 items-end"> <div className="space-y-2"> <Label className="flex items-center gap-2"> <BellRing className="w-4 h-4 text-[#088395]" /> Low Stock Threshold </Label> <Input type="number" step="1" placeholder="e.g. 10" value={formData.lowStockThreshold} onChange={(e) => setFormData({ ...formData, lowStockThreshold: parseFloat(e.target.value) || 0, }) } /> </div> <p className="text-[11px] text-gray-400 pb-2 italic"> Systems will alert when stock levels fall below this value. </p> </div> </div>
<div className="space-y-4"> <h3 className="text-sm font-bold text-gray-900 uppercase tracking-wider border-b pb-2"> Additional Notes </h3> <div className="grid grid-cols-1 gap-4"> <div className="space-y-2"> <Label>Notes</Label> <Textarea placeholder="Internal notes" value={formData.notes} onChange={(e) => setFormData({ ...formData, notes: e.target.value }) } /> </div> </div> </div>
<div className="flex gap-3 pt-4 border-t"> <Button variant="outline" className="flex-1" onClick={() => setShowCreateModal(false)} > Cancel </Button> <Button className="flex-1 bg-[#088395] hover:bg-[#0A4D68]" onClick={handleSave} disabled={saving} > {saving ? "Saving..." : editingId ? "Update Product" : "Create Product"} </Button> </div> </div> </DialogContent> </Dialog>
<AlertDialog open={!!deleteConfirmId} onOpenChange={() => setDeleteConfirmId(null)} > <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>Delete Product?</AlertDialogTitle> </AlertDialogHeader> <AlertDialogDescription> This action will remove the medicine type from the catalogue permanently. </AlertDialogDescription> <AlertDialogFooter> <AlertDialogCancel>Cancel</AlertDialogCancel> <AlertDialogAction onClick={handleDelete} className="bg-red-600"> Delete </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618import { useState } from "react";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Button } from "./ui/button";import { Badge } from "./ui/badge";import { Switch } from "./ui/switch";import { Tabs, TabsContent, TabsList, TabsTrigger } from "./ui/tabs";import { Bell, AlertTriangle, Info, Check, X, Mail, MessageSquare, Smartphone,} from "lucide-react";import { User } from "../types";
interface NotificationCenterProps { user: User; notifications: any[]; onUpdateNotifications: (notifications: any[]) => void;}
export default function NotificationCenter({ user, notifications, onUpdateNotifications,}: NotificationCenterProps) { const [filter, setFilter] = useState<"all" | "unread" | "critical">("all");
// Notification preferences const [emailEnabled, setEmailEnabled] = useState(true); const [smsEnabled, setSmsEnabled] = useState(true); const [whatsappEnabled, setWhatsappEnabled] = useState(false); const [criticalAlerts, setCriticalAlerts] = useState(true); const [inventoryAlerts, setInventoryAlerts] = useState(true); const [healthAlerts, setHealthAlerts] = useState(true);
const filteredNotifications = notifications.filter((notif) => { if (filter === "unread") return !notif.read; if (filter === "critical") return notif.priority === "critical"; return true; });
const unreadCount = notifications.filter((n) => !n.read).length; const criticalCount = notifications.filter( (n) => n.priority === "critical" && !n.read, ).length;
const handleMarkAsRead = (id: string) => { onUpdateNotifications( notifications.map((n) => (n.id === id ? { ...n, read: true } : n)), ); };
const handleMarkAllAsRead = () => { onUpdateNotifications(notifications.map((n) => ({ ...n, read: true }))); };
const handleDelete = (id: string) => { onUpdateNotifications(notifications.filter((n) => n.id !== id)); };
const getNotificationIcon = (type: string) => { switch (type) { case "alert": case "WARNING": case "warning": return AlertTriangle; case "CRITICAL": case "critical": return AlertTriangle; case "SUCCESS": case "success": return Check; case "INFO": case "info": return Info; default: return Bell; } };
const getNotificationColor = (type: string) => { const t = type?.toUpperCase(); switch (t) { case "CRITICAL": return "bg-red-50 border-red-200"; case "WARNING": return "bg-yellow-50 border-yellow-200"; case "SUCCESS": return "bg-green-50 border-green-200"; case "INFO": case "NORMAL": return "bg-blue-50 border-blue-200"; default: return "bg-gray-50 border-gray-200"; } }; const getPriorityBadgeColor = (priority: string) => { switch (priority) { case "critical": return "bg-red-100 text-red-800"; case "high": return "bg-orange-100 text-orange-800"; case "medium": return "bg-yellow-100 text-yellow-800"; case "low": return "bg-blue-100 text-blue-800"; default: return "bg-gray-100 text-gray-800"; } };
const parseTimestampValue = (value: unknown): Date | null => { if (value instanceof Date) { return Number.isNaN(value.getTime()) ? null : value; }
if (typeof value === "number" && Number.isFinite(value)) { const normalized = Math.abs(value) < 1e12 ? value * 1000 : value; const date = new Date(normalized); return Number.isNaN(date.getTime()) ? null : date; }
if (typeof value === "string" && value.trim()) { const trimmed = value.trim(); if (/^\d+(\.\d+)?$/.test(trimmed)) { const numericValue = Number(trimmed); if (Number.isFinite(numericValue)) { const normalized = Math.abs(numericValue) < 1e12 ? numericValue * 1000 : numericValue; const date = new Date(normalized); if (!Number.isNaN(date.getTime())) return date; } }
const date = new Date(trimmed); return Number.isNaN(date.getTime()) ? null : date; }
return null; };
const getTimeAgo = (timestamp?: unknown) => { const time = parseTimestampValue(timestamp); if (!time) return "Just now";
const diffMs = Date.now() - time.getTime(); if (diffMs <= 0) return "Just now";
const diffInMinutes = Math.floor(diffMs / (1000 * 60)); if (diffInMinutes < 1) return "Just now"; if (diffInMinutes < 60) return `${diffInMinutes}m ago`;
const diffInHours = Math.floor(diffInMinutes / 60); if (diffInHours < 24) return `${diffInHours}h ago`;
const diffInDays = Math.floor(diffInHours / 24); if (diffInDays < 7) return `${diffInDays}d ago`;
return time.toLocaleDateString(); };
const getExactTime = (timestamp?: unknown) => { const time = parseTimestampValue(timestamp); return time ? time.toLocaleString() : ""; }; const isWaterChangeDone = (notification: any) => notification.type === "SUCCESS" || notification.type === "success" || notification.templateName === "WATER_CHANGE_DONE" || notification.subject?.toLowerCase().includes("water change completed") || notification.subject?.toLowerCase().includes("water change done"); const isFeedingCompleted = (notification: any) => notification.templateName === "FEEDING_DONE" || notification.templateName === "FEEDING_COMPLETED" || notification.subject?.toLowerCase().includes("feeding completed") || notification.subject?.toLowerCase().includes("feeding done"); const isHarvestFinished = (notification: any) => notification.templateName === "HARVEST_FINISHED" || notification.templateName === "HARVEST_DONE" || notification.subject?.toLowerCase().includes("harvest finished") || notification.subject?.toLowerCase().includes("harvest completed"); // Notifications styled as a green, "DONE" card const isCompleted = (notification: any) => isWaterChangeDone(notification) || isFeedingCompleted(notification) || isHarvestFinished(notification); const isWaterChangeTask = (notification: any) => !isCompleted(notification) && (notification.templateName === "WATER_CHANGE_TASK" || notification.subject?.toLowerCase().includes("water change task")); const isCritical = (notification: any) => notification.priority === "critical" || notification.type?.toUpperCase() === "CRITICAL" || notification.subject?.toLowerCase().includes("critical"); const isHarvestReminder = (notification: any) => !isCritical(notification) && (notification.templateName === "HARVEST_REMINDER" || notification.subject?.toLowerCase().includes("harvest reminder")); const isHarvestTask = (notification: any) => !isCompleted(notification) && (notification.templateName === "HARVEST_TASK" || notification.subject?.toLowerCase().includes("harvest task")); // Notifications styled as a blue, badge-less info card const isBlueInfo = (notification: any) => isWaterChangeTask(notification) || isHarvestReminder(notification) || isHarvestTask(notification); return ( <div className="p-6 space-y-6"> <div className="flex items-center justify-between"> <div> <h1 className="text-2xl">Notification Center</h1> <p className="text-gray-600"> Manage alerts and communication preferences </p> </div> <Button onClick={handleMarkAllAsRead} variant="outline"> <Check className="w-4 h-4 mr-2" /> Mark All Read </Button> </div>
{/* Summary Cards */} <div className="grid grid-cols-1 md:grid-cols-3 gap-4"> <Card> <CardHeader className="flex flex-row items-center justify-between pb-2"> <CardTitle className="text-sm">Total Notifications</CardTitle> <Bell className="w-4 h-4 text-blue-600" /> </CardHeader> <CardContent> <div className="text-2xl">{notifications.length}</div> <p className="text-xs text-gray-600 mt-1">{unreadCount} unread</p> </CardContent> </Card>
<Card> <CardHeader className="flex flex-row items-center justify-between pb-2"> <CardTitle className="text-sm">Critical Alerts</CardTitle> <AlertTriangle className="w-4 h-4 text-red-600" /> </CardHeader> <CardContent> <div className="text-2xl text-red-600">{criticalCount}</div> <p className="text-xs text-gray-600 mt-1">Unread critical</p> </CardContent> </Card>
<Card> <CardHeader className="flex flex-row items-center justify-between pb-2"> <CardTitle className="text-sm">Active Channels</CardTitle> <Mail className="w-4 h-4 text-green-600" /> </CardHeader> <CardContent> <div className="text-2xl"> { [emailEnabled, smsEnabled, whatsappEnabled].filter(Boolean) .length } </div> <p className="text-xs text-gray-600 mt-1">Communication methods</p> </CardContent> </Card> </div>
<Tabs defaultValue="notifications" className="space-y-4"> <TabsList> <TabsTrigger value="notifications"> <Bell className="w-4 h-4 mr-2" /> Notifications </TabsTrigger> </TabsList>
{/* Notifications Tab */} <TabsContent value="notifications" className="space-y-4"> <Card> <CardHeader> <div className="flex items-center gap-2"> <Button variant={filter === "all" ? "default" : "outline"} size="sm" onClick={() => setFilter("all")} > All ({notifications.length}) </Button> <Button variant={filter === "unread" ? "default" : "outline"} size="sm" onClick={() => setFilter("unread")} > Unread ({unreadCount}) </Button> <Button variant={filter === "critical" ? "default" : "outline"} size="sm" onClick={() => setFilter("critical")} > Critical ({criticalCount}) </Button> </div> </CardHeader> <CardContent> <div className="space-y-2"> {filteredNotifications.map((notification) => { const Icon = getNotificationIcon(notification.type); const subjectText = notification.subject || notification.title || "Notification"; const bodyText = notification.message || notification.body || "";
return ( <div key={notification.id} className={`p-4 border rounded-lg transition-all ${!isCompleted(notification) && !isBlueInfo(notification) && !isCritical(notification) ? getNotificationColor(notification.priority) : ""} ${!notification.read ? "border-l-4" : ""}`} style={ isCompleted(notification) ? { backgroundColor: "#f0fdf4", borderColor: "#bbf7d0", } : isBlueInfo(notification) ? { backgroundColor: "#eff6ff", borderColor: "#bfdbfe", } : isCritical(notification) ? { backgroundColor: "#fee2e2", borderColor: "#fca5a5", } : undefined } > <div className="flex items-start gap-3"> <div className="mt-0.5" style={{ color: isCritical(notification) ? "#dc2626" : isBlueInfo(notification) ? "#2563eb" : notification.type?.toUpperCase() === "WARNING" ? "#ca8a04" : notification.type?.toUpperCase() === "SUCCESS" || isCompleted(notification) ? "#16a34a" : "#2563eb", }} > {notification.type?.toUpperCase() === "SUCCESS" || isCompleted(notification) ? ( <Check className="w-5 h-5" /> ) : isCritical(notification) ? ( <AlertTriangle className="w-5 h-5" /> ) : isBlueInfo(notification) ? ( <Info className="w-5 h-5" /> ) : notification.type?.toUpperCase() === "WARNING" ? ( <AlertTriangle className="w-5 h-5" /> ) : ( <Info className="w-5 h-5" /> )} </div>
<div className="flex-1 min-w-0"> <div className="flex items-start justify-between mb-1"> <div className="flex items-center gap-2 flex-1"> <p className={`text-sm ${!notification.read ? "font-medium" : ""}`} > {subjectText} </p> {isCompleted(notification) ? ( <Badge className="bg-green-600 text-white border-green-600" variant="outline" > DONE </Badge> ) : isBlueInfo(notification) ? null : ( <Badge className={getPriorityBadgeColor( notification.priority, )} variant="outline" > {notification.priority} </Badge> )} {!notification.read && ( <div className="w-2 h-2 bg-blue-600 rounded-full" /> )} </div> <span className="text-xs text-gray-500 whitespace-nowrap ml-2" title={getExactTime(notification.timestamp)} > {getTimeAgo(notification.timestamp)} </span> </div>
<p className="text-sm text-gray-700 mb-2"> {bodyText} </p>
<div className="flex items-center gap-2"> {!notification.read && ( <Button size="sm" variant="outline" onClick={() => handleMarkAsRead(notification.id) } > <Check className="w-3 h-3 mr-1" /> Mark Read </Button> )} <Button size="sm" variant="ghost" onClick={() => handleDelete(notification.id)} > <X className="w-3 h-3 mr-1" /> Dismiss </Button> </div> </div> </div> </div> ); })}
{filteredNotifications.length === 0 && ( <div className="text-center py-12"> <Bell className="w-12 h-12 text-gray-400 mx-auto mb-3" /> <p className="text-gray-600">No notifications</p> <p className="text-sm text-gray-500 mt-1"> {filter === "unread" ? "You're all caught up!" : filter === "critical" ? "No critical alerts at this time" : "You'll see notifications here"} </p> </div> )} </div> </CardContent> </Card> </TabsContent>
{/* Preferences Tab */} <TabsContent value="preferences" className="space-y-4"> <Card> <CardHeader> <CardTitle className="text-sm">Notification Channels</CardTitle> <p className="text-xs text-gray-600"> Choose how you want to receive alerts </p> </CardHeader> <CardContent className="space-y-4"> <div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"> <div className="flex items-center gap-3"> <Mail className="w-5 h-5 text-blue-600" /> <div> <p className="text-sm">Email Notifications</p> <p className="text-xs text-gray-600">{user.email}</p> </div> </div> <Switch checked={emailEnabled} onCheckedChange={setEmailEnabled} /> </div>
<div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"> <div className="flex items-center gap-3"> <Smartphone className="w-5 h-5 text-green-600" /> <div> <p className="text-sm">SMS Alerts</p> <p className="text-xs text-gray-600">{user.phone}</p> </div> </div> <Switch checked={smsEnabled} onCheckedChange={setSmsEnabled} /> </div>
<div className="flex items-center justify-between p-3 bg-gray-50 rounded-lg"> <div className="flex items-center gap-3"> <MessageSquare className="w-5 h-5 text-green-700" /> <div> <p className="text-sm">WhatsApp</p> <p className="text-xs text-gray-600">{user.phone}</p> </div> </div> <Switch checked={whatsappEnabled} onCheckedChange={setWhatsappEnabled} /> </div> </CardContent> </Card>
<Card> <CardHeader> <CardTitle className="text-sm">Alert Types</CardTitle> <p className="text-xs text-gray-600"> Customize which alerts you want to receive </p> </CardHeader> <CardContent className="space-y-4"> <div className="flex items-center justify-between p-3 border rounded-lg"> <div className="flex items-center gap-3"> <AlertTriangle className="w-5 h-5 text-red-600" /> <div> <p className="text-sm">Critical System Alerts</p> <p className="text-xs text-gray-600"> Water quality issues, equipment failures </p> </div> </div> <Switch checked={criticalAlerts} onCheckedChange={setCriticalAlerts} /> </div>
<div className="flex items-center justify-between p-3 border rounded-lg"> <div className="flex items-center gap-3"> <Bell className="w-5 h-5 text-orange-600" /> <div> <p className="text-sm">Inventory Alerts</p> <p className="text-xs text-gray-600"> Low stock, expiring items </p> </div> </div> <Switch checked={inventoryAlerts} onCheckedChange={setInventoryAlerts} /> </div>
<div className="flex items-center justify-between p-3 border rounded-lg"> <div className="flex items-center gap-3"> <AlertTriangle className="w-5 h-5 text-purple-600" /> <div> <p className="text-sm">Health & Disease Alerts</p> <p className="text-xs text-gray-600"> Disease detection, mortality spikes </p> </div> </div> <Switch checked={healthAlerts} onCheckedChange={setHealthAlerts} /> </div>
<div className="flex items-center justify-between p-3 border rounded-lg"> <div className="flex items-center gap-3"> <Info className="w-5 h-5 text-blue-600" /> <div> <p className="text-sm">Daily Reports</p> <p className="text-xs text-gray-600"> Performance summaries, growth updates </p> </div> </div> <Switch defaultChecked /> </div>
<div className="flex items-center justify-between p-3 border rounded-lg"> <div className="flex items-center gap-3"> <Info className="w-5 h-5 text-green-600" /> <div> <p className="text-sm">Scheduled Tasks</p> <p className="text-xs text-gray-600"> Feeding reminders, sampling schedules </p> </div> </div> <Switch defaultChecked /> </div> </CardContent> </Card>
<Card> <CardHeader> <CardTitle className="text-sm">Quiet Hours</CardTitle> <p className="text-xs text-gray-600"> Set times when non-critical notifications are paused </p> </CardHeader> <CardContent> <div className="flex items-center justify-between p-3 border rounded-lg"> <div> <p className="text-sm">Enable Quiet Hours</p> <p className="text-xs text-gray-600">10:00 PM - 7:00 AM</p> </div> <Switch /> </div> <p className="text-xs text-gray-600 mt-3"> Note: Critical alerts will always be delivered immediately </p> </CardContent> </Card>
<div className="flex justify-end"> <Button>Save Preferences</Button> </div> </TabsContent> </Tabs> </div> );}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401import { useCallback, useEffect, useMemo, useState } from 'react';import { Card, CardContent, CardHeader, CardTitle } from './ui/card';import { Button } from './ui/button';import { Badge } from './ui/badge';import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from './ui/dialog';import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,} from './ui/alert-dialog';import { Input } from './ui/input';import { Label } from './ui/label';import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from './ui/select';import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from './ui/table';import { CreateMedicineOrderDialog, MedicineOrderFormItem } from './procurement/CreateMedicineOrderDialog';import { ShoppingCart, Users, Plus, CheckCircle, Clock, XCircle, Fish as FishIcon, Wheat, Loader2, Truck, Search, PackageCheck,} from 'lucide-react';import { User, Farm } from '../types';import { mockFarms } from '../mockData';import { getFishTypes } from '../services/fishTypesApi';import { getFoodTypes } from '../services/foodTypesApi';import { createFeedPurchaseOrder, createFishPurchaseOrder, createMedicinePurchaseOrder, createProcurementSupplier, FeedPurchaseOrderRecord, FishPurchaseOrderRecord, formatProcurementStatusLabel, getFeedPurchaseOrders, getFishPurchaseOrders, getMedicinePurchaseOrderById, getMedicinePurchaseOrders, getProcurementSuppliers, MedicinePurchaseOrderRecord, normalizeProcurementStatus, ProcurementSupplierRecord, updateFeedPurchaseOrderDeliveryStatus, updateFeedPurchaseOrderItemStatus, updateFeedPurchaseOrderStatus, updateFishPurchaseOrderItemStatus, updateFishPurchaseOrderStatus, updateMedicinePurchaseOrderDeliveryStatus, updateMedicinePurchaseOrderItemStatus, updateMedicinePurchaseOrderStatus,} from '../services/procurementApi';import { canReceiveByDeliveryStatus, formatCurrencyEgp, formatFishCount, formatKg, formatNameWithId, getProcurementStatusColorClass, normalizeProcurementUiStatus, toShortId,} from '../services/procurementUi';
interface ProcurementProps { user: User; selectedFarm: Farm | null;}
interface FeedOrderFormItem { foodTypeId: string; quantityKg: number; unitCost: number;}
interface FishOrderFormItem { fishTypeId: string; quantity: number; unitCost: number;}
interface ReceiveDialogItem { id: string; label: string; typeId?: string; orderedQuantity: number; actualQuantity: number; unit: 'kg' | 'fish';}
interface ReceiveDialogState { kind: 'feed' | 'fish'; orderId: string; orderNumber: string; supplierName: string; location: string; items: ReceiveDialogItem[];}
interface ConfirmationDialogState { open: boolean; title: string; description: string; successMessage: string; action: null | (() => Promise<void>);}
interface DetailsDialogState { kind: 'feed' | 'fish' | 'medicine'; order: FeedPurchaseOrderRecord | FishPurchaseOrderRecord | MedicinePurchaseOrderRecord;}
const PAGE_SIZE = 5;const DEFAULT_RECEIVING_LOCATION = 'RECEIVING_AREA';
const SUPPLIER_ITEM_TYPE_OPTIONS = ['FOOD', 'FEED', 'FISH', 'FINGERLINGS', 'MEDICINE', 'EQUIPMENT'];const ORDER_STATUS_FILTER_OPTIONS = [ { value: 'ALL', label: 'All Statuses' }, { value: 'PENDING', label: 'Pending' }, { value: 'APPROVED', label: 'Approved' }, { value: 'SHIPPED', label: 'Shipped' }, { value: 'DELIVERED', label: 'Delivered' }, { value: 'RECEIVED', label: 'Received' }, { value: 'PARTIALLY_RECEIVED', label: 'Partially Received' }, { value: 'CANCELED', label: 'Canceled' }, { value: 'REJECTED', label: 'Rejected' },];const LINE_ITEM_STATUS_OPTIONS = ORDER_STATUS_FILTER_OPTIONS.filter((option) => option.value !== 'ALL');
const createFeedOrderItem = (): FeedOrderFormItem => ({ foodTypeId: '', quantityKg: 0, unitCost: 0,});
const createFishOrderItem = (): FishOrderFormItem => ({ fishTypeId: '', quantity: 0, unitCost: 0,});
const createMedicineOrderItem = (): MedicineOrderFormItem => ({ medicine: '', company: '', fishTypeIds: [], quantity: 0, unitCost: 0,});
const normalizeErrorMessage = (error: unknown): string => { if (error instanceof Error && error.message.trim()) { return error.message; } return 'Unexpected error while processing procurement request.';};
const normalizeStatusFilterValue = (status: string): string => { const normalized = normalizeProcurementUiStatus(status); if (normalized === 'CANCELLED') { return 'CANCELED'; } return normalized;};
const matchesStatusFilter = (statusFilter: string, ...statuses: Array<string | undefined>): boolean => { if (statusFilter === 'ALL') { return true; }
const candidates = statuses .filter((value): value is string => Boolean(value)) .map((value) => normalizeStatusFilterValue(value));
if (statusFilter === 'CANCELED') { return candidates.includes('CANCELED') || candidates.includes('CANCELLED'); }
return candidates.includes(statusFilter);};
const looksLikeEntityId = (value: string): boolean => /^[0-9a-f]{8}(?:-[0-9a-f]{4}){0,4}$/i.test(value.trim());
const getUserInitials = (name: string): string => name .split(' ') .filter(Boolean) .map((part) => part[0]) .join('') .toUpperCase();
const getStatusIcon = (status: string) => { switch (normalizeProcurementStatus(status)) { case 'DELIVERED': case 'RECEIVED': case 'APPROVED': return <CheckCircle className="w-4 h-4" />; case 'PENDING': case 'SHIPPED': case 'PARTIALLY_RECEIVED': return <Clock className="w-4 h-4" />; case 'CANCELLED': case 'CANCELED': case 'REJECTED': case 'RETURNED': return <XCircle className="w-4 h-4" />; default: return <Clock className="w-4 h-4" />; }};
export default function Procurement({ user, selectedFarm }: ProcurementProps) { const currentFarm = selectedFarm || mockFarms[0];
const [activeTab, setActiveTab] = useState('feed-orders'); const [loading, setLoading] = useState(true); const [submitting, setSubmitting] = useState(false); const [errorMessage, setErrorMessage] = useState<string | null>(null); const [inventoryFeedback, setInventoryFeedback] = useState<string | null>(null);
const [feedOrders, setFeedOrders] = useState<FeedPurchaseOrderRecord[]>([]); const [fishOrders, setFishOrders] = useState<FishPurchaseOrderRecord[]>([]); const [medicineOrders, setMedicineOrders] = useState<MedicinePurchaseOrderRecord[]>([]); const [suppliers, setSuppliers] = useState<ProcurementSupplierRecord[]>([]);
const [foodTypes, setFoodTypes] = useState<Array<{ id: string; name: string }>>([]); const [fishTypes, setFishTypes] = useState<Array<{ id: string; name: string }>>([]);
const [showCreateFeedOrder, setShowCreateFeedOrder] = useState(false); const [showCreateFishOrder, setShowCreateFishOrder] = useState(false); const [showCreateMedicineOrder, setShowCreateMedicineOrder] = useState(false); const [showCreateSupplier, setShowCreateSupplier] = useState(false);
const [feedStatusFilter, setFeedStatusFilter] = useState('ALL'); const [fishStatusFilter, setFishStatusFilter] = useState('ALL'); const [medicineStatusFilter, setMedicineStatusFilter] = useState('ALL'); const [medicineSupplierSearchTerm, setMedicineSupplierSearchTerm] = useState(''); const [supplierSearchTerm, setSupplierSearchTerm] = useState(''); const [feedPage, setFeedPage] = useState(1); const [fishPage, setFishPage] = useState(1); const [medicinePage, setMedicinePage] = useState(1);
const [feedOrderSupplierId, setFeedOrderSupplierId] = useState(''); const [feedOrderItems, setFeedOrderItems] = useState<FeedOrderFormItem[]>([createFeedOrderItem()]);
const [fishOrderSupplierId, setFishOrderSupplierId] = useState(''); const [fishOrderItems, setFishOrderItems] = useState<FishOrderFormItem[]>([createFishOrderItem()]);
const [medicineOrderSupplierId, setMedicineOrderSupplierId] = useState(''); const [medicineOrderItems, setMedicineOrderItems] = useState<MedicineOrderFormItem[]>([createMedicineOrderItem()]);
const [supplierName, setSupplierName] = useState(''); const [supplierEmail, setSupplierEmail] = useState(''); const [supplierPhone, setSupplierPhone] = useState(''); const [supplierAddress, setSupplierAddress] = useState(''); const [supplierItemTypes, setSupplierItemTypes] = useState<string[]>(['FOOD']);
const [detailsDialog, setDetailsDialog] = useState<DetailsDialogState | null>(null); const [lineItemStatusDrafts, setLineItemStatusDrafts] = useState<Record<string, string>>({}); const [updatingLineItemId, setUpdatingLineItemId] = useState<string | null>(null); const [receiveDialog, setReceiveDialog] = useState<ReceiveDialogState | null>(null); const [confirmationDialog, setConfirmationDialog] = useState<ConfirmationDialogState>({ open: false, title: '', description: '', successMessage: '', action: null, });
const feedOrderTotal = useMemo( () => feedOrderItems.reduce((sum, item) => sum + item.quantityKg * item.unitCost, 0), [feedOrderItems], );
const fishOrderTotal = useMemo( () => fishOrderItems.reduce((sum, item) => sum + item.quantity * item.unitCost, 0), [fishOrderItems], );
const medicineOrderTotal = useMemo( () => medicineOrderItems.reduce((sum, item) => sum + item.quantity * item.unitCost, 0), [medicineOrderItems], );
const feedSuppliers = useMemo( () => suppliers.filter((supplier) => supplier.items.includes('FOOD') || supplier.items.includes('FEED')), [suppliers], );
const fishSuppliers = useMemo( () => suppliers.filter((supplier) => supplier.items.includes('FISH') || supplier.items.includes('FINGERLINGS')), [suppliers], );
const medicineSuppliers = useMemo( () => suppliers.filter((supplier) => supplier.items.includes('MEDICINE')), [suppliers], );
const filteredSuppliers = useMemo(() => { const query = supplierSearchTerm.trim().toLowerCase(); if (!query) { return suppliers; }
return suppliers.filter((supplier) => { const haystack = [ supplier.name, supplier.id, supplier.email, supplier.phoneNumber, supplier.address, supplier.items.join(' '), ] .filter((value): value is string => Boolean(value)) .join(' ') .toLowerCase();
return haystack.includes(query); }); }, [supplierSearchTerm, suppliers]);
const filteredFeedOrders = useMemo( () => feedOrders.filter((order) => matchesStatusFilter(feedStatusFilter, order.status, order.deliveryStatus)), [feedOrders, feedStatusFilter], );
const filteredFishOrders = useMemo( () => fishOrders.filter((order) => matchesStatusFilter(fishStatusFilter, order.status)), [fishOrders, fishStatusFilter], );
const filteredMedicineOrders = useMemo(() => { const supplierQuery = medicineSupplierSearchTerm.trim().toLowerCase(); return medicineOrders.filter((order) => { const matchesStatus = matchesStatusFilter( medicineStatusFilter, order.status, order.deliveryStatus, ); if (!matchesStatus) { return false; }
if (!supplierQuery) { return true; }
return order.supplierName.toLowerCase().includes(supplierQuery); }); }, [medicineOrders, medicineStatusFilter, medicineSupplierSearchTerm]);
const feedPageCount = Math.max(1, Math.ceil(filteredFeedOrders.length / PAGE_SIZE)); const fishPageCount = Math.max(1, Math.ceil(filteredFishOrders.length / PAGE_SIZE)); const medicinePageCount = Math.max(1, Math.ceil(filteredMedicineOrders.length / PAGE_SIZE));
const paginatedFeedOrders = useMemo(() => { const start = (feedPage - 1) * PAGE_SIZE; return filteredFeedOrders.slice(start, start + PAGE_SIZE); }, [feedPage, filteredFeedOrders]);
const paginatedFishOrders = useMemo(() => { const start = (fishPage - 1) * PAGE_SIZE; return filteredFishOrders.slice(start, start + PAGE_SIZE); }, [fishPage, filteredFishOrders]);
const paginatedMedicineOrders = useMemo(() => { const start = (medicinePage - 1) * PAGE_SIZE; return filteredMedicineOrders.slice(start, start + PAGE_SIZE); }, [medicinePage, filteredMedicineOrders]);
useEffect(() => { setFeedPage(1); }, [feedStatusFilter]);
useEffect(() => { setFishPage(1); }, [fishStatusFilter]);
useEffect(() => { setMedicinePage(1); }, [medicineStatusFilter, medicineSupplierSearchTerm]);
useEffect(() => { if (feedPage > feedPageCount) { setFeedPage(feedPageCount); } }, [feedPage, feedPageCount]);
useEffect(() => { if (fishPage > fishPageCount) { setFishPage(fishPageCount); } }, [fishPage, fishPageCount]);
useEffect(() => { if (medicinePage > medicinePageCount) { setMedicinePage(medicinePageCount); } }, [medicinePage, medicinePageCount]);
const loadProcurementData = useCallback(async () => { setLoading(true); setErrorMessage(null);
try { const [feedOrdersData, fishOrdersData, medicineOrdersData, suppliersData, foodTypesData, fishTypesData] = await Promise.all([ getFeedPurchaseOrders({ offset: 0, limit: 200 }), getFishPurchaseOrders({ offset: 0, limit: 200 }), getMedicinePurchaseOrders({ offset: 0, limit: 200 }), getProcurementSuppliers(), getFoodTypes(), getFishTypes(false), ]);
const supplierNamesById = new Map(suppliersData.map((supplier) => [supplier.id, supplier.name])); const resolveOrderSupplierNames = <T extends { supplierId?: string; supplierName: string }>(orders: T[]): T[] => orders.map((order) => { const fallbackName = order.supplierId ? supplierNamesById.get(order.supplierId) : undefined; const normalizedSupplierName = order.supplierName.trim().toLowerCase(); const shouldFallback = normalizedSupplierName === 'unknown supplier' || looksLikeEntityId(order.supplierName);
if (!fallbackName || !shouldFallback) { return order; }
return { ...order, supplierName: fallbackName, }; });
setFeedOrders(resolveOrderSupplierNames(feedOrdersData)); setFishOrders(resolveOrderSupplierNames(fishOrdersData)); setMedicineOrders(resolveOrderSupplierNames(medicineOrdersData)); setSuppliers(suppliersData); setFoodTypes(foodTypesData.map((foodType) => ({ id: foodType.id, name: foodType.name }))); setFishTypes(fishTypesData.map((fishType) => ({ id: fishType.id, name: fishType.name }))); } catch (error) { setErrorMessage(normalizeErrorMessage(error)); } finally { setLoading(false); } }, []);
useEffect(() => { void loadProcurementData(); }, [loadProcurementData]);
useEffect(() => { if (!detailsDialog) { setLineItemStatusDrafts({}); return; }
const items = detailsDialog.kind === 'feed' ? (detailsDialog.order as FeedPurchaseOrderRecord).items : detailsDialog.kind === 'fish' ? (detailsDialog.order as FishPurchaseOrderRecord).items : (detailsDialog.order as MedicinePurchaseOrderRecord).items;
const nextDrafts = items.reduce<Record<string, string>>((accumulator, item) => { accumulator[item.id] = normalizeProcurementUiStatus(item.status); return accumulator; }, {});
setLineItemStatusDrafts(nextDrafts); }, [detailsDialog]);
const handleOrderAction = async (action: () => Promise<void>, successMessage: string) => { try { setSubmitting(true); await action(); await loadProcurementData(); window.alert(successMessage); } catch (error) { window.alert(normalizeErrorMessage(error)); } finally { setSubmitting(false); } };
const updateLineItemStatusDraft = (itemId: string, status: string) => { setLineItemStatusDrafts((previous) => ({ ...previous, [itemId]: normalizeProcurementUiStatus(status), })); };
const submitLineItemStatus = async ( itemId: string, currentStatus: string, kind: 'feed' | 'fish' | 'medicine', orderId: string, ) => { const nextStatus = normalizeProcurementUiStatus(lineItemStatusDrafts[itemId] || currentStatus); if (nextStatus === normalizeProcurementUiStatus(currentStatus)) { return; }
try { setSubmitting(true); setUpdatingLineItemId(itemId);
if (kind === 'feed') { await updateFeedPurchaseOrderItemStatus(orderId, itemId, nextStatus); } else if (kind === 'fish') { await updateFishPurchaseOrderItemStatus(orderId, itemId, nextStatus); } else { await updateMedicinePurchaseOrderItemStatus(orderId, itemId, nextStatus); }
setDetailsDialog(null); await loadProcurementData(); window.alert('Line item status updated successfully.'); } catch (error) { window.alert(normalizeErrorMessage(error)); } finally { setUpdatingLineItemId(null); setSubmitting(false); } };
const openConfirmationDialog = ( title: string, description: string, successMessage: string, action: () => Promise<void>, ) => { setConfirmationDialog({ open: true, title, description, successMessage, action, }); };
const runConfirmationAction = async () => { if (!confirmationDialog.action) { return; }
try { setSubmitting(true); await confirmationDialog.action(); await loadProcurementData(); setConfirmationDialog({ open: false, title: '', description: '', successMessage: '', action: null, }); window.alert(confirmationDialog.successMessage); } catch (error) { window.alert(normalizeErrorMessage(error)); } finally { setSubmitting(false); } };
const resetFeedOrderForm = () => { setFeedOrderSupplierId(''); setFeedOrderItems([createFeedOrderItem()]); };
const resetFishOrderForm = () => { setFishOrderSupplierId(''); setFishOrderItems([createFishOrderItem()]); };
const resetMedicineOrderForm = () => { setMedicineOrderSupplierId(''); setMedicineOrderItems([createMedicineOrderItem()]); };
const resetSupplierForm = () => { setSupplierName(''); setSupplierEmail(''); setSupplierPhone(''); setSupplierAddress(''); setSupplierItemTypes(['FOOD']); };
const handleCreateFeedOrder = async () => { if (!feedOrderSupplierId) { window.alert('Please select a supplier.'); return; }
const validItems = feedOrderItems.filter( (item) => item.foodTypeId && item.quantityKg > 0 && item.unitCost > 0, );
if (validItems.length === 0) { window.alert('Please add at least one valid feed item.'); return; }
try { setSubmitting(true); await createFeedPurchaseOrder({ supplierId: feedOrderSupplierId, items: validItems.map((item) => ({ foodTypeId: item.foodTypeId, quantityKg: item.quantityKg, unitCost: item.unitCost, })), });
setShowCreateFeedOrder(false); resetFeedOrderForm(); await loadProcurementData(); window.alert('Feed purchase order created successfully.'); } catch (error) { window.alert(normalizeErrorMessage(error)); } finally { setSubmitting(false); } };
const handleCreateFishOrder = async () => { if (!fishOrderSupplierId) { window.alert('Please select a supplier.'); return; }
const validItems = fishOrderItems.filter( (item) => item.fishTypeId && item.quantity > 0 && item.unitCost > 0, );
if (validItems.length === 0) { window.alert('Please add at least one valid fish item.'); return; }
try { setSubmitting(true); await createFishPurchaseOrder({ supplierId: fishOrderSupplierId, items: validItems.map((item) => ({ fishTypeId: item.fishTypeId, quantity: item.quantity, totalCost: item.quantity * item.unitCost, })), });
setShowCreateFishOrder(false); resetFishOrderForm(); await loadProcurementData(); window.alert('Fish purchase order created successfully.'); } catch (error) { window.alert(normalizeErrorMessage(error)); } finally { setSubmitting(false); } };
const handleCreateMedicineOrder = async () => { if (!medicineOrderSupplierId) { window.alert('Please select a supplier.'); return; }
const validItems = medicineOrderItems.filter( (item) => item.medicine.trim() && item.company.trim() && item.fishTypeIds.length > 0 && item.quantity > 0 && item.unitCost > 0, );
if (validItems.length === 0) { window.alert('Please add at least one valid medicine item.'); return; }
if (validItems.length !== medicineOrderItems.length) { window.alert('All medicine line items must include medicine, company, fish types, quantity, and unit cost.'); return; }
try { setSubmitting(true); await createMedicinePurchaseOrder({ supplierId: medicineOrderSupplierId, items: validItems.map((item) => ({ medicine: item.medicine.trim(), company: item.company.trim(), fishTypeIds: item.fishTypeIds, quantity: item.quantity, unitCost: item.unitCost, })), });
setShowCreateMedicineOrder(false); resetMedicineOrderForm(); await loadProcurementData(); window.alert('Medicine purchase order created successfully.'); } catch (error) { window.alert(normalizeErrorMessage(error)); } finally { setSubmitting(false); } };
const toggleSupplierItemType = (value: string) => { setSupplierItemTypes((previous) => previous.includes(value) ? previous.filter((entry) => entry !== value) : [...previous, value], ); };
const handleCreateSupplier = async () => { if (!supplierName.trim()) { window.alert('Supplier name is required.'); return; }
if (supplierItemTypes.length === 0) { window.alert('Please select at least one supplied item type.'); return; }
try { setSubmitting(true); await createProcurementSupplier({ name: supplierName.trim(), email: supplierEmail.trim() || undefined, phoneNumber: supplierPhone.trim() || undefined, address: supplierAddress.trim() || undefined, items: supplierItemTypes, });
setShowCreateSupplier(false); resetSupplierForm(); await loadProcurementData(); window.alert('Supplier created successfully.'); } catch (error) { window.alert(normalizeErrorMessage(error)); } finally { setSubmitting(false); } };
const isFeedOrderDeliverable = (order: FeedPurchaseOrderRecord): boolean => canReceiveByDeliveryStatus(order.deliveryStatus || order.status);
const isFishOrderDeliverable = (order: FishPurchaseOrderRecord): boolean => canReceiveByDeliveryStatus(order.status);
const openReceiveDialogForFeedOrder = (order: FeedPurchaseOrderRecord) => { setReceiveDialog({ kind: 'feed', orderId: order.id, orderNumber: order.orderNumber, supplierName: order.supplierName, location: DEFAULT_RECEIVING_LOCATION, items: order.items.map((item) => ({ id: item.id, label: item.foodTypeName || 'Unknown food type', typeId: item.foodTypeId, orderedQuantity: item.quantityKg, actualQuantity: item.actualQuantityKg ?? item.quantityKg, unit: 'kg', })), }); };
const openReceiveDialogForFishOrder = (order: FishPurchaseOrderRecord) => { setReceiveDialog({ kind: 'fish', orderId: order.id, orderNumber: order.orderNumber, supplierName: order.supplierName, location: DEFAULT_RECEIVING_LOCATION, items: order.items.map((item) => ({ id: item.id, label: item.fishTypeName || 'Unknown fish type', typeId: item.fishTypeId, orderedQuantity: item.quantity, actualQuantity: item.actualQuantity ?? item.quantity, unit: 'fish', })), }); };
const openMedicineOrderDetails = async (order: MedicinePurchaseOrderRecord) => { try { setSubmitting(true); const latestOrder = await getMedicinePurchaseOrderById(order.id); const resolvedLatestOrder = latestOrder ? { ...latestOrder, supplierName: latestOrder.supplierName.trim().toLowerCase() === 'unknown supplier' || looksLikeEntityId(latestOrder.supplierName) ? order.supplierName : latestOrder.supplierName, } : order; setDetailsDialog({ kind: 'medicine', order: resolvedLatestOrder, }); } catch (error) { window.alert(normalizeErrorMessage(error)); } finally { setSubmitting(false); } };
const updateReceiveDialogItem = (itemId: string, actualQuantity: number) => { setReceiveDialog((previous) => { if (!previous) { return previous; }
return { ...previous, items: previous.items.map((item) => item.id === itemId ? { ...item, actualQuantity: Math.max(0, actualQuantity) } : item, ), }; }); };
const submitReceiving = async () => { if (!receiveDialog) { return; }
const itemsToSubmit = receiveDialog.items.filter((item) => item.orderedQuantity > 0); if (itemsToSubmit.length === 0) { window.alert('No receivable items found for this order.'); return; }
try { setSubmitting(true);
const requests = itemsToSubmit.map((item) => { let nextStatus = 'REJECTED'; if (item.actualQuantity >= item.orderedQuantity) { nextStatus = 'RECEIVED'; } else if (item.actualQuantity > 0 && item.actualQuantity < item.orderedQuantity) { nextStatus = 'PARTIALLY_RECEIVED'; }
if (receiveDialog.kind === 'feed') { return updateFeedPurchaseOrderItemStatus(receiveDialog.orderId, item.id, nextStatus, { actualQuantityKg: item.actualQuantity, receiptLocation: receiveDialog.location, }); }
return updateFishPurchaseOrderItemStatus(receiveDialog.orderId, item.id, nextStatus, { actualQuantity: item.actualQuantity, receiptLocation: receiveDialog.location, }); });
await Promise.all(requests); const totalReceived = itemsToSubmit.reduce((sum, item) => sum + item.actualQuantity, 0); const quantityUnit = receiveDialog.kind === 'feed' ? 'kg' : 'fish';
setReceiveDialog(null); setInventoryFeedback( `Receipt posted: ${totalReceived.toLocaleString()} ${quantityUnit} moved to ${receiveDialog.location}.`, ); await loadProcurementData(); } catch (error) { window.alert(normalizeErrorMessage(error)); } finally { setSubmitting(false); } };
if (loading) { return ( <div className="min-h-screen bg-[#F9FAFB] flex items-center justify-center"> <div className="flex items-center gap-2 text-gray-700"> <Loader2 className="w-5 h-5 animate-spin" /> <span>Loading procurement data...</span> </div> </div> ); }
return ( <div className="min-h-screen bg-[#F9FAFB]"> <div className="bg-[#0A4D68] text-white px-6 py-4"> <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> <ShoppingCart className="w-6 h-6" /> <span className="text-xl font-semibold">Procurement</span> </div> <div className="flex items-center gap-4"> <span className="text-sm">{currentFarm.name}</span> <div className="w-10 h-10 rounded-full bg-[#088395] flex items-center justify-center font-semibold"> {getUserInitials(user.name)} </div> </div> </div> </div>
<div className="p-6 space-y-6"> {errorMessage && ( <Card className="bg-red-50 border-red-200"> <CardContent className="p-4 text-sm text-red-700 flex items-center justify-between gap-2"> <span>{errorMessage}</span> <Button variant="outline" size="sm" onClick={() => void loadProcurementData()}> Retry </Button> </CardContent> </Card> )}
{inventoryFeedback && ( <Card className="bg-green-50 border-green-200"> <CardContent className="p-4 text-sm text-green-800 flex items-center justify-between gap-2"> <div className="flex items-center gap-2"> <PackageCheck className="w-4 h-4" /> <span>{inventoryFeedback}</span> </div> <Button variant="outline" size="sm" onClick={() => setInventoryFeedback(null)}> Dismiss </Button> </CardContent> </Card> )}
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4"> <TabsList className="bg-white"> <TabsTrigger value="feed-orders">Feed Orders</TabsTrigger> <TabsTrigger value="fish-orders">Fish Orders</TabsTrigger> <TabsTrigger value="medicine-orders">Medicine Orders</TabsTrigger> <TabsTrigger value="suppliers">Suppliers</TabsTrigger> </TabsList>
<TabsContent value="feed-orders" className="space-y-4"> <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4"> <div> <h2 className="text-2xl font-semibold">Feed Purchase Orders</h2> <p className="text-sm text-gray-600 mt-1"> Showing {filteredFeedOrders.length} order(s), page {feedPage} of {feedPageCount} </p> </div>
<div className="flex flex-col sm:flex-row items-stretch sm:items-end gap-3"> <div className="space-y-1"> <Label htmlFor="feed-status-filter" className="text-xs text-gray-600"> Feed order status filter </Label> <select id="feed-status-filter" className="h-10 rounded-md border border-gray-300 px-3 text-sm bg-white" value={feedStatusFilter} onChange={(event) => setFeedStatusFilter(event.target.value)} > {ORDER_STATUS_FILTER_OPTIONS.map((option) => ( <option key={`feed-filter-${option.value}`} value={option.value}> {option.label} </option> ))} </select> </div>
<Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => setShowCreateFeedOrder(true)} disabled={submitting} > <Plus className="w-4 h-4 mr-2" /> New Feed Order </Button> </div> </div>
<div className="space-y-4"> {paginatedFeedOrders.map((order) => ( <Card key={order.id} className="bg-white shadow-sm"> <CardHeader className="pb-3"> <div className="flex items-center justify-between gap-4"> <div> <div className="flex items-center gap-2 flex-wrap"> <CardTitle className="text-lg">{order.orderNumber}</CardTitle> <Badge variant="outline" className="text-xs">ID: {toShortId(order.id)}</Badge> </div> <p className="text-sm text-gray-600 mt-2"> Supplier: {formatNameWithId(order.supplierName, order.supplierId)} </p> <p className="text-xs text-gray-500 mt-1"> Order Date: {order.orderDate ? new Date(order.orderDate).toLocaleDateString() : 'N/A'} </p> </div>
<div className="text-right"> <p className="text-2xl font-bold text-[#0A4D68]">{formatCurrencyEgp(order.totalCost)}</p> {order.deliveryDate && ( <p className="text-xs text-gray-500"> Delivery: {new Date(order.deliveryDate).toLocaleDateString()} </p> )} </div> </div> </CardHeader>
<CardContent> <div className="space-y-2"> <p className="text-sm font-medium text-gray-700">Items:</p> {order.items.map((item) => ( <div key={item.id} className="bg-gray-50 p-3 rounded-lg"> <div className="flex items-center justify-between gap-2"> <div className="flex-1"> <p className="font-medium text-sm"> {formatNameWithId(item.foodTypeName || 'Unknown food type', item.foodTypeId)} </p> <div className="flex items-center gap-4 text-xs text-gray-600 mt-1 flex-wrap"> <span> Ordered: {formatKg(item.quantityKg)} @ {formatCurrencyEgp(item.unitCost)}/kg </span> <span>Line ID: {toShortId(item.id)}</span> {item.actualQuantityKg !== undefined && ( <span className={ item.actualQuantityKg < item.quantityKg ? 'text-yellow-700' : 'text-green-700' } > Actual: {formatKg(item.actualQuantityKg)} </span> )} </div> </div> <Badge className={`${getProcurementStatusColorClass(item.status)} text-xs`}> {formatProcurementStatusLabel(item.status)} </Badge> </div> </div> ))} </div>
<div className="flex gap-2 mt-4 flex-wrap"> <Button size="sm" variant="outline" onClick={() => setDetailsDialog({ kind: 'feed', order })}> View Details </Button>
{normalizeProcurementStatus(order.status) === 'PENDING' && ( <> <Button size="sm" className="bg-[#10B981] hover:bg-[#059669]" onClick={() => openConfirmationDialog( 'Approve Feed Order', `Approve ${order.orderNumber} for ${order.supplierName}?`, 'Feed order approved.', () => updateFeedPurchaseOrderStatus(order.id, 'APPROVED'), ) } disabled={submitting} > Approve </Button> <Button size="sm" variant="destructive" onClick={() => openConfirmationDialog( 'Cancel Feed Order', `Cancel ${order.orderNumber} for ${order.supplierName}?`, 'Feed order canceled.', () => updateFeedPurchaseOrderStatus(order.id, 'CANCELED'), ) } disabled={submitting} > Cancel </Button> </> )}
<Button size="sm" variant="outline" onClick={() => void handleOrderAction( () => updateFeedPurchaseOrderDeliveryStatus(order.id, 'SHIPPED'), 'Delivery status updated to shipped.', ) } disabled={submitting} > Mark Shipped </Button>
<Button size="sm" variant="outline" onClick={() => void handleOrderAction( () => updateFeedPurchaseOrderDeliveryStatus(order.id, 'DELIVERED'), 'Delivery status updated to delivered.', ) } disabled={submitting} > Mark Delivered </Button>
<Button size="sm" variant="outline" disabled={!isFeedOrderDeliverable(order) || submitting} onClick={() => openReceiveDialogForFeedOrder(order)} > Receive Items </Button> </div> </CardContent> </Card> ))}
{filteredFeedOrders.length === 0 && ( <Card className="bg-white shadow-sm"> <CardContent className="p-8 text-center text-gray-600">No feed purchase orders found.</CardContent> </Card> )}
{filteredFeedOrders.length > 0 && ( <div className="flex items-center justify-between rounded-lg border bg-white p-3"> <p className="text-sm text-gray-600"> Page {feedPage} of {feedPageCount} </p> <div className="flex gap-2"> <Button size="sm" variant="outline" disabled={feedPage <= 1} aria-label="Previous feed page" onClick={() => setFeedPage((previous) => Math.max(1, previous - 1))} > Previous </Button> <Button size="sm" variant="outline" disabled={feedPage >= feedPageCount} aria-label="Next feed page" onClick={() => setFeedPage((previous) => Math.min(feedPageCount, previous + 1))} > Next </Button> </div> </div> )} </div> </TabsContent>
<TabsContent value="fish-orders" className="space-y-4"> <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4"> <div> <h2 className="text-2xl font-semibold">Fish Purchase Orders</h2> <p className="text-sm text-gray-600 mt-1"> Showing {filteredFishOrders.length} order(s), page {fishPage} of {fishPageCount} </p> </div>
<div className="flex flex-col sm:flex-row items-stretch sm:items-end gap-3"> <div className="space-y-1"> <Label htmlFor="fish-status-filter" className="text-xs text-gray-600"> Fish order status filter </Label> <select id="fish-status-filter" className="h-10 rounded-md border border-gray-300 px-3 text-sm bg-white" value={fishStatusFilter} onChange={(event) => setFishStatusFilter(event.target.value)} > {ORDER_STATUS_FILTER_OPTIONS.map((option) => ( <option key={`fish-filter-${option.value}`} value={option.value}> {option.label} </option> ))} </select> </div>
<Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => setShowCreateFishOrder(true)} disabled={submitting} > <Plus className="w-4 h-4 mr-2" /> New Fish Order </Button> </div> </div>
<div className="space-y-4"> {paginatedFishOrders.map((order) => ( <Card key={order.id} className="bg-white shadow-sm"> <CardHeader className="pb-3"> <div className="flex items-center justify-between gap-4"> <div> <div className="flex items-center gap-2 flex-wrap"> <CardTitle className="text-lg">{order.orderNumber}</CardTitle> <Badge variant="outline" className="text-xs">ID: {toShortId(order.id)}</Badge> <Badge className={getProcurementStatusColorClass(order.status)}> {getStatusIcon(order.status)} <span className="ml-1">{formatProcurementStatusLabel(order.status)}</span> </Badge> </div> <p className="text-sm text-gray-600 mt-2"> Supplier: {formatNameWithId(order.supplierName, order.supplierId)} </p> <p className="text-xs text-gray-500 mt-1"> Order Date: {order.orderDate ? new Date(order.orderDate).toLocaleDateString() : 'N/A'} </p> </div>
<div className="text-right"> <p className="text-2xl font-bold text-[#0A4D68]">{formatCurrencyEgp(order.totalCost)}</p> {order.deliveryDate && ( <p className="text-xs text-gray-500"> Delivery: {new Date(order.deliveryDate).toLocaleDateString()} </p> )} </div> </div> </CardHeader> <CardContent> <div className="space-y-2"> <p className="text-sm font-medium text-gray-700">Items:</p> {order.items.map((item) => ( <div key={item.id} className="bg-gray-50 p-3 rounded-lg"> <div className="flex items-center justify-between gap-2"> <div className="flex-1"> <p className="font-medium text-sm"> {formatNameWithId(item.fishTypeName || 'Unknown fish type', item.fishTypeId)} </p> <div className="flex items-center gap-4 text-xs text-gray-600 mt-1 flex-wrap"> <span>Ordered: {formatFishCount(item.quantity)}</span> <span>Line ID: {toShortId(item.id)}</span> {item.actualQuantity !== undefined && ( <span className={item.actualQuantity < item.quantity ? 'text-yellow-700' : 'text-green-700'} > Actual: {formatFishCount(item.actualQuantity)} </span> )} <span>Cost: {formatCurrencyEgp(item.totalCost)}</span> </div> </div> <Badge className={`${getProcurementStatusColorClass(item.status)} text-xs`}> {formatProcurementStatusLabel(item.status)} </Badge> </div> </div> ))} </div>
<div className="flex gap-2 mt-4 flex-wrap"> <Button size="sm" variant="outline" onClick={() => setDetailsDialog({ kind: 'fish', order })}> View Details </Button>
{normalizeProcurementStatus(order.status) === 'PENDING' && ( <> <Button size="sm" className="bg-[#10B981] hover:bg-[#059669]" onClick={() => openConfirmationDialog( 'Approve Fish Order', `Approve ${order.orderNumber} for ${order.supplierName}?`, 'Fish order approved.', () => updateFishPurchaseOrderStatus(order.id, 'APPROVED'), ) } disabled={submitting} > Approve </Button> <Button size="sm" variant="destructive" onClick={() => openConfirmationDialog( 'Cancel Fish Order', `Cancel ${order.orderNumber} for ${order.supplierName}?`, 'Fish order canceled.', () => updateFishPurchaseOrderStatus(order.id, 'CANCELED'), ) } disabled={submitting} > Cancel </Button> </> )}
<Button size="sm" variant="outline" disabled={!isFishOrderDeliverable(order) || submitting} onClick={() => openReceiveDialogForFishOrder(order)} > Receive Items </Button> </div> </CardContent> </Card> ))}
{filteredFishOrders.length === 0 && ( <Card className="bg-white shadow-sm"> <CardContent className="p-8 text-center text-gray-600">No fish purchase orders found.</CardContent> </Card> )}
{filteredFishOrders.length > 0 && ( <div className="flex items-center justify-between rounded-lg border bg-white p-3"> <p className="text-sm text-gray-600"> Page {fishPage} of {fishPageCount} </p> <div className="flex gap-2"> <Button size="sm" variant="outline" disabled={fishPage <= 1} aria-label="Previous fish page" onClick={() => setFishPage((previous) => Math.max(1, previous - 1))} > Previous </Button> <Button size="sm" variant="outline" disabled={fishPage >= fishPageCount} aria-label="Next fish page" onClick={() => setFishPage((previous) => Math.min(fishPageCount, previous + 1))} > Next </Button> </div> </div> )} </div> </TabsContent>
<TabsContent value="medicine-orders" className="space-y-4"> <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4"> <div> <h2 className="text-2xl font-semibold">Medicine Purchase Orders</h2> <p className="text-sm text-gray-600 mt-1"> Showing {filteredMedicineOrders.length} order(s), page {medicinePage} of {medicinePageCount} </p> </div>
<div className="flex flex-col md:flex-row items-stretch md:items-end gap-3"> <div className="space-y-1"> <Label htmlFor="medicine-supplier-search" className="text-xs text-gray-600"> Search supplier </Label> <div className="relative"> <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" /> <Input id="medicine-supplier-search" aria-label="Search medicine suppliers" value={medicineSupplierSearchTerm} onChange={(event) => setMedicineSupplierSearchTerm(event.target.value)} placeholder="Search by supplier name" className="pl-8 w-full md:w-64" /> </div> </div>
<div className="space-y-1"> <Label htmlFor="medicine-status-filter" className="text-xs text-gray-600"> Status filter </Label> <select id="medicine-status-filter" className="h-10 rounded-md border border-gray-300 px-3 text-sm bg-white" value={medicineStatusFilter} onChange={(event) => setMedicineStatusFilter(event.target.value)} > {ORDER_STATUS_FILTER_OPTIONS.map((option) => ( <option key={`medicine-filter-${option.value}`} value={option.value}> {option.label} </option> ))} </select> </div>
<Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => setShowCreateMedicineOrder(true)} disabled={submitting} > <Plus className="w-4 h-4 mr-2" /> New Medicine Order </Button> </div> </div>
<Card className="bg-white shadow-sm"> <CardContent className="p-0"> <Table> <TableHeader> <TableRow> <TableHead>Order ID</TableHead> <TableHead>Supplier</TableHead> <TableHead>Date</TableHead> <TableHead>Total Cost</TableHead> <TableHead>Status</TableHead> <TableHead>Delivery Status</TableHead> <TableHead className="text-right">Actions</TableHead> </TableRow> </TableHeader> <TableBody> {paginatedMedicineOrders.map((order) => ( <TableRow key={order.id}> <TableCell> <div className="font-medium">{order.orderNumber}</div> <div className="text-xs text-gray-500">ID: {toShortId(order.id)}</div> </TableCell> <TableCell>{formatNameWithId(order.supplierName, order.supplierId)}</TableCell> <TableCell>{order.orderDate ? new Date(order.orderDate).toLocaleDateString() : 'N/A'}</TableCell> <TableCell>{formatCurrencyEgp(order.totalCost)}</TableCell> <TableCell> <Badge className={getProcurementStatusColorClass(order.status)}> {formatProcurementStatusLabel(order.status)} </Badge> </TableCell> <TableCell> <Badge className={getProcurementStatusColorClass(order.deliveryStatus || order.status)}> {formatProcurementStatusLabel(order.deliveryStatus || 'N/A')} </Badge> </TableCell> <TableCell className="text-right"> <div className="flex flex-wrap justify-end gap-2"> <Button size="sm" variant="outline" onClick={() => void openMedicineOrderDetails(order)} > Details </Button> {normalizeProcurementStatus(order.status) === 'PENDING' && ( <Button size="sm" className="bg-[#10B981] hover:bg-[#059669]" disabled={submitting} onClick={() => openConfirmationDialog( 'Approve Medicine Order', `Approve ${order.orderNumber} for ${order.supplierName}?`, 'Medicine order approved and marked delivered.', () => updateMedicinePurchaseOrderStatus(order.id, 'DELIVERED'), ) } > Approve </Button> )} <Button size="sm" variant="outline" disabled={submitting} onClick={() => void handleOrderAction( () => updateMedicinePurchaseOrderDeliveryStatus(order.id, 'SHIPPED'), 'Medicine delivery status updated to shipped.', ) } > Mark Shipped </Button> <Button size="sm" variant="outline" disabled={submitting} onClick={() => void handleOrderAction( () => updateMedicinePurchaseOrderDeliveryStatus(order.id, 'DELIVERED'), 'Medicine delivery status updated to delivered.', ) } > Mark Delivered </Button> </div> </TableCell> </TableRow> ))}
{filteredMedicineOrders.length === 0 && ( <TableRow> <TableCell colSpan={7} className="h-24 text-center text-gray-600"> No medicine purchase orders found. </TableCell> </TableRow> )} </TableBody> </Table> </CardContent> </Card>
{filteredMedicineOrders.length > 0 && ( <div className="flex items-center justify-between rounded-lg border bg-white p-3"> <p className="text-sm text-gray-600"> Page {medicinePage} of {medicinePageCount} </p> <div className="flex gap-2"> <Button size="sm" variant="outline" disabled={medicinePage <= 1} aria-label="Previous medicine page" onClick={() => setMedicinePage((previous) => Math.max(1, previous - 1))} > Previous </Button> <Button size="sm" variant="outline" disabled={medicinePage >= medicinePageCount} aria-label="Next medicine page" onClick={() => setMedicinePage((previous) => Math.min(medicinePageCount, previous + 1))} > Next </Button> </div> </div> )} </TabsContent>
<TabsContent value="suppliers" className="space-y-4"> <div className="flex flex-col lg:flex-row lg:items-end lg:justify-between gap-4"> <div> <h2 className="text-2xl font-semibold">Suppliers</h2> <p className="text-sm text-gray-600 mt-1">Manage fish/feed providers with searchable contact details.</p> </div>
<div className="flex flex-col sm:flex-row items-stretch sm:items-end gap-3"> <div className="space-y-1"> <Label htmlFor="supplier-search" className="text-xs text-gray-600"> Search suppliers </Label> <div className="relative"> <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-gray-400" /> <Input id="supplier-search" aria-label="Search suppliers" value={supplierSearchTerm} onChange={(event) => setSupplierSearchTerm(event.target.value)} placeholder="Search by name, id, email, phone" className="pl-8 w-full sm:w-80" /> </div> </div>
<Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => setShowCreateSupplier(true)} disabled={submitting} > <Plus className="w-4 h-4 mr-2" /> New Supplier </Button> </div> </div>
<Card className="bg-white shadow-sm"> <CardContent className="p-0"> <Table> <TableHeader> <TableRow> <TableHead>Supplier</TableHead> <TableHead>Primary Contact</TableHead> <TableHead>Item Types</TableHead> <TableHead>Address</TableHead> </TableRow> </TableHeader> <TableBody> {filteredSuppliers.map((supplier) => ( <TableRow key={supplier.id}> <TableCell> <div className="font-medium">{supplier.name}</div> <div className="text-xs text-gray-500">ID: {toShortId(supplier.id)}</div> </TableCell> <TableCell> <div className="text-sm text-gray-700">{supplier.email || supplier.phoneNumber || 'N/A'}</div> {supplier.email && supplier.phoneNumber && ( <div className="text-xs text-gray-500">{supplier.phoneNumber}</div> )} </TableCell> <TableCell> <div className="flex gap-1 flex-wrap"> {supplier.items.map((item) => ( <Badge key={`${supplier.id}-${item}`} variant="outline" className="text-xs"> {item === 'FOOD' || item === 'FEED' ? ( <Wheat className="w-3 h-3 mr-1" /> ) : ( <FishIcon className="w-3 h-3 mr-1" /> )} {formatProcurementStatusLabel(item)} </Badge> ))} </div> </TableCell> <TableCell> <span className="text-sm text-gray-700">{supplier.address || 'N/A'}</span> </TableCell> </TableRow> ))}
{filteredSuppliers.length === 0 && ( <TableRow> <TableCell colSpan={4} className="h-24 text-center text-gray-600"> No suppliers match your search. </TableCell> </TableRow> )} </TableBody> </Table> </CardContent> </Card> </TabsContent> </Tabs> </div>
<Dialog open={showCreateFeedOrder} onOpenChange={(open) => { setShowCreateFeedOrder(open); if (!open) { resetFeedOrderForm(); } }} > <DialogContent className="max-w-3xl"> <DialogHeader> <DialogTitle>Create New Feed Purchase Order</DialogTitle> <DialogDescription> Build a feed order with dynamic line items and automatic totals. </DialogDescription> </DialogHeader>
<div className="space-y-4"> <div className="space-y-2"> <Label>Supplier *</Label> <Select value={feedOrderSupplierId} onValueChange={setFeedOrderSupplierId}> <SelectTrigger> <SelectValue placeholder="Select supplier" /> </SelectTrigger> <SelectContent> {feedSuppliers.map((supplier) => ( <SelectItem key={supplier.id} value={supplier.id}> {formatNameWithId(supplier.name, supplier.id)} </SelectItem> ))} </SelectContent> </Select> </div>
<div className="border rounded-lg p-4 space-y-3"> <div className="flex items-center justify-between"> <h4 className="font-medium">Order Items</h4> <Button size="sm" variant="outline" onClick={() => setFeedOrderItems((previous) => [...previous, createFeedOrderItem()])} > <Plus className="w-4 h-4 mr-1" /> Add Item </Button> </div>
<div className="space-y-3"> {feedOrderItems.map((item, index) => ( <div key={`feed-item-form-${index}`} className="border rounded-md p-3 space-y-2"> <div className="grid grid-cols-12 gap-2"> <div className="col-span-5"> <Label className="text-xs">Food Type</Label> <Select value={item.foodTypeId} onValueChange={(value) => setFeedOrderItems((previous) => previous.map((entry, entryIndex) => entryIndex === index ? { ...entry, foodTypeId: value } : entry, ), ) } > <SelectTrigger className="h-9"> <SelectValue placeholder="Select" /> </SelectTrigger> <SelectContent> {foodTypes.map((foodType) => ( <SelectItem key={foodType.id} value={foodType.id}> {formatNameWithId(foodType.name, foodType.id)} </SelectItem> ))} </SelectContent> </Select> </div>
<div className="col-span-3"> <Label className="text-xs">Quantity (kg)</Label> <Input type="number" min="0" className="h-9" value={item.quantityKg || ''} onChange={(event) => setFeedOrderItems((previous) => previous.map((entry, entryIndex) => entryIndex === index ? { ...entry, quantityKg: Number(event.target.value) || 0 } : entry, ), ) } /> </div>
<div className="col-span-3"> <Label className="text-xs">Unit Cost (EGP)</Label> <Input type="number" min="0" className="h-9" value={item.unitCost || ''} onChange={(event) => setFeedOrderItems((previous) => previous.map((entry, entryIndex) => entryIndex === index ? { ...entry, unitCost: Number(event.target.value) || 0 } : entry, ), ) } /> </div>
<div className="col-span-1 flex items-end"> <Button size="sm" variant="ghost" className="h-9 w-9 p-0" onClick={() => setFeedOrderItems((previous) => previous.length === 1 ? previous : previous.filter((_, entryIndex) => entryIndex !== index), ) } > <XCircle className="w-4 h-4" /> </Button> </div> </div>
<p className="text-xs text-gray-600"> Line Total: {formatCurrencyEgp(item.quantityKg * item.unitCost)} </p> </div> ))} </div> </div>
<div className="bg-gray-50 p-4 rounded-lg"> <div className="flex items-center justify-between text-lg font-semibold"> <span>Grand Total:</span> <span className="text-[#0A4D68]">{formatCurrencyEgp(feedOrderTotal)}</span> </div> </div>
<div className="flex gap-2"> <Button variant="outline" className="flex-1" onClick={() => setShowCreateFeedOrder(false)}> Cancel </Button> <Button className="flex-1 bg-[#088395] hover:bg-[#0A4D68]" onClick={() => void handleCreateFeedOrder()} disabled={submitting} > {submitting ? 'Creating...' : 'Create Purchase Order'} </Button> </div> </div> </DialogContent> </Dialog>
<Dialog open={showCreateFishOrder} onOpenChange={(open) => { setShowCreateFishOrder(open); if (!open) { resetFishOrderForm(); } }} > <DialogContent className="max-w-3xl"> <DialogHeader> <DialogTitle>Create New Fish Purchase Order</DialogTitle> <DialogDescription> Build a fish order with dynamic line items and automatic totals. </DialogDescription> </DialogHeader>
<div className="space-y-4"> <div className="space-y-2"> <Label>Supplier *</Label> <Select value={fishOrderSupplierId} onValueChange={setFishOrderSupplierId}> <SelectTrigger> <SelectValue placeholder="Select supplier" /> </SelectTrigger> <SelectContent> {fishSuppliers.map((supplier) => ( <SelectItem key={supplier.id} value={supplier.id}> {formatNameWithId(supplier.name, supplier.id)} </SelectItem> ))} </SelectContent> </Select> </div>
<div className="border rounded-lg p-4 space-y-3"> <div className="flex items-center justify-between"> <h4 className="font-medium">Order Items</h4> <Button size="sm" variant="outline" onClick={() => setFishOrderItems((previous) => [...previous, createFishOrderItem()])} > <Plus className="w-4 h-4 mr-1" /> Add Item </Button> </div>
<div className="space-y-3"> {fishOrderItems.map((item, index) => ( <div key={`fish-item-form-${index}`} className="border rounded-md p-3 space-y-2"> <div className="grid grid-cols-12 gap-2"> <div className="col-span-5"> <Label className="text-xs">Fish Type</Label> <Select value={item.fishTypeId} onValueChange={(value) => setFishOrderItems((previous) => previous.map((entry, entryIndex) => entryIndex === index ? { ...entry, fishTypeId: value } : entry, ), ) } > <SelectTrigger className="h-9"> <SelectValue placeholder="Select" /> </SelectTrigger> <SelectContent> {fishTypes.map((fishType) => ( <SelectItem key={fishType.id} value={fishType.id}> {formatNameWithId(fishType.name, fishType.id)} </SelectItem> ))} </SelectContent> </Select> </div>
<div className="col-span-3"> <Label className="text-xs">Quantity</Label> <Input type="number" min="0" className="h-9" value={item.quantity || ''} onChange={(event) => setFishOrderItems((previous) => previous.map((entry, entryIndex) => entryIndex === index ? { ...entry, quantity: Number(event.target.value) || 0 } : entry, ), ) } /> </div>
<div className="col-span-3"> <Label className="text-xs">Unit Cost (EGP)</Label> <Input type="number" min="0" className="h-9" value={item.unitCost || ''} onChange={(event) => setFishOrderItems((previous) => previous.map((entry, entryIndex) => entryIndex === index ? { ...entry, unitCost: Number(event.target.value) || 0 } : entry, ), ) } /> </div>
<div className="col-span-1 flex items-end"> <Button size="sm" variant="ghost" className="h-9 w-9 p-0" onClick={() => setFishOrderItems((previous) => previous.length === 1 ? previous : previous.filter((_, entryIndex) => entryIndex !== index), ) } > <XCircle className="w-4 h-4" /> </Button> </div> </div>
<p className="text-xs text-gray-600"> Line Total: {formatCurrencyEgp(item.quantity * item.unitCost)} </p> </div> ))} </div> </div>
<div className="bg-gray-50 p-4 rounded-lg"> <div className="flex items-center justify-between text-lg font-semibold"> <span>Grand Total:</span> <span className="text-[#0A4D68]">{formatCurrencyEgp(fishOrderTotal)}</span> </div> </div>
<div className="flex gap-2"> <Button variant="outline" className="flex-1" onClick={() => setShowCreateFishOrder(false)}> Cancel </Button> <Button className="flex-1 bg-[#088395] hover:bg-[#0A4D68]" onClick={() => void handleCreateFishOrder()} disabled={submitting} > {submitting ? 'Creating...' : 'Create Purchase Order'} </Button> </div> </div> </DialogContent> </Dialog>
<CreateMedicineOrderDialog open={showCreateMedicineOrder} onOpenChange={(open) => { setShowCreateMedicineOrder(open); if (!open) { resetMedicineOrderForm(); } }} submitting={submitting} supplierId={medicineOrderSupplierId} suppliers={medicineSuppliers} items={medicineOrderItems} fishTypes={fishTypes} totalCost={medicineOrderTotal} onSupplierChange={setMedicineOrderSupplierId} onItemsChange={setMedicineOrderItems} onAddItem={() => setMedicineOrderItems((previous) => [...previous, createMedicineOrderItem()])} onCreate={handleCreateMedicineOrder} />
<Dialog open={showCreateSupplier} onOpenChange={(open) => { setShowCreateSupplier(open); if (!open) { resetSupplierForm(); } }} > <DialogContent className="max-w-xl"> <DialogHeader> <DialogTitle>Add Supplier</DialogTitle> <DialogDescription> Provide supplier details and one or more supplied item types. </DialogDescription> </DialogHeader>
<div className="space-y-4"> <div className="space-y-2"> <Label>Name *</Label> <Input value={supplierName} onChange={(event) => setSupplierName(event.target.value)} /> </div>
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3"> <div className="space-y-2"> <Label>Email</Label> <Input type="email" value={supplierEmail} onChange={(event) => setSupplierEmail(event.target.value)} /> </div>
<div className="space-y-2"> <Label>Phone</Label> <Input value={supplierPhone} onChange={(event) => setSupplierPhone(event.target.value)} /> </div> </div>
<div className="space-y-2"> <Label>Address</Label> <Input value={supplierAddress} onChange={(event) => setSupplierAddress(event.target.value)} /> </div>
<div className="space-y-2"> <Label>Supplied Item Types *</Label> <div className="grid grid-cols-2 gap-2 rounded-md border p-3"> {SUPPLIER_ITEM_TYPE_OPTIONS.map((itemType) => ( <label key={itemType} className="flex items-center gap-2 text-sm cursor-pointer select-none"> <input type="checkbox" checked={supplierItemTypes.includes(itemType)} onChange={() => toggleSupplierItemType(itemType)} className="h-4 w-4 rounded border-gray-300" /> <span>{formatProcurementStatusLabel(itemType)}</span> </label> ))} </div> </div>
<div className="flex gap-2 pt-2"> <Button variant="outline" className="flex-1" onClick={() => setShowCreateSupplier(false)}> Cancel </Button> <Button className="flex-1 bg-[#088395] hover:bg-[#0A4D68]" onClick={() => void handleCreateSupplier()} disabled={submitting} > {submitting ? 'Saving...' : 'Create Supplier'} </Button> </div> </div> </DialogContent> </Dialog>
<Dialog open={Boolean(detailsDialog)} onOpenChange={(open) => !open && setDetailsDialog(null)}> <DialogContent className="max-w-4xl"> <DialogHeader> <DialogTitle> {detailsDialog ? `${detailsDialog.kind === 'feed' ? 'Feed' : detailsDialog.kind === 'fish' ? 'Fish' : 'Medicine'} Order ${detailsDialog.order.orderNumber}` : 'Order Details'} </DialogTitle> <DialogDescription> {detailsDialog ? `Order ID: ${toShortId(detailsDialog.order.id)} · Supplier: ${formatNameWithId( detailsDialog.order.supplierName, detailsDialog.order.supplierId, )}` : ''} </DialogDescription> </DialogHeader>
{detailsDialog && ( <div className="space-y-4"> <div className="grid grid-cols-1 sm:grid-cols-3 gap-3 text-sm"> <Card className="bg-gray-50"> <CardContent className="p-3"> <p className="text-gray-500 text-xs">Status</p> <Badge className={`${getProcurementStatusColorClass(detailsDialog.order.status)} mt-1`}> {formatProcurementStatusLabel(detailsDialog.order.status)} </Badge> </CardContent> </Card>
<Card className="bg-gray-50"> <CardContent className="p-3"> <p className="text-gray-500 text-xs">Order Date</p> <p className="font-medium mt-1"> {detailsDialog.order.orderDate ? new Date(detailsDialog.order.orderDate).toLocaleDateString() : 'N/A'} </p> </CardContent> </Card>
<Card className="bg-gray-50"> <CardContent className="p-3"> <p className="text-gray-500 text-xs">Total Cost</p> <p className="font-medium mt-1 text-[#0A4D68]">{formatCurrencyEgp(detailsDialog.order.totalCost)}</p> </CardContent> </Card> </div>
<div className="rounded-md border"> <Table> <TableHeader> <TableRow> <TableHead>Item</TableHead> <TableHead>Ordered</TableHead> <TableHead>Actual</TableHead> <TableHead>Status</TableHead> <TableHead>Line ID</TableHead> <TableHead>Update Status</TableHead> </TableRow> </TableHeader> <TableBody> {detailsDialog.kind === 'feed' ? (detailsDialog.order as FeedPurchaseOrderRecord).items.map((item) => ( <TableRow key={item.id}> <TableCell> {formatNameWithId(item.foodTypeName || 'Unknown food type', item.foodTypeId)} </TableCell> <TableCell>{formatKg(item.quantityKg)}</TableCell> <TableCell>{item.actualQuantityKg !== undefined ? formatKg(item.actualQuantityKg) : '-'}</TableCell> <TableCell> <Badge className={`${getProcurementStatusColorClass(item.status)} text-xs`}> {formatProcurementStatusLabel(item.status)} </Badge> </TableCell> <TableCell>{toShortId(item.id)}</TableCell> <TableCell> <div className="flex items-center gap-2"> <select aria-label={`Line item status ${item.id}`} className="h-8 rounded-md border border-gray-300 px-2 text-xs bg-white" value={lineItemStatusDrafts[item.id] || normalizeProcurementUiStatus(item.status)} onChange={(event) => updateLineItemStatusDraft(item.id, event.target.value)} disabled={submitting} > {LINE_ITEM_STATUS_OPTIONS.map((option) => ( <option key={`${item.id}-feed-status-${option.value}`} value={option.value}> {option.label} </option> ))} </select> <Button size="sm" variant="outline" disabled={ submitting || updatingLineItemId === item.id || normalizeProcurementUiStatus(lineItemStatusDrafts[item.id] || item.status) === normalizeProcurementUiStatus(item.status) } onClick={() => void submitLineItemStatus(item.id, item.status, 'feed', detailsDialog.order.id) } > {updatingLineItemId === item.id ? 'Updating...' : 'Update'} </Button> </div> </TableCell> </TableRow> )) : detailsDialog.kind === 'fish' ? (detailsDialog.order as FishPurchaseOrderRecord).items.map((item) => ( <TableRow key={item.id}> <TableCell> {formatNameWithId(item.fishTypeName || 'Unknown fish type', item.fishTypeId)} </TableCell> <TableCell>{formatFishCount(item.quantity)}</TableCell> <TableCell> {item.actualQuantity !== undefined ? formatFishCount(item.actualQuantity) : '-'} </TableCell> <TableCell> <Badge className={`${getProcurementStatusColorClass(item.status)} text-xs`}> {formatProcurementStatusLabel(item.status)} </Badge> </TableCell> <TableCell>{toShortId(item.id)}</TableCell> <TableCell> <div className="flex items-center gap-2"> <select aria-label={`Line item status ${item.id}`} className="h-8 rounded-md border border-gray-300 px-2 text-xs bg-white" value={lineItemStatusDrafts[item.id] || normalizeProcurementUiStatus(item.status)} onChange={(event) => updateLineItemStatusDraft(item.id, event.target.value)} disabled={submitting} > {LINE_ITEM_STATUS_OPTIONS.map((option) => ( <option key={`${item.id}-fish-status-${option.value}`} value={option.value}> {option.label} </option> ))} </select> <Button size="sm" variant="outline" disabled={ submitting || updatingLineItemId === item.id || normalizeProcurementUiStatus(lineItemStatusDrafts[item.id] || item.status) === normalizeProcurementUiStatus(item.status) } onClick={() => void submitLineItemStatus(item.id, item.status, 'fish', detailsDialog.order.id) } > {updatingLineItemId === item.id ? 'Updating...' : 'Update'} </Button> </div> </TableCell> </TableRow> )) : (detailsDialog.order as MedicinePurchaseOrderRecord).items.map((item) => ( <TableRow key={item.id}> <TableCell> <div className="font-medium">{item.medicine}</div> <div className="text-xs text-gray-500">Company: {item.company}</div> <div className="text-xs text-gray-500"> Fish Types:{' '} {item.fishTypeNames.length > 0 ? item.fishTypeNames.join(', ') : item.fishTypeIds.map((fishTypeId) => toShortId(fishTypeId)).join(', ') || 'N/A'} </div> </TableCell> <TableCell>{item.quantity.toLocaleString()}</TableCell> <TableCell>{item.actualQuantity !== undefined ? item.actualQuantity.toLocaleString() : '-'}</TableCell> <TableCell> <Badge className={`${getProcurementStatusColorClass(item.status)} text-xs`}> {formatProcurementStatusLabel(item.status)} </Badge> </TableCell> <TableCell>{toShortId(item.id)}</TableCell> <TableCell> <div className="flex items-center gap-2"> <select aria-label={`Line item status ${item.id}`} className="h-8 rounded-md border border-gray-300 px-2 text-xs bg-white" value={lineItemStatusDrafts[item.id] || normalizeProcurementUiStatus(item.status)} onChange={(event) => updateLineItemStatusDraft(item.id, event.target.value)} disabled={submitting} > {LINE_ITEM_STATUS_OPTIONS.map((option) => ( <option key={`${item.id}-medicine-status-${option.value}`} value={option.value}> {option.label} </option> ))} </select> <Button size="sm" variant="outline" disabled={ submitting || updatingLineItemId === item.id || normalizeProcurementUiStatus(lineItemStatusDrafts[item.id] || item.status) === normalizeProcurementUiStatus(item.status) } onClick={() => void submitLineItemStatus(item.id, item.status, 'medicine', detailsDialog.order.id) } > {updatingLineItemId === item.id ? 'Updating...' : 'Update'} </Button> </div> </TableCell> </TableRow> ))} </TableBody> </Table> </div> </div> )} </DialogContent> </Dialog>
<Dialog open={Boolean(receiveDialog)} onOpenChange={(open) => !open && setReceiveDialog(null)}> <DialogContent className="max-w-4xl"> <DialogHeader> <DialogTitle> Receive Items - {receiveDialog?.orderNumber} </DialogTitle> <DialogDescription> {receiveDialog ? `Supplier: ${receiveDialog.supplierName} (${toShortId(receiveDialog.orderId)})` : ''} </DialogDescription> </DialogHeader>
{receiveDialog && ( <div className="space-y-4"> <div className="space-y-2"> <Label htmlFor="receipt-location">Receipt Location</Label> <Input id="receipt-location" value={receiveDialog.location} onChange={(event) => setReceiveDialog((previous) => previous ? { ...previous, location: event.target.value || DEFAULT_RECEIVING_LOCATION } : previous, ) } /> </div>
<div className="rounded-md border"> <Table> <TableHeader> <TableRow> <TableHead>Line Item</TableHead> <TableHead>Ordered</TableHead> <TableHead>Actual Receipt</TableHead> <TableHead>Next Status</TableHead> </TableRow> </TableHeader> <TableBody> {receiveDialog.items.map((item) => { let nextStatus = 'Rejected'; if (item.actualQuantity >= item.orderedQuantity) { nextStatus = 'Received'; } else if (item.actualQuantity > 0 && item.actualQuantity < item.orderedQuantity) { nextStatus = 'Partially Received'; }
return ( <TableRow key={item.id}> <TableCell> <div className="font-medium">{formatNameWithId(item.label, item.typeId)}</div> <div className="text-xs text-gray-500">Line ID: {toShortId(item.id)}</div> </TableCell> <TableCell>{item.unit === 'kg' ? formatKg(item.orderedQuantity) : formatFishCount(item.orderedQuantity)}</TableCell> <TableCell> <Input type="number" min="0" value={item.actualQuantity} onChange={(event) => updateReceiveDialogItem(item.id, Number(event.target.value) || 0) } /> </TableCell> <TableCell> <Badge className={`${getProcurementStatusColorClass(nextStatus)} text-xs`}> {nextStatus} </Badge> </TableCell> </TableRow> ); })} </TableBody> </Table> </div>
<div className="flex gap-2 justify-end"> <Button variant="outline" onClick={() => setReceiveDialog(null)}> Cancel </Button> <Button onClick={() => void submitReceiving()} disabled={submitting}> {submitting ? 'Posting Receipt...' : 'Submit Receipt'} </Button> </div> </div> )} </DialogContent> </Dialog>
<AlertDialog open={confirmationDialog.open} onOpenChange={(open) => setConfirmationDialog((previous) => ({ ...previous, open, action: open ? previous.action : null, })) } > <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle>{confirmationDialog.title}</AlertDialogTitle> <AlertDialogDescription>{confirmationDialog.description}</AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel disabled={submitting}>Cancel</AlertDialogCancel> <AlertDialogAction onClick={() => void runConfirmationAction()} disabled={submitting}> Confirm </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog> </div> );}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import { ReactNode } from 'react';import { Table } from './ui/table';
interface ResponsiveDataTableProps { children: ReactNode; className?: string;}
export function ResponsiveDataTable({ children, className = '' }: ResponsiveDataTableProps) { return ( <div className="w-full"> {/* Desktop Table */} <div className="hidden md:block overflow-x-auto rounded-lg border border-gray-200"> <Table className={className}> {children} </Table> </div> {/* Mobile View - Will be handled by individual components with cards */} <div className="md:hidden"> {children} </div> </div> );}
interface StatCardProps { icon: ReactNode; title: string; value: string | number; subtitle?: string; trend?: { value: number; isPositive: boolean; }; bgColor?: string; iconBgColor?: string; iconColor?: string;}
export function StatCard({ icon, title, value, subtitle, trend, bgColor = 'bg-white', iconBgColor = 'bg-[#E0F4F5]', iconColor = 'text-[#088395]'}: StatCardProps) { return ( <div className={`${bgColor} p-4 md:p-6 rounded-lg border border-gray-200 shadow-sm`}> <div className="flex items-start justify-between"> <div className="flex-1"> <p className="text-xs md:text-sm text-gray-600 mb-1">{title}</p> <p className="text-2xl md:text-3xl font-bold text-gray-900">{value}</p> {subtitle && ( <p className="text-xs md:text-sm text-gray-500 mt-1">{subtitle}</p> )} {trend && ( <div className="flex items-center gap-1 mt-2"> <span className={`text-xs md:text-sm font-medium ${trend.isPositive ? 'text-green-600' : 'text-red-600'}`}> {trend.isPositive ? '↑' : '↓'} {Math.abs(trend.value)}% </span> </div> )} </div> <div className={`w-10 h-10 md:w-12 md:h-12 rounded-lg ${iconBgColor} flex items-center justify-center flex-shrink-0`}> <div className={`w-5 h-5 md:w-6 md:h-6 ${iconColor}`}> {icon} </div> </div> </div> </div> );}12345678910111213141516171819202122232425import { ReactNode } from 'react';
interface ResponsivePageHeaderProps { title: string; description?: string; actions?: ReactNode;}
export function ResponsivePageHeader({ title, description, actions }: ResponsivePageHeaderProps) { return ( <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3 md:gap-4 mb-4 md:mb-6"> <div> <h1 className="text-2xl md:text-3xl font-semibold text-gray-900">{title}</h1> {description && ( <p className="text-sm md:text-base text-gray-600 mt-1">{description}</p> )} </div> {actions && ( <div className="flex flex-wrap gap-2"> {actions} </div> )} </div> );}1234567891011121314151617181920212223242526272829303132333435import { ReactNode } from 'react';
interface ResponsivePageLayoutProps { children: ReactNode; className?: string;}
export function ResponsivePageLayout({ children, className = '' }: ResponsivePageLayoutProps) { return ( <div className={`min-h-screen bg-[#F9FAFB] p-4 md:p-6 space-y-4 md:space-y-6 ${className}`}> {children} </div> );}
interface ResponsiveCardGridProps { children: ReactNode; cols?: 1 | 2 | 3 | 4; className?: string;}
export function ResponsiveCardGrid({ children, cols = 3, className = '' }: ResponsiveCardGridProps) { const gridClasses = { 1: 'grid grid-cols-1 gap-3 md:gap-4', 2: 'grid grid-cols-1 md:grid-cols-2 gap-3 md:gap-4', 3: 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3 md:gap-4', 4: 'grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-3 md:gap-4' };
return ( <div className={`${gridClasses[cols]} ${className}`}> {children} </div> );}12345678910111213141516171819202122232425262728293031323334353637import { ReactNode } from 'react';import { Card } from './ui/card';
interface ResponsiveTableProps { children: ReactNode; className?: string;}
export function ResponsiveTableWrapper({ children, className = '' }: ResponsiveTableProps) { return ( <div className={`overflow-x-auto -mx-4 sm:mx-0 ${className}`}> <div className="inline-block min-w-full align-middle"> <div className="overflow-hidden border-b border-gray-200 sm:rounded-lg"> {children} </div> </div> </div> );}
interface MobileCardListProps<T> { items: T[]; renderCard: (item: T, index: number) => ReactNode; className?: string;}
export function MobileCardList<T>({ items, renderCard, className = '' }: MobileCardListProps<T>) { return ( <div className={`space-y-3 ${className}`}> {items.map((item, index) => ( <Card key={index} className="p-4"> {renderCard(item, index)} </Card> ))} </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199import { useCallback, useEffect, useState } from 'react';import { Card, CardContent } from './ui/card';import { Tabs, TabsContent, TabsList, TabsTrigger } from './ui/tabs';import { ShoppingBag, Package, ClipboardList, TrendingUp, Loader2, ArrowRight,} from 'lucide-react';import { User, Farm } from '../types';import { mockFarms } from '../mockData';import CustomerManagement from './sales/CustomerManagement';import SalesOrderList from './sales/SalesOrderList';import { getSalesDashboardMetrics } from '../services/salesApi';import { Button } from './ui/button';
interface SalesModuleProps { user: User; selectedFarm: Farm | null; allowedPages?: string[]; onNavigateToPage?: (page: string) => void;}
const normalizeErrorMessage = (error: unknown): string => { if (error instanceof Error && error.message.trim()) { return error.message; } return 'Failed to load sales dashboard data.';};
export default function SalesModule({ user, selectedFarm, allowedPages = [], onNavigateToPage }: SalesModuleProps) { const currentFarm = selectedFarm || mockFarms[0]; const canOpenHarvest = allowedPages.includes('harvest'); const [activeTab, setActiveTab] = useState('orders'); const [refreshKey, setRefreshKey] = useState(0); const [loadingStats, setLoadingStats] = useState(true); const [statsError, setStatsError] = useState<string | null>(null); const [stats, setStats] = useState({ totalOrders: 0, pendingOrders: 0, totalRevenue: 0, availableStock: 0, });
const refreshStats = useCallback(async () => { setLoadingStats(true); setStatsError(null);
try { const response = await getSalesDashboardMetrics(); setStats(response); } catch (error) { setStatsError(normalizeErrorMessage(error)); } finally { setLoadingStats(false); } }, []);
useEffect(() => { void refreshStats(); }, [refreshStats, refreshKey]);
const handleDataChanged = () => { setRefreshKey((previous) => previous + 1); };
return ( <div className="min-h-screen bg-[#F9FAFB]"> <div className="bg-[#0A4D68] text-white px-6 py-4"> <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> <ShoppingBag className="w-6 h-6" /> <span className="text-xl font-semibold">Sales Management</span> </div> <div className="flex items-center gap-4"> {canOpenHarvest && ( <Button type="button" variant="outline" className="border-white/30 bg-transparent text-white hover:bg-white/10 hover:text-white" onClick={() => onNavigateToPage?.('harvest')} > Go to Harvest <ArrowRight className="w-4 h-4 ml-2" /> </Button> )} <span className="text-sm">{currentFarm.name}</span> <div className="w-10 h-10 rounded-full bg-[#088395] flex items-center justify-center font-semibold"> {user.name .split(' ') .map((namePart) => namePart[0]) .join('') .toUpperCase()} </div> </div> </div> </div>
<div className="p-6 space-y-6"> {statsError && ( <Card className="bg-red-50 border-red-200"> <CardContent className="p-4 text-sm text-red-700">{statsError}</CardContent> </Card> )}
<div className="grid grid-cols-1 md:grid-cols-4 gap-4"> <Card className="bg-white shadow-sm"> <CardContent className="p-4"> <div className="flex items-center justify-between"> <div> <p className="text-sm text-gray-600">Total Orders</p> <p className="text-2xl font-bold text-gray-900"> {loadingStats ? <Loader2 className="w-5 h-5 animate-spin" /> : stats.totalOrders} </p> </div> <div className="w-12 h-12 rounded-full bg-[#E0F4F5] flex items-center justify-center"> <ClipboardList className="w-6 h-6 text-[#088395]" /> </div> </div> </CardContent> </Card>
<Card className="bg-white shadow-sm"> <CardContent className="p-4"> <div className="flex items-center justify-between"> <div> <p className="text-sm text-gray-600">Pending Orders</p> <p className="text-2xl font-bold text-[#F59E0B]"> {loadingStats ? <Loader2 className="w-5 h-5 animate-spin" /> : stats.pendingOrders} </p> </div> <div className="w-12 h-12 rounded-full bg-[#FEF3C7] flex items-center justify-center"> <ClipboardList className="w-6 h-6 text-[#F59E0B]" /> </div> </div> </CardContent> </Card>
<Card className="bg-white shadow-sm"> <CardContent className="p-4"> <div className="flex items-center justify-between"> <div> <p className="text-sm text-gray-600">Total Revenue</p> <p className="text-2xl font-bold text-[#10B981]"> {loadingStats ? <Loader2 className="w-5 h-5 animate-spin" /> : `${stats.totalRevenue.toLocaleString()} EGP`} </p> </div> <div className="w-12 h-12 rounded-full bg-[#D1FAE5] flex items-center justify-center"> <TrendingUp className="w-6 h-6 text-[#10B981]" /> </div> </div> </CardContent> </Card>
<Card className="bg-white shadow-sm"> <CardContent className="p-4"> <div className="flex items-center justify-between"> <div> <p className="text-sm text-gray-600">Available Stock</p> <p className="text-2xl font-bold text-gray-900"> {loadingStats ? <Loader2 className="w-5 h-5 animate-spin" /> : `${stats.availableStock} kg`} </p> </div> <div className="w-12 h-12 rounded-full bg-[#FEE2E2] flex items-center justify-center"> <Package className="w-6 h-6 text-[#EF4444]" /> </div> </div> </CardContent> </Card> </div>
<Tabs value={activeTab} onValueChange={setActiveTab} className="space-y-4"> <TabsList className="bg-white"> <TabsTrigger value="orders">Sales Orders</TabsTrigger> <TabsTrigger value="customers">Customers</TabsTrigger> </TabsList>
<TabsContent value="orders"> <SalesOrderList user={user} selectedFarm={currentFarm} onOrdersChanged={handleDataChanged} /> </TabsContent>
<TabsContent value="customers"> <CustomerManagement user={user} selectedFarm={currentFarm} onCustomersChanged={handleDataChanged} /> </TabsContent> </Tabs> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185import { LayoutDashboard, Droplet, DollarSign, Package, TrendingUp, Bot, Heart, Bell, LogOut, Fish, ShoppingCart, Wheat, ShoppingBag, Scissors, ShieldUser, ListChecks, Cpu, Tractor, Pill,} from "lucide-react";import { Button } from "./ui/button";import { Avatar, AvatarFallback } from "./ui/avatar";import { User } from "../types";
interface SidebarProps { currentPage: string; onPageChange: (page: string) => void; onLogout: () => void; user: User; notifications: any[]; allowedPages: string[]; moduleLabelMap: Record<string, string>;}
export default function Sidebar({ currentPage, onPageChange, onLogout, user, notifications, allowedPages, moduleLabelMap,}: SidebarProps) { const unreadCount = notifications.filter((n) => !n.read).length; const isTechnician = user.role.toLocaleLowerCase() === "technician"; const menuItems = [ { id: "dashboard", label: "Dashboard", icon: LayoutDashboard }, { id: "tanks", label: "Tank Management", icon: Droplet }, { id: "inventory", label: "Inventory", icon: Package }, { id: "harvest", label: "Harvest", icon: Scissors }, { id: "fish-types", label: "Fish Types", icon: Fish }, { id: "food-types", label: "Food Types", icon: Wheat }, { id: "medicine-types", label: "Medicine Types", icon: Pill }, { id: "health", label: "Health Library", icon: Heart }, { id: "ai-assistant", label: "AI Assistant", icon: Bot }, { id: "iot-management", label: "Sensors readings", icon: Cpu }, { id: "farms", label: "Farms", icon: Tractor }, { id: "users", label: "User Management", icon: ShieldUser },
{ id: "tasks", label: "Tasks", icon: ListChecks }, { id: "notifications", label: "Notifications", icon: Bell, badge: unreadCount > 0 ? unreadCount : null, }, { id: "sales", label: "Sales", icon: ShoppingBag, comingSoon: true, }, { id: "accounting", label: "Accounting", icon: DollarSign, comingSoon: true, }, { id: "analytics", label: "Analytics", icon: TrendingUp, comingSoon: true, }, { id: "procurement", label: "Procurement", icon: ShoppingCart, comingSoon: true, }, ]; const visibleMenuItems = menuItems.filter( (item) => (allowedPages.includes(item.id) || item.comingSoon) && !(isTechnician && item.id === "tasks"), );
const getInitials = (name: string) => { return name .split(" ") .map((n) => n[0]) .join("") .toUpperCase(); };
return ( <div className="w-64 bg-[#0A4D68] text-white flex flex-col"> {/* Header */} <div className="p-4 border-b border-white/10"> <div className="flex items-center gap-3"> <div className="bg-[#088395] p-2 rounded-lg"> <Fish className="w-6 h-6 text-white" /> </div> <div> <p className="font-semibold">FishFarm360</p> </div> </div> </div>
{/* User Info */} <div className="p-4 border-b border-white/10"> <div className="flex items-center gap-3"> <Avatar> <AvatarFallback className="bg-[#088395] text-white"> {getInitials(user.name)} </AvatarFallback> </Avatar> <div className="flex-1 min-w-0"> <p className="text-sm truncate font-medium">{user.name}</p> </div> </div> </div>
{/* Navigation */} <nav className="flex-1 p-2 overflow-y-auto"> {visibleMenuItems.map((item) => { const Icon = item.icon; const isActive = currentPage === item.id; const normalizedId = item.id.toLowerCase(); const baseLabel = moduleLabelMap[normalizedId] || item.label; const label = item.comingSoon ? `${baseLabel} (Coming Soon)` : baseLabel;
return ( <button key={item.id} onClick={() => { if (!item.comingSoon) onPageChange(item.id); }} className={`w-full flex items-center justify-between px-3 py-2 rounded-lg mb-1 transition-colors ${item.comingSoon ? "opacity-50 cursor-not-allowed" : ""} ${ isActive ? "bg-[#088395] text-white" : "text-gray-200 hover:bg-white/10" }`} > <div className="flex items-center gap-3"> <Icon className="w-5 h-5" /> <span className="text-sm">{label}</span> </div> {item.badge && ( <span className="bg-red-500 text-white text-[10px] font-bold px-1.5 py-0.5 rounded-full min-w-[20px] text-center"> {item.badge} </span> )} </button> ); })} </nav>
{/* Logout */} <div className="p-4 border-t border-white/10"> <Button variant="ghost" className="w-full justify-start text-white hover:bg-white/10 hover:text-white" onClick={onLogout} > <LogOut className="w-5 h-5 mr-3" /> Logout </Button> </div> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600import { useState, useEffect, useCallback, MouseEvent } from "react";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Button } from "./ui/button";import { Badge } from "./ui/badge";import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle,} from "./ui/alert-dialog";import { toast } from "sonner";import { Activity, Droplet, Fish, HeartPulse, Loader2, Plus, Trash2,} from "lucide-react";import { Progress } from "./ui/progress";import { User, Farm } from "../types";import { apiDelete, apiGet, apiPatch, apiPost, apiPut } from "../api";import TankDetailView from "./tanks/TankDetailView";import { AddTankModal } from "./tanks/modals/AddTankModal";import { Pencil } from "lucide-react";import { fetchAllTankHealthOverviews, TankHealthOverview,} from "../services/tankHealthOverview";import { formatHealthStatus, getHealthStatusColor,} from "../services/healthCheckApi";
interface TankManagementProps { user: User; selectedFarm: Farm | null;}
interface ApiTankBiomass { actual?: number; capacity?: number; unit?: string; overstockPercentage?: number | null; volumeM3?: number;}interface ApiTankWaterQuality { overallStatus?: string; temperature?: number; dissolvedOxygen?: number; ph?: number; ammonia?: number;}interface ApiTankFeeding { currentMeal?: number; totalMeals?: number; weightFed?: number; targetWeight?: number; percentage?: number;}interface RawApiTank { id: string; _id?: string; name: string; status: string; fishType?: string; biomass?: ApiTankBiomass; waterQuality: ApiTankWaterQuality | null; feeding: ApiTankFeeding | null; batches?: any[]; assignedUserIds?: string[]; assignedUsers?: Array< string | { id?: string; _id?: string; userId?: string } >; volumeCubicMeters?: number; location?: string; farmId?: string;}interface ApiTank { id: string; name: string; farmId?: string; status: string; fishType?: string; species: string; biomass: number; capacity: number; volume: number; location?: string; waterQuality: { overall: string; temp: { value: number; status: string }; do: { value: number; status: string }; ph: { value: number; status: string }; nh3: { value: number; status: string }; } | null; feeding: { todayMeals: number; totalMeals: number; todayFed: number; recommended: number; } | null; batches?: any[];}
const formatDateTime = (value?: string) => { if (!value) return "Unknown"; const date = new Date(value); if (Number.isNaN(date.getTime())) return value; return date.toLocaleString(undefined, { year: "numeric", month: "short", day: "numeric", hour: "2-digit", minute: "2-digit", });};
export default function TankManagement({ user, selectedFarm,}: TankManagementProps) { const [viewMode, setViewMode] = useState<"list" | "detail">("list"); const [selectedTank, setSelectedTank] = useState<any>(null); const [deleteConfirmId, setDeleteConfirmId] = useState<string | null>(null); const [tanks, setTanks] = useState<ApiTank[]>([]); const [tanksLoading, setTanksLoading] = useState(true); const [tanksError, setTanksError] = useState<string | null>(null); const [showAddTankModal, setShowAddTankModal] = useState(false); const [statusFilter, setStatusFilter] = useState< "ALL" | "ACTIVE" | "INACTIVE" | "MAINTENANCE" | "EMPTY" >("ALL"); const [editingTank, setEditingTank] = useState<any | null>(null); const [showEditModal, setShowEditModal] = useState(false); const [editTankId, setEditTankId] = useState<string | null>(null); const [healthOverviewByTank, setHealthOverviewByTank] = useState< Record<string, TankHealthOverview> >({}); const [loadingHealthOverview, setLoadingHealthOverview] = useState(false);
const currentFarm = selectedFarm;
const loadHealthOverviews = useCallback(async (sourceTanks: ApiTank[]) => { if (sourceTanks.length === 0) { setHealthOverviewByTank({}); return; }
setLoadingHealthOverview(true); try { const result = await fetchAllTankHealthOverviews(sourceTanks); const nextMap = result.overviews.reduce< Record<string, TankHealthOverview> >((acc, overview) => { acc[overview.tank.id] = overview; return acc; }, {}); setHealthOverviewByTank(nextMap); } catch (error) { toast.error( `Failed to load tank health data: ${(error as Error).message}`, ); } finally { setLoadingHealthOverview(false); } }, []);
const fetchTanks = useCallback(async () => { if (!currentFarm) { setTanks([]); setHealthOverviewByTank({}); setTanksLoading(false); return; }
setTanksLoading(true); setTanksError(null); try { const res = await apiGet< { success: boolean; data: RawApiTank[] } | RawApiTank[] >("/tanks"); const list: RawApiTank[] = Array.isArray(res) ? res : ((res as { success: boolean; data: RawApiTank[] }).data ?? []);
const normalised = list.map((tank) => { const bioObj = tank.biomass as ApiTankBiomass | undefined; const biomassKg = bioObj?.actual ?? 0; const capacityKg = bioObj?.capacity ?? 25000; const wq = tank.waterQuality as ApiTankWaterQuality | undefined; const fd = tank.feeding as ApiTankFeeding | undefined; const species = tank.fishType && tank.fishType !== "None" ? tank.fishType : "Empty/No Fish";
return { ...tank, id: tank.id || tank._id || "", species, biomass: biomassKg, capacity: capacityKg, volume: tank.volumeCubicMeters ?? bioObj?.volumeM3 ?? 50, waterQuality: wq ? { overall: (wq.overallStatus ?? "unknown").toLowerCase(), temp: { value: parseFloat((wq.temperature ?? 0).toFixed(1)), status: "unknown", }, do: { value: parseFloat((wq.dissolvedOxygen ?? 0).toFixed(2)), status: "unknown", }, ph: { value: parseFloat((wq.ph ?? 0).toFixed(2)), status: "unknown", }, nh3: { value: parseFloat((wq.ammonia ?? 0).toFixed(4)), status: "unknown", }, } : null, feeding: fd ? { todayMeals: fd.currentMeal ?? 0, totalMeals: fd.totalMeals ?? 4, todayFed: fd.weightFed ?? 0, recommended: fd.targetWeight ?? 0, } : null, }; });
setTanks(normalised as ApiTank[]); await loadHealthOverviews(normalised as ApiTank[]); } catch (err) { console.error("Fetch Tanks Error:", err); setTanksError((err as Error).message); } finally { setTanksLoading(false); } }, [currentFarm, loadHealthOverviews]);
useEffect(() => { void fetchTanks(); }, [fetchTanks]);
useEffect(() => { if (viewMode === "detail" && selectedTank) { const updated = tanks.find((tank) => tank.id === selectedTank.id); if (updated && JSON.stringify(updated) !== JSON.stringify(selectedTank)) { setSelectedTank(updated); } } }, [selectedTank, tanks, viewMode]);
const handleAddTank = async (data: { name: string; capacity: number; volume: number; location: string; }) => { try { await apiPost("/tanks", { name: data.name, location: data.location || "General", volumeCubicMeters: data.volume, status: "EMPTY", }); setShowAddTankModal(false); await fetchTanks(); toast.success("Tank created successfully"); } catch (err) { toast.error(`Failed to create tank: ${(err as Error).message}`); } };
const handleUpdateTank = async (data: { name: string; capacity: number; volume: number; location: string; }) => { if (!editTankId) return; try { const payload = { name: data.name, location: data.location, volumeCubicMeters: data.volume, biomassLimit: data.capacity, };
try { await apiPatch(`/tanks/${editTankId}`, payload); toast.success("Tank updated successfully"); } catch (patchErr: any) { if (patchErr.message.includes("404")) { await apiPut(`/tanks/${editTankId}`, payload); toast.success("Tank updated successfully"); } else { throw patchErr; } }
setShowEditModal(false); setEditTankId(null); setEditingTank(null); await fetchTanks(); } catch (err) { toast.error(`Failed to update tank: ${(err as Error).message}`); } };
const handleDeleteTank = async () => { if (!deleteConfirmId) return; try { await apiDelete(`/tanks/${deleteConfirmId}`); setDeleteConfirmId(null); await fetchTanks(); toast.success("Tank deleted successfully"); } catch (err) { toast.error(`Failed to delete tank: ${(err as Error).message}`); setDeleteConfirmId(null); } };
const getStatusColor = (status: string) => { const normalized = status.toLowerCase(); switch (normalized) { case "critical": return "bg-[#EF4444] critical-blink"; case "warning": return "bg-[#F59E0B] blink"; case "acceptable": return "bg-[#3B82F6]"; case "optimal": case "active": return "bg-[#10B981]"; case "maintenance": return "bg-purple-500"; case "empty": return "bg-gray-400"; default: return "bg-gray-500"; } };
if (viewMode === "detail" && selectedTank) { return ( <TankDetailView user={user} tank={selectedTank} onBack={() => setViewMode("list")} /> ); }
const filteredTanks = tanks.filter((tank) => { if (statusFilter === "ALL") return true; return (tank.status ?? "").toUpperCase() === statusFilter; });
return ( <div className="min-h-screen bg-[#F9FAFB]"> <div className="bg-[#0A4D68] px-6 py-4 text-white"> <div className="flex items-center justify-between"> <div className="flex items-center gap-2"> <Droplet className="h-6 w-6" /> <span className="text-xl font-semibold">Tank Management</span> </div> <div className="flex items-center gap-4"> <span className="text-sm">{currentFarm?.name}</span> <div className="flex h-10 w-10 items-center justify-center rounded-full bg-[#088395] font-semibold"> {user.name .split(" ") .map((segment) => segment[0]) .join("") .toUpperCase()} </div> </div> </div> </div>
<div className="space-y-6 p-6"> <div className="flex items-center justify-between"> <div> <h1 className="text-3xl font-semibold text-gray-900">All Tanks</h1> <p className="mt-1 text-sm text-gray-500"> Health status now includes live AI reports and recovery actions without opening the full tank view. </p> </div> <Button className="bg-[#088395] hover:bg-[#0A4D68]" onClick={() => setShowAddTankModal(true)} > <Plus className="mr-2 h-4 w-4" /> Add New Tank </Button> </div>
{/* <div className="flex flex-wrap gap-2"> {['ALL', 'ACTIVE', 'INACTIVE', 'MAINTENANCE', 'EMPTY'].map((status) => ( <Button key={status} variant={statusFilter === status ? 'default' : 'outline'} size="sm" className={statusFilter === status ? 'bg-[#088395] hover:bg-[#0A4D68]' : ''} onClick={() => setStatusFilter(status as typeof statusFilter)} > {status} </Button> ))} </div> */}
<AddTankModal open={showAddTankModal} onOpenChange={setShowAddTankModal} onConfirm={handleAddTank} />
{tanksError && ( <div className="flex items-center gap-3 rounded-lg border border-red-200 bg-red-50 p-4"> <Activity className="h-5 w-5 flex-shrink-0 text-red-500" /> <div className="flex-1"> <p className="text-sm font-medium text-red-800"> Failed to load tanks </p> <p className="mt-0.5 text-xs text-red-600">{tanksError}</p> </div> <Button size="sm" variant="outline" onClick={() => void fetchTanks()} > Retry </Button> </div> )}
{tanksLoading ? ( <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3"> {[1, 2, 3, 4, 5, 6].map((index) => ( <Card key={index} className="animate-pulse bg-white shadow-sm"> <CardContent className="space-y-3 p-6"> <div className="h-5 w-1/2 rounded bg-gray-200" /> <div className="h-3 w-1/3 rounded bg-gray-200" /> <div className="h-2 w-full rounded bg-gray-200" /> <div className="h-12 rounded bg-gray-100" /> <div className="h-20 rounded bg-gray-100" /> </CardContent> </Card> ))} </div> ) : filteredTanks.length === 0 && !tanksError ? ( <div className="py-16 text-center"> <Fish className="mx-auto mb-3 h-12 w-12 text-gray-300" /> <p className="text-gray-600"> No {statusFilter !== "ALL" ? statusFilter.toLowerCase() : ""}{" "} tanks found </p> </div> ) : ( <div className="grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-3"> {filteredTanks.map((tank) => { const healthOverview = healthOverviewByTank[tank.id];
return ( <Card key={tank.id} className="cursor-pointer bg-white shadow-sm transition-shadow hover:shadow-md" onClick={() => { setSelectedTank(tank); setViewMode("detail"); }} > <CardHeader className="pb-3"> <div className="flex items-center justify-between gap-3"> <div> <CardTitle className="text-lg">{tank.name}</CardTitle> </div> <div className="flex items-center gap-2"> <Badge className={`${getStatusColor(tank.status ?? "")} text-[10px] text-white`} > {(tank.status ?? "unknown").toUpperCase()} </Badge> <div className="flex items-center gap-1"> <Button variant="ghost" size="sm" className="h-8 w-8 p-0 text-blue-400 transition-colors hover:bg-blue-50 hover:text-blue-600" onClick={(event: MouseEvent<HTMLButtonElement>) => { event.stopPropagation(); setEditingTank({ name: tank.name, location: tank.location || "General", capacity: tank.capacity || 25000, volume: tank.volume || 50, }); setEditTankId(tank.id); setShowEditModal(true); }} > <Pencil className="h-3.5 w-3.5" /> </Button> <Button variant="ghost" size="sm" className="h-8 w-8 p-0 text-red-400 transition-colors hover:bg-red-50 hover:text-red-600" onClick={(event: MouseEvent<HTMLButtonElement>) => { event.stopPropagation(); setDeleteConfirmId(tank.id); }} > <Trash2 className="h-4 w-4" /> </Button> </div> </div> </div> <p className="text-sm text-gray-600">{tank.species}</p> </CardHeader> <CardContent className="space-y-4"> <div> <div className="mb-1 flex items-center justify-between text-sm"> <span className="text-gray-600">Biomass</span> <span className="font-medium"> {tank.biomass} / {tank.capacity} kg </span> </div> <Progress value={Math.min( (tank.biomass / tank.capacity) * 100, 100, )} className="h-2" /> {tank.biomass > tank.capacity && ( <p className="mt-1 text-xs text-red-600"> Overstocked by{" "} {Math.round( ((tank.biomass - tank.capacity) / tank.capacity) * 100, )} % </p> )} </div> </CardContent> </Card> ); })} </div> )} </div>
<AlertDialog open={!!deleteConfirmId} onOpenChange={(open: boolean) => !open && setDeleteConfirmId(null)} > <AlertDialogContent> <AlertDialogHeader> <AlertDialogTitle> Are you sure you want to delete this tank? </AlertDialogTitle> <AlertDialogDescription> This action cannot be undone. All data associated with this tank, including historical records and batches, might be affected or lost. </AlertDialogDescription> </AlertDialogHeader> <AlertDialogFooter> <AlertDialogCancel>Cancel</AlertDialogCancel> <AlertDialogAction onClick={handleDeleteTank} className="bg-red-600 text-white hover:bg-red-700" > Delete Tank </AlertDialogAction> </AlertDialogFooter> </AlertDialogContent> </AlertDialog>
<AddTankModal open={showEditModal} onOpenChange={setShowEditModal} onConfirm={handleUpdateTank} initialData={editingTank} mode="edit" /> </div> );}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338import { useCallback, useEffect, useMemo, useState } from "react";import { Card, CardContent, CardHeader, CardTitle } from "./ui/card";import { Button } from "./ui/button";import { Badge } from "./ui/badge";import { toast } from "sonner";import { CheckCircle2, Clock3, ListChecks, RefreshCcw, Trash2,} from "lucide-react";import { User } from "../types";import { deleteTask, getFarmTasks, getMyTasks, isFeedingTask, notifyFeedingTaskCompleted, TaskItem, TaskStatus, updateTaskStatus,} from "../services/taskApi";
interface TasksProps { user: User;}
const STATUSES: TaskStatus[] = ["OPEN", "IN_PROGRESS", "DONE", "CANCELLED"];
const STATUS_BADGE_CLASS: Record<TaskStatus, string> = { OPEN: "bg-blue-100 text-blue-800", IN_PROGRESS: "bg-yellow-100 text-amber-800", DONE: "bg-green-600 text-white border-green-600", CANCELLED: "bg-red-100 text-white border-red-700",};
const formatDateTime = (value?: string): string => { if (!value) return "N/A"; const date = new Date(value); if (Number.isNaN(date.getTime())) return "N/A"; return date.toLocaleString();};
export default function Tasks({ user }: TasksProps) { const canViewFarmTasks = user.role === "admin" || user.role === "manager"; const canCancelTask = canViewFarmTasks;
const [scope, setScope] = useState<"mine" | "farm">( canViewFarmTasks ? "farm" : "mine", ); const [statusFilter, setStatusFilter] = useState<"ALL" | TaskStatus>("ALL"); const [tasks, setTasks] = useState<TaskItem[]>([]); const [loading, setLoading] = useState(false); const [error, setError] = useState<string | null>(null); const [busyTaskIds, setBusyTaskIds] = useState<Record<string, boolean>>({});
const setTaskBusy = (taskId: string, busy: boolean) => { setBusyTaskIds((prev) => ({ ...prev, [taskId]: busy })); };
const loadTasks = useCallback(async () => { setLoading(true); setError(null); try { const data = scope === "mine" ? await getMyTasks() : await getFarmTasks( statusFilter === "ALL" ? undefined : statusFilter, ); setTasks(data); } catch (err) { setError((err as Error).message); setTasks([]); } finally { setLoading(false); } }, [scope, statusFilter]);
useEffect(() => { void loadTasks(); }, [loadTasks]);
const filteredTasks = useMemo(() => { if (statusFilter === "ALL") return tasks; return tasks.filter((task) => task.status === statusFilter); }, [statusFilter, tasks]);
const summary = useMemo(() => { const counts: Record<"total" | TaskStatus, number> = { total: filteredTasks.length, OPEN: 0, IN_PROGRESS: 0, DONE: 0, CANCELLED: 0, };
filteredTasks.forEach((task) => { counts[task.status] += 1; });
return counts; }, [filteredTasks]);
const handleUpdateStatus = async (task: TaskItem, status: TaskStatus) => { setTaskBusy(task.id, true); try { await updateTaskStatus(task.id, status); if (status === "DONE" && isFeedingTask(task)) { notifyFeedingTaskCompleted(task.id); } toast.success(`Task moved to ${status}`); await loadTasks(); } catch (err) { toast.error(`Failed to update task: ${(err as Error).message}`); } finally { setTaskBusy(task.id, false); } };
const handleDeleteTask = async (task: TaskItem) => { setTaskBusy(task.id, true); try { await deleteTask(task.id); toast.success("Task cancelled"); await loadTasks(); } catch (err) { toast.error(`Failed to cancel task: ${(err as Error).message}`); } finally { setTaskBusy(task.id, false); } }; const isWorker = user.role.toLowerCase() === "worker"; return ( <div className="p-6 space-y-6"> <div className="flex flex-wrap items-center justify-between gap-3"> <div> <h1 className="text-2xl font-semibold">Tasks</h1> <p className="text-sm text-gray-600"> Track and complete operational tasks assigned from alerts and workflows. </p> </div>
<Button variant="outline" onClick={() => void loadTasks()} disabled={loading} > <RefreshCcw className="w-4 h-4 mr-2" /> Refresh </Button> </div>
<Card> <CardContent className="pt-6 flex flex-wrap gap-3 items-center"> {canViewFarmTasks && ( <div className="flex items-center gap-2"> <Button size="sm" variant={scope === "farm" ? "default" : "outline"} onClick={() => setScope("farm")} > Farm Tasks </Button> <Button size="sm" variant={scope === "mine" ? "default" : "outline"} onClick={() => setScope("mine")} > My Tasks </Button> </div> )}
<select className="h-9 rounded-md border border-input bg-background px-3 text-sm" value={statusFilter} onChange={(event) => setStatusFilter(event.target.value as "ALL" | TaskStatus) } > <option value="ALL">All Statuses</option> {STATUSES.map((status) => ( <option key={status} value={status}> {status} </option> ))} </select> </CardContent> </Card>
<div className="grid grid-cols-1 md:grid-cols-4 gap-4"> <Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Total</CardTitle> </CardHeader> <CardContent className="text-2xl font-semibold"> {summary.total} </CardContent> </Card> <Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Open</CardTitle> </CardHeader> <CardContent className="text-2xl font-semibold text-blue-700"> {summary.OPEN} </CardContent> </Card> <Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">In Progress</CardTitle> </CardHeader> <CardContent className="text-2xl font-semibold text-amber-700"> {summary.IN_PROGRESS} </CardContent> </Card> <Card> <CardHeader className="pb-2"> <CardTitle className="text-sm">Done</CardTitle> </CardHeader> <CardContent className="text-2xl font-semibold text-emerald-700"> {summary.DONE} </CardContent> </Card> </div>
<Card> <CardHeader> <CardTitle className="text-base"> {scope === "farm" ? "Farm Task Queue" : "My Assigned Tasks"} </CardTitle> </CardHeader> <CardContent className="space-y-3"> {loading && ( <div className="text-sm text-gray-600">Loading tasks...</div> )}
{!loading && error && ( <div className="text-sm text-red-700"> Failed to load tasks: {error} </div> )}
{!loading && !error && filteredTasks.length === 0 && ( <div className="py-10 text-center text-gray-500"> <ListChecks className="w-10 h-10 mx-auto mb-2 text-gray-400" /> <p>No tasks found for the selected filter.</p> </div> )}
{!loading && !error && filteredTasks.map((task) => { const isBusy = !!busyTaskIds[task.id]; const canStart = task.status === "OPEN"; const canComplete = task.status === "OPEN" || task.status === "IN_PROGRESS"; const canCancel = canCancelTask && task.status !== "DONE" && task.status !== "CANCELLED";
return ( <div key={task.id} className="rounded-lg border p-4 space-y-3"> <div className="flex flex-wrap items-center justify-between gap-2"> <div className="flex items-center gap-2"> <p className="font-medium"> {task.title.replace("Feed Tank ", "Feed Tank : ")} </p> <Badge className={STATUS_BADGE_CLASS[task.status]} variant="outline" > {task.status} </Badge> </div> <p className="text-xs text-gray-500">ID: {task.id}</p> </div>
<p className="text-sm text-gray-700"> {task.description || "No description provided."} </p>
<div className="grid grid-cols-1 md:grid-cols-3 gap-2 text-xs text-gray-600"> <p>Assigned To: {task.assignedToUserId || "N/A"}</p> <p>Due: {formatDateTime(task.dueAt)}</p> <p>Created: {formatDateTime(task.createdAt)}</p> </div>
<div className="flex flex-wrap gap-2"> {canStart && isWorker && ( <Button size="sm" variant="outline" disabled={isBusy} onClick={() => void handleUpdateStatus(task, "IN_PROGRESS") } > <Clock3 className="w-3 h-3 mr-1" /> Start </Button> )}
{canComplete && isWorker && ( <Button size="sm" disabled={isBusy} onClick={() => void handleUpdateStatus(task, "DONE")} > <CheckCircle2 className="w-3 h-3 mr-1" /> Mark Done </Button> )}
{canCancel && isWorker && ( <Button size="sm" variant="ghost" className="text-red-600 hover:text-red-700" disabled={isBusy} onClick={() => void handleDeleteTask(task)} > <Trash2 className="w-3 h-3 mr-1" /> Cancel </Button> )} </div> </div> ); })} </CardContent> </Card> </div> );}.dockerignoreAdded+20
.github/workflows/sync-to-huggen-face.ymlAdded+54
.gitignoreAdded+12
BACKEND_INFO.mdAdded+20
DockerfileAdded+28
README.mdAdded+10
Swagger UI.htmlAdded
batches.jsonAdded
docker-compose.ymlAdded+16
index.htmlAdded+16
jest.config.cjsAdded+18
jest.setup.jsAdded+1
package-lock.jsonAdded
package.jsonAdded+77
pnpm-lock.yamlAdded
src/.babelrcAdded+7
src/App.tsxAdded+484
src/Attributions.mdAdded+3
src/FISH_TYPE_ENHANCEMENTS_README.mdAdded+427
src/GROWTH_TRACKING_README.mdAdded+301
src/HARVEST_MODULE_README.mdAdded+338
src/HARVEST_PER_TANK_UPDATES.mdAdded+204
src/api.tsAdded+94
src/api/inventoryApi.tsAdded+57
src/components/AIAssistant.tsxAdded+969
src/components/Accounting.tsxAdded+12
src/components/AllocateFishToTank.tsxAdded+387
src/components/Analytics.tsxAdded+508
src/components/Combobox.tsxAdded+120
src/components/Dashboard.tsxAdded+754
src/components/Farms.tsxAdded+366
src/components/FishTypeManagement.tsxAdded+1
src/components/FishTypeManagementEnhanced.tsxAdded+1745
src/components/FoodTypeManagement.tsxAdded+500
src/components/HarvestManagement.tsxAdded+1492
src/components/HealthLibrary.tsxAdded+1507
src/components/Inventory.tsxAdded+2562
src/components/IoTManagement.tsxAdded+339
src/components/Login.tsxAdded+324
src/components/MedicineTypeManagement.tsxAdded+483
src/components/NotificationCenter.tsxAdded+618
src/components/Procurement.tsxAdded+2401
src/components/ResponsiveComponents.tsxAdded+76
src/components/ResponsivePageHeader.tsxAdded+25
src/components/ResponsivePageLayout.tsxAdded+35
src/components/ResponsiveTable.tsxAdded+37
src/components/SalesModule.tsxAdded+199
src/components/Sidebar.tsxAdded+185
src/components/TankManagement.tsxAdded+600
src/components/Tasks.tsxAdded+338