Spaces:
Running
Running
File size: 14,885 Bytes
f287aeb | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 | import { 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>
);
}
|