diff --git a/app/src/components/layout/scenes/ComparisonScene.tsx b/app/src/components/layout/scenes/ComparisonScene.tsx index bb63015..38d65cb 100644 --- a/app/src/components/layout/scenes/ComparisonScene.tsx +++ b/app/src/components/layout/scenes/ComparisonScene.tsx @@ -27,6 +27,7 @@ export interface CompareProduct { simulationTime?: number; simulationCost?: number; efficiencyScore?: number; + energyUsage?: number; }; } @@ -52,6 +53,7 @@ const calculateSimulationData = (assets: AssetData[]) => { transfer: 20, storageUnit: 10, }; + const energyUsage = assets.filter((a) => a.type === "human").reduce((sum, a) => sum + a.activeTime * 1, 0); assets.forEach((asset) => { totalActiveTime += asset.activeTime; @@ -90,6 +92,7 @@ const calculateSimulationData = (assets: AssetData[]) => { simulationTime, simulationCost, efficiencyScore, + energyUsage, }; }; @@ -102,11 +105,13 @@ export const createCompareProduct = (productUuid: string, productName: string, a function ComparisonScene() { const { isPlaying } = usePlayButtonStore(); const { productStore } = useSceneContext(); - const { products } = productStore(); + const { products, getProductById } = productStore(); const { isVersionSaved } = useSaveVersion(); + const { activeModule } = useModuleStore(); const { selectedProductStore } = useProductContext(); const { selectedProduct } = selectedProductStore(); + const { comparisonProduct, setComparisonProduct } = useComparisonProduct(); const { mainProduct } = useMainProduct(); const { loadingProgress } = useLoadingProgress(); @@ -171,15 +176,15 @@ function ComparisonScene() { // useEffect(() => { - // console.log('mainProduct: ', mainProduct); - // console.log('comparisonProduct: ', comparisonProduct); + // + // // if (mainProduct && comparisonProduct) { // // if (mainProduct && comparisonProduct && compareProductsData.length > 1) { - // // console.log('compareProductsData: ', compareProductsData); + // // // const hasMain = compareProductsData.some(val => val.productUuid === mainProduct.productUuid); // const hasComparison = compareProductsData.some(val => val.productUuid === comparisonProduct.productUuid); - // console.log('hasMain: ', hasMain); - // console.log('hasComparison: ', hasComparison); + // + // // if (hasMain && hasComparison) { // setShouldShowComparisonResult(true); // } else { @@ -189,20 +194,20 @@ function ComparisonScene() { // }, [compareProductsData, mainProduct, comparisonProduct]); useEffect(() => { + const selectedProductData = getProductById(selectedProduct.productUuid); if (mainProduct && comparisonProduct && selectedVersion) { const product1 = useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, mainProduct.productUuid); const product2 = useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, comparisonProduct.productUuid); - const compareProduct1 = createCompareProduct(product1?.productId ?? "", mainProduct.productName, product1?.data || []); - const compareProduct2 = createCompareProduct(product2?.productId ?? "", comparisonProduct.productName, product2?.data || []); + const compareProduct1 = createCompareProduct(product1?.productId ?? "", mainProduct.productName, product1?.simulateData || []); + const compareProduct2 = createCompareProduct(product2?.productId ?? "", comparisonProduct.productName, product2?.simulateData || []); const comparedArray = [compareProduct1, compareProduct2]; if (product1 == undefined || product2 === undefined) { setShouldShowComparisonResult(false); } else if (comparedArray.length === 2) { - console.log("comparedArray: ", comparedArray); setCompareProductsData(comparedArray); setShouldShowComparisonResult(true); } diff --git a/app/src/components/layout/scenes/MainScene.tsx b/app/src/components/layout/scenes/MainScene.tsx index 8076ec2..79e1958 100644 --- a/app/src/components/layout/scenes/MainScene.tsx +++ b/app/src/components/layout/scenes/MainScene.tsx @@ -54,7 +54,7 @@ function MainScene() { const { assetStore, productStore } = useSceneContext(); const { products } = productStore(); const { setName, selectedAssets, setSelectedAssets } = assetStore(); - const { projectId } = useParams() + const { projectId } = useParams(); const { organization, userId } = getUserData(); const { isRenameMode, setIsRenameMode } = useRenameModeStore(); const { versionHistory } = useVersionHistoryStore(); @@ -66,15 +66,15 @@ function MainScene() { useEffect(() => { return () => { resetStates(); - } - }, []) + }; + }, []); useEffect(() => { - if (activeModule !== 'simulation') { + if (activeModule !== "simulation") { clearComparisonProduct(); setIsVersionSaved(false); } - }, [activeModule, clearComparisonProduct, setIsVersionSaved]) + }, [activeModule, clearComparisonProduct, setIsVersionSaved]); useEffect(() => { if (versionHistory.length > 0 && organization && userId) { @@ -88,9 +88,9 @@ function MainScene() { } else { setSelectedVersion(versionHistory[0]); } - }) + }); } - }, [setSelectedVersion, versionHistory, projectId]) + }, [setSelectedVersion, versionHistory, projectId]); const handleSelectVersion = (option: string) => { const version = versionHistory.find((version) => version.versionName === option); @@ -107,33 +107,33 @@ function MainScene() { }; const handleObjectRename = async (newName: string) => { - if (!projectId) return + if (!projectId) return; if (selectedFloorAsset) { setAssetsApi({ modelUuid: selectedFloorAsset.userData.modelUuid, modelName: newName, projectId, - versionId: selectedVersion?.versionId || '' + versionId: selectedVersion?.versionId || "", }).then(() => { selectedFloorAsset.userData = { ...selectedFloorAsset.userData, modelName: newName }; setSelectedFloorAsset(selectedFloorAsset); setIsRenameMode(false); setName(selectedFloorAsset.userData.modelUuid, newName); - }) + }); } else if (selectedAssets.length === 1) { setAssetsApi({ modelUuid: selectedAssets[0].userData.modelUuid, modelName: newName, projectId, - versionId: selectedVersion?.versionId || '' + versionId: selectedVersion?.versionId || "", }).then(() => { selectedAssets[0].userData = { ...selectedAssets[0].userData, modelName: newName }; setSelectedAssets(selectedAssets); setIsRenameMode(false); setName(selectedAssets[0].userData.modelUuid, newName); - }) + }); } - } + }; return ( <> @@ -150,11 +150,9 @@ function MainScene() { )} {activeModule === "market" && } - {activeModule !== "market" && !isPlaying && !isVersionSaved && ( - - )} - {(isPlaying) && activeModule === "simulation" && loadingProgress === 0 && } - {(isPlaying) && activeModule !== "simulation" && } + {activeModule !== "market" && !isPlaying && !isVersionSaved && } + {isPlaying && activeModule === "simulation" && loadingProgress === 0 && } + {isPlaying && activeModule !== "simulation" && } {isRenameMode && (selectedFloorAsset?.userData.modelName || selectedAssets.length === 1) && } {/* remove this later */} @@ -168,8 +166,7 @@ function MainScene() { height: isPlaying || activeModule !== "visualization" ? "100vh" : "", width: isPlaying || activeModule !== "visualization" ? "100vw" : "", left: isPlaying || activeModule !== "visualization" ? "0%" : "", - borderRadius: - isPlaying || activeModule !== "visualization" ? "" : "6px", + borderRadius: isPlaying || activeModule !== "visualization" ? "" : "6px", }} role="application" onDrop={(event) => @@ -180,7 +177,7 @@ function MainScene() { setFloatingWidget, event, projectId, - versionId: selectedVersion?.versionId || '', + versionId: selectedVersion?.versionId || "", }) } onDragOver={(event) => event.preventDefault()} @@ -210,11 +207,7 @@ function MainScene() { - { - (commentPositionState !== null || selectedComment !== null) && - - } - + {(commentPositionState !== null || selectedComment !== null) && } ); } diff --git a/app/src/components/layout/scenes/functions/simulationStorage.ts b/app/src/components/layout/scenes/functions/simulationStorage.ts index 2e4b428..3dcced5 100644 --- a/app/src/components/layout/scenes/functions/simulationStorage.ts +++ b/app/src/components/layout/scenes/functions/simulationStorage.ts @@ -1,14 +1,93 @@ +let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}`; interface SimulationData { - key: string; - data?: object | any; + key: string; + data?: object | any; } -export const saveSimulationData = ({ key, data }: SimulationData) => { - console.log("key: ", key); - localStorage.setItem(key, JSON.stringify(data)); +interface SimulationUsageRecord { + activeTime: number; + isActive: boolean; + idleTime: number; + type: "roboticArm" | "vehicle" | "transfer" | "storageUnit" | "crane" | "human" | "machine"; + assetId: string; +} + +// Product → holds multiple usage records +interface ProductSimulation { + productId: string; + simulateData: SimulationUsageRecord[]; +} + +// Version → holds multiple products +interface VersionSimulation { + versionId: string; + products: ProductSimulation[]; +} + +// Project → holds multiple versions +interface ProjectSimulation { + projectId: string | undefined; + versions: VersionSimulation[]; +} +export const saveSimulationData = async (data: any) => { + try { + const response = await fetch(`${url_Backend_dwinzo}/api/V1/SimulatedUpsert`, { + method: "POST", + headers: { + Authorization: "Bearer ", + "Content-Type": "application/json", + token: localStorage.getItem("token") || "", + refresh_token: localStorage.getItem("refreshToken") || "", + }, + body: JSON.stringify(data), + }); + const newAccessToken = response.headers.get("x-access-token"); + if (newAccessToken) { + localStorage.setItem("token", newAccessToken); + } + if (!response.ok) { + console.error("Failed to add project"); + } + + const result = await response.json(); + + return result; + } catch (error) { + if (error instanceof Error) { + console.log(error.message); + } else { + console.log("An unknown error occurred"); + } + } }; -export const getSimulationData = ({ key }: SimulationData) => { - const data = localStorage.getItem(key); - console.log("data: ", JSON.parse(data || "{}")); - return data; +export const getSimulationData = async (data: any) => { + try { + const response = await fetch(`${url_Backend_dwinzo}/api/V1/ValidateSimulated`, { + method: "POST", + headers: { + Authorization: "Bearer ", + "Content-Type": "application/json", + token: localStorage.getItem("token") || "", + refresh_token: localStorage.getItem("refreshToken") || "", + }, + body: JSON.stringify(data), + }); + const newAccessToken = response.headers.get("x-access-token"); + if (newAccessToken) { + localStorage.setItem("token", newAccessToken); + } + if (!response.ok) { + console.error("Failed to add project"); + } + + const result = await response.json(); + + return result; + } catch (error) { + if (error instanceof Error) { + console.log(error.message); + } else { + console.log("An unknown error occurred"); + } + } }; export const clearSimulationData = ({ key, data }: SimulationData) => {}; diff --git a/app/src/components/ui/compareVersion/ComparisonResult.tsx b/app/src/components/ui/compareVersion/ComparisonResult.tsx index 6e2b751..388a111 100644 --- a/app/src/components/ui/compareVersion/ComparisonResult.tsx +++ b/app/src/components/ui/compareVersion/ComparisonResult.tsx @@ -135,7 +135,6 @@ const ComparisonResult = () => {
Performance Comparison
-

Throughput (units/hr)

@@ -179,7 +178,7 @@ const ComparisonResult = () => {
- + {/* */}
Overall Downtime
diff --git a/app/src/components/ui/compareVersion/result-card/EnergyUsage.tsx b/app/src/components/ui/compareVersion/result-card/EnergyUsage.tsx index 0c453a4..b343ca9 100644 --- a/app/src/components/ui/compareVersion/result-card/EnergyUsage.tsx +++ b/app/src/components/ui/compareVersion/result-card/EnergyUsage.tsx @@ -1,113 +1,174 @@ import React, { useMemo } from "react"; import { Line } from "react-chartjs-2"; -import { - Chart as ChartJS, - LineElement, - PointElement, - CategoryScale, - LinearScale, - Tooltip, - Legend, -} from "chart.js"; +import { Chart as ChartJS, LineElement, PointElement, CategoryScale, LinearScale, Tooltip, Legend } from "chart.js"; -ChartJS.register( - LineElement, - PointElement, - CategoryScale, - LinearScale, - Tooltip, - Legend -); +ChartJS.register(LineElement, PointElement, CategoryScale, LinearScale, Tooltip, Legend); -const EnergyUsage = ({comparedProducts}:any) => { - const data = useMemo(() => { - const randomizeData = () => - Array.from({ length: 5 }, () => Math.floor(Math.random() * (2000 - 300 + 1)) + 300); +// const EnergyUsage = ({comparedProducts}:any) => { +// const data = useMemo(() => { +// const randomizeData = () => +// Array.from({ length: 5 }, () => Math.floor(Math.random() * (2000 - 300 + 1)) + 300); - return { - labels: ["Mon", "Tue", "Wed", "Thu", "Fri"], - datasets: [ - { - label: "Simulation 1", - data: randomizeData(), - borderColor: "#6a0dad", - fill: false, - tension: 0.5, // More curved line - pointRadius: 0, // Remove point indicators - }, - { - label: "Simulation 2", - data: randomizeData(), - borderColor: "#b19cd9", - fill: false, - tension: 0.5, - pointRadius: 0, - }, - ], - }; - }, []); +// return { +// labels: ["Mon", "Tue", "Wed", "Thu", "Fri"], +// datasets: [ +// { +// label: "Simulation 1", +// data: randomizeData(), +// borderColor: "#6a0dad", +// fill: false, +// tension: 0.5, // More curved line +// pointRadius: 0, // Remove point indicators +// }, +// { +// label: "Simulation 2", +// data: randomizeData(), +// borderColor: "#b19cd9", +// fill: false, +// tension: 0.5, +// pointRadius: 0, +// }, +// ], +// }; +// }, []); - const options = useMemo( - () => ({ - responsive: true, - maintainAspectRatio: false, - plugins: { - title: { - display: true, - }, - legend: { - display: false, - }, - }, - scales: { - x: { - display: false, // Hide x-axis - grid: { - display: false, - }, - }, - y: { - display: false, // Hide y-axis - grid: { - display: false, - }, - }, - }, - }), - [] - ); +// const options = useMemo( +// () => ({ +// responsive: true, +// maintainAspectRatio: false, +// plugins: { +// title: { +// display: true, +// }, +// legend: { +// display: false, +// }, +// }, +// scales: { +// x: { +// display: false, // Hide x-axis +// grid: { +// display: false, +// }, +// }, +// y: { +// display: false, // Hide y-axis +// grid: { +// display: false, +// }, +// }, +// }, +// }), +// [] +// ); - return ( -
-
-

Energy Usage

-

- 2500 kWh -

-
+// return ( +//
+//
+//

Energy Usage

+//

+// 2500 kWh +//

+//
-
-
-
-
-
{comparedProducts[0]?.productName}
-
98%
-
+//
+//
+//
+//
+//
{comparedProducts[0]?.productName}
+//
98%
+//
+//
+//
+//
+//
+//
{comparedProducts[1]?.productName}
+//
97%
+//
+//
+//
+ +//
+// +//
+//
+// ); +// }; + +// export default EnergyUsage; + +const EnergyUsage = ({ comparedProducts }: any) => { + const data = useMemo(() => { + return { + labels: ["Mon", "Tue", "Wed", "Thu", "Fri"], + datasets: comparedProducts.map((product: any, idx: number) => ({ + label: product.productName, + // use actual energyUsage instead of random data + data: Array(5).fill(product.simulationData.energyUsage), + borderColor: idx === 0 ? "#6a0dad" : "#b19cd9", + fill: false, + tension: 0.5, + pointRadius: 0, + })), + }; + }, [comparedProducts]); + + const options = useMemo( + () => ({ + responsive: true, + maintainAspectRatio: false, + plugins: { + title: { + display: true, + }, + legend: { + display: false, + }, + }, + scales: { + x: { + display: false, + grid: { + display: false, + }, + }, + y: { + display: false, + grid: { + display: false, + }, + }, + }, + }), + [] + ); + + return ( +
+
+

Energy Usage

+

+ {comparedProducts.reduce((acc: number, p: any) => acc + (p.simulationData.energyUsage || 0), 0)} kWh +

+
+ +
+ {comparedProducts.map((product: any, idx: number) => ( +
+
+
+
{product.productName}
+
{product.simulationData.energyUsage} kWh
+
+
+ ))} +
+ +
+ +
-
-
-
-
{comparedProducts[1]?.productName}
-
97%
-
-
-
- -
- -
-
- ); + ); }; export default EnergyUsage; diff --git a/app/src/components/ui/simulation/simulationPlayer.tsx b/app/src/components/ui/simulation/simulationPlayer.tsx index f6ff314..5875ee5 100644 --- a/app/src/components/ui/simulation/simulationPlayer.tsx +++ b/app/src/components/ui/simulation/simulationPlayer.tsx @@ -68,7 +68,7 @@ const SimulationPlayer: React.FC = () => { useEffect(() => { if (materialData.length === 0) return; console.log('materialData: ', materialData); - saveSimulationData({ key: selectedProduct.productUuid, data: materialData }); + // saveSimulationData({ key: selectedProduct.productUuid, data: materialData }); }, [materialData]) // Button functions diff --git a/app/src/modules/simulation/analysis/ROI/roiData.tsx b/app/src/modules/simulation/analysis/ROI/roiData.tsx index 8720faa..6c9ae61 100644 --- a/app/src/modules/simulation/analysis/ROI/roiData.tsx +++ b/app/src/modules/simulation/analysis/ROI/roiData.tsx @@ -149,7 +149,7 @@ export default function ROIData() { } console.log('selectedProduct.productUuid: ', selectedProduct.productUuid); - saveSimulationData({ key: selectedProduct.productUuid, data: data }); + // saveSimulationData({ key: selectedProduct.productUuid, data: data }); const datas = { roi: data } diff --git a/app/src/modules/simulation/analysis/productionCapacity/productionCapacityData.tsx b/app/src/modules/simulation/analysis/productionCapacity/productionCapacityData.tsx index f17ba57..c50b167 100644 --- a/app/src/modules/simulation/analysis/productionCapacity/productionCapacityData.tsx +++ b/app/src/modules/simulation/analysis/productionCapacity/productionCapacityData.tsx @@ -25,7 +25,7 @@ export default function ProductionCapacityData() { const Monthly_working_days = workingDaysPerYear / 12; const Production_capacity_per_month = throughputData * Monthly_working_days; const data = Number(Production_capacity_per_month.toFixed(2)); - saveSimulationData({ key: 'productionCapacity', data: data }); + // saveSimulationData({ key: 'productionCapacity', data: data }); setMaterialData({ ...materialData, productionCapacity: data }); setProductionCapacityData(Number(Production_capacity_per_month.toFixed(2))); } diff --git a/app/src/modules/simulation/analysis/throughPut/throughPutData.tsx b/app/src/modules/simulation/analysis/throughPut/throughPutData.tsx index c5e771d..e589479 100644 --- a/app/src/modules/simulation/analysis/throughPut/throughPutData.tsx +++ b/app/src/modules/simulation/analysis/throughPut/throughPutData.tsx @@ -222,7 +222,7 @@ export default function ThroughPutData() { const Throughput_per_day = Units_per_shift * shiftsPerDay * (yieldRate / 100); const data = Number(Throughput_per_day.toFixed(2)) console.log('data: ', data); - saveSimulationData({ key: selectedProduct.productUuid, data: data }); + // saveSimulationData({ key: selectedProduct.productUuid, data: data }); setMaterialData({ ...materialData, throughput: data }); setThroughputData(Number(Throughput_per_day.toFixed(2))); // Keep as number diff --git a/app/src/modules/simulation/simulator/SimulationHandler.tsx b/app/src/modules/simulation/simulator/SimulationHandler.tsx index f8c8615..08fbfe4 100644 --- a/app/src/modules/simulation/simulator/SimulationHandler.tsx +++ b/app/src/modules/simulation/simulator/SimulationHandler.tsx @@ -1,4 +1,4 @@ -import React, { useEffect } from "react"; +import React, { useEffect, useState } from "react"; import { useSceneContext } from "../../scene/sceneContext"; import { useProductContext } from "../products/productContext"; import { determineExecutionMachineSequences } from "./functions/determineExecutionMachineSequences"; @@ -8,18 +8,13 @@ import { useParams } from "react-router-dom"; import { useVersionContext } from "../../builder/version/versionContext"; import { getSimulationData, saveSimulationData } from "../../../components/layout/scenes/functions/simulationStorage"; import { get } from "http"; +import { set } from "immer/dist/internal"; interface SimulationUsageRecord { activeTime: number; isActive: boolean; idleTime: number; - type: - | "roboticArm" - | "vehicle" - | "transfer" - | "storageUnit" - | "crane" - | "human" - | "machine"; + type: "roboticArm" | "vehicle" | "transfer" | "storageUnit" | "crane" | "human" | "machine"; + assetId: string; } // Product → holds multiple usage records @@ -40,17 +35,7 @@ interface ProjectSimulation { versions: VersionSimulation[]; } const SimulationHandler = () => { - const { - materialStore, - armBotStore, - machineStore, - conveyorStore, - vehicleStore, - storageUnitStore, - productStore, - craneStore, - humanStore, - } = useSceneContext(); + const { materialStore, armBotStore, machineStore, conveyorStore, vehicleStore, storageUnitStore, productStore, craneStore, humanStore } = useSceneContext(); const { armBots, getArmBotById } = armBotStore(); const { vehicles, getVehicleById } = vehicleStore(); const { getConveyorById } = conveyorStore(); @@ -67,6 +52,7 @@ const SimulationHandler = () => { const { projectId } = useParams(); const { selectedVersionStore } = useVersionContext(); const { selectedVersion } = selectedVersionStore(); + const [simulationEntry, setSimulationEntry] = useState(); const COST_RATES: Record = { roboticArm: 5, vehicle: 2, @@ -135,31 +121,72 @@ const SimulationHandler = () => { return { ...m, efficiencyScore }; }); } + useEffect(() => { + const runSimulation = async () => { + console.log("simulationRecords: ", simulationRecords); + if (!projectId || !selectedVersion || !selectedProduct.productUuid || simulationRecords.length === 0) return; + + const project = simulationRecords[0]; + + if (project) { + // const scores = calculateEfficiencyScores(project.versions); + // console.log("Version Comparisons:", scores); + } + console.log("simulationEntry: ", simulationEntry); + console.log("simulationEntrysaddasd: ", useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, selectedProduct.productUuid)?.simulateData); + + const data = { + projectId: projectId, + versionId: selectedVersion.versionId, + productUuid: selectedProduct.productUuid, + simulateData: useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, selectedProduct.productUuid)?.simulateData, + }; + + const simulations = await saveSimulationData(data); + if (simulations.message === "SimulatedData created Successfully") { + setSimulationEntry(simulations.data); + } + console.log("Saved simulations:", simulations); + }; + + runSimulation(); + }, [simulationRecords, projectId, selectedVersion, selectedProduct, simulationEntry]); + + // useEffect(() => { + // console.log('simulationRecords: ', simulationRecords); + // if (!projectId || !selectedVersion || !selectedProduct.productUuid || simulationRecords.length === 0) return; + + // const project = simulationRecords[0]; + + // if (project) { + // const scores = calculateEfficiencyScores(project.versions); + // console.log("Version Comparisons:", scores); + // } + + // saveSimulationData({ + // key: selectedProduct.productUuid, + // data: simulationRecords, + // }); + // // saveSimulationData({ + // // key: selectedProduct.productUuid, + // // data: simulationRecords, + // // }); + // }, [simulationRecords]); useEffect(() => { - console.log('simulationRecords: ', simulationRecords); - if (!projectId || !selectedVersion || !selectedProduct.productUuid || simulationRecords.length === 0) return; - - const project = simulationRecords[0]; - - if (project) { - const scores = calculateEfficiencyScores(project.versions); - console.log("Version Comparisons:", scores); - } - - saveSimulationData({ - key: selectedProduct.productUuid, - data: simulationRecords, - }); - }, [simulationRecords]); - - useEffect(() => { - const simData = getSimulationData({ key: selectedProduct.productUuid }); - if (simData) { - useSimulationManager.getState().setSimulationRecords(JSON.parse(simData)); - // Parse and set in the store - } else { } - }, []) + const fetchSimulationData = async () => { + if (!projectId || !selectedVersion || !selectedProduct.productUuid) return; + const data = { + projectId: projectId, + versionId: selectedVersion.versionId, + productUuid: selectedProduct.productUuid, + simulatedId: simulationEntry, + }; + const datas = await getSimulationData(data); + console.log("datas: ", datas); + }; + fetchSimulationData(); + }, []); useEffect(() => { let checkTimer: ReturnType; @@ -169,9 +196,7 @@ const SimulationHandler = () => { let hasActiveEntity = false; if (currentProduct) { - const executionSequences = await determineExecutionMachineSequences([ - currentProduct, - ]); + const executionSequences = await determineExecutionMachineSequences([currentProduct]); if (executionSequences?.length > 0) { executionSequences.forEach((sequence) => { sequence.forEach((entity) => { @@ -221,11 +246,7 @@ const SimulationHandler = () => { }); } - if ( - materials.length === 0 && - materialHistory.length >= 0 && - !hasActiveEntity - ) { + if (materials.length === 0 && materialHistory.length >= 0 && !hasActiveEntity) { if (executionSequences?.length > 0) { executionSequences.forEach((sequence) => { sequence.forEach((entity) => { @@ -245,25 +266,13 @@ const SimulationHandler = () => { const obj = getter(entity.modelUuid); if (!obj) return; // skip if not found - addSimulationRecord( - projectId, - selectedVersion?.versionId || "", - selectedProduct?.productUuid, - { - activeTime: obj.activeTime ?? 0, - isActive: obj.isActive ?? false, - idleTime: obj.idleTime ?? 0, - type: entity.type as - | "roboticArm" - | "vehicle" - | "machine" - | "human" - | "crane" - | "storageUnit" - | "transfer", - assetId: entity.modelUuid, - } - ); + addSimulationRecord(projectId, selectedVersion?.versionId || "", selectedProduct?.productUuid, { + activeTime: obj.activeTime ?? 0, + isActive: obj.isActive ?? false, + idleTime: obj.idleTime ?? 0, + type: entity.type as "roboticArm" | "vehicle" | "machine" | "human" | "crane" | "storageUnit" | "transfer", + assetId: entity.modelUuid, + }); }); }); } @@ -281,16 +290,7 @@ const SimulationHandler = () => { return () => { if (checkTimer) clearTimeout(checkTimer); }; - }, [ - materials, - materialHistory, - selectedVersion, - selectedProduct?.productUuid, - isPlaying, - armBots, - vehicles, - machines, - ]); + }, [materials, materialHistory, selectedVersion, selectedProduct?.productUuid, isPlaying, armBots, vehicles, machines]); return null; }; diff --git a/app/src/store/rough/useSimulationManagerStore.ts b/app/src/store/rough/useSimulationManagerStore.ts index a8c82a4..77b6d5a 100644 --- a/app/src/store/rough/useSimulationManagerStore.ts +++ b/app/src/store/rough/useSimulationManagerStore.ts @@ -11,7 +11,7 @@ interface SimulationUsageRecord { // Product → holds multiple usage records interface ProductSimulation { productId: string; - data: SimulationUsageRecord[]; + simulateData: SimulationUsageRecord[]; } // Version → holds multiple products @@ -29,7 +29,7 @@ interface ProjectSimulation { interface SimulationManagerStore { simulationRecords: ProjectSimulation[]; - setSimulationRecords: (data: ProjectSimulation[]) => void; + setSimulationRecords: (simulateData: ProjectSimulation[]) => void; addSimulationRecord: (projectId: string | undefined, versionId: string, productId: string, record: SimulationUsageRecord) => void; resetProductRecords: (projectId: string, versionId: string, productId: string) => void; @@ -53,7 +53,7 @@ export const useSimulationManager = create((set, get) => return { ...version, - products: version.products.map((product) => (product.productId === productId ? { ...product, data: [...product.data, record] } : product)), + products: version.products.map((product) => (product.productId === productId ? { ...product, simulateData: [...product.simulateData, record] } : product)), }; }), }; @@ -66,7 +66,7 @@ export const useSimulationManager = create((set, get) => versions: [ { versionId, - products: [{ productId, data: [record] }], + products: [{ productId, simulateData: [record] }], }, ], }); @@ -75,12 +75,12 @@ export const useSimulationManager = create((set, get) => if (!project.versions.find((v) => v.versionId === versionId)) { project.versions.push({ versionId, - products: [{ productId, data: [record] }], + products: [{ productId, simulateData: [record] }], }); } else { const version = project.versions.find((v) => v.versionId === versionId)!; if (!version.products.find((p) => p.productId === productId)) { - version.products.push({ productId, data: [record] }); + version.products.push({ productId, simulateData: [record] }); } } } @@ -100,7 +100,7 @@ export const useSimulationManager = create((set, get) => return { ...version, - products: version.products.map((product) => (product.productId === productId ? { ...product, data: [] } : product)), + products: version.products.map((product) => (product.productId === productId ? { ...product, simulateData: [] } : product)), }; }), }; @@ -108,8 +108,8 @@ export const useSimulationManager = create((set, get) => return { simulationRecords: projects }; }), - setSimulationRecords: (data) => { - set({ simulationRecords: data }); + setSimulationRecords: (simulateData) => { + set({ simulationRecords: simulateData }); }, getProjectById: (projectId: string | undefined) => { return get().simulationRecords.find((p: ProjectSimulation) => p.projectId === projectId);