layout worked with backend

This commit is contained in:
2025-09-06 09:24:10 +05:30
parent 901ecc0ec6
commit 0e8a004f70
11 changed files with 377 additions and 240 deletions

View File

@@ -27,6 +27,7 @@ export interface CompareProduct {
simulationTime?: number; simulationTime?: number;
simulationCost?: number; simulationCost?: number;
efficiencyScore?: number; efficiencyScore?: number;
energyUsage?: number;
}; };
} }
@@ -52,6 +53,7 @@ const calculateSimulationData = (assets: AssetData[]) => {
transfer: 20, transfer: 20,
storageUnit: 10, storageUnit: 10,
}; };
const energyUsage = assets.filter((a) => a.type === "human").reduce((sum, a) => sum + a.activeTime * 1, 0);
assets.forEach((asset) => { assets.forEach((asset) => {
totalActiveTime += asset.activeTime; totalActiveTime += asset.activeTime;
@@ -90,6 +92,7 @@ const calculateSimulationData = (assets: AssetData[]) => {
simulationTime, simulationTime,
simulationCost, simulationCost,
efficiencyScore, efficiencyScore,
energyUsage,
}; };
}; };
@@ -102,11 +105,13 @@ export const createCompareProduct = (productUuid: string, productName: string, a
function ComparisonScene() { function ComparisonScene() {
const { isPlaying } = usePlayButtonStore(); const { isPlaying } = usePlayButtonStore();
const { productStore } = useSceneContext(); const { productStore } = useSceneContext();
const { products } = productStore(); const { products, getProductById } = productStore();
const { isVersionSaved } = useSaveVersion(); const { isVersionSaved } = useSaveVersion();
const { activeModule } = useModuleStore(); const { activeModule } = useModuleStore();
const { selectedProductStore } = useProductContext(); const { selectedProductStore } = useProductContext();
const { selectedProduct } = selectedProductStore(); const { selectedProduct } = selectedProductStore();
const { comparisonProduct, setComparisonProduct } = useComparisonProduct(); const { comparisonProduct, setComparisonProduct } = useComparisonProduct();
const { mainProduct } = useMainProduct(); const { mainProduct } = useMainProduct();
const { loadingProgress } = useLoadingProgress(); const { loadingProgress } = useLoadingProgress();
@@ -171,15 +176,15 @@ function ComparisonScene() {
// useEffect(() => { // useEffect(() => {
// console.log('mainProduct: ', mainProduct); //
// console.log('comparisonProduct: ', comparisonProduct); //
// if (mainProduct && comparisonProduct) { // if (mainProduct && comparisonProduct) {
// // if (mainProduct && comparisonProduct && compareProductsData.length > 1) { // // if (mainProduct && comparisonProduct && compareProductsData.length > 1) {
// // console.log('compareProductsData: ', compareProductsData); // //
// const hasMain = compareProductsData.some(val => val.productUuid === mainProduct.productUuid); // const hasMain = compareProductsData.some(val => val.productUuid === mainProduct.productUuid);
// const hasComparison = compareProductsData.some(val => val.productUuid === comparisonProduct.productUuid); // const hasComparison = compareProductsData.some(val => val.productUuid === comparisonProduct.productUuid);
// console.log('hasMain: ', hasMain); //
// console.log('hasComparison: ', hasComparison); //
// if (hasMain && hasComparison) { // if (hasMain && hasComparison) {
// setShouldShowComparisonResult(true); // setShouldShowComparisonResult(true);
// } else { // } else {
@@ -189,20 +194,20 @@ function ComparisonScene() {
// }, [compareProductsData, mainProduct, comparisonProduct]); // }, [compareProductsData, mainProduct, comparisonProduct]);
useEffect(() => { useEffect(() => {
const selectedProductData = getProductById(selectedProduct.productUuid);
if (mainProduct && comparisonProduct && selectedVersion) { if (mainProduct && comparisonProduct && selectedVersion) {
const product1 = useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, mainProduct.productUuid); const product1 = useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, mainProduct.productUuid);
const product2 = useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, comparisonProduct.productUuid); const product2 = useSimulationManager.getState().getProductById(projectId, selectedVersion?.versionId, comparisonProduct.productUuid);
const compareProduct1 = createCompareProduct(product1?.productId ?? "", mainProduct.productName, product1?.data || []); const compareProduct1 = createCompareProduct(product1?.productId ?? "", mainProduct.productName, product1?.simulateData || []);
const compareProduct2 = createCompareProduct(product2?.productId ?? "", comparisonProduct.productName, product2?.data || []); const compareProduct2 = createCompareProduct(product2?.productId ?? "", comparisonProduct.productName, product2?.simulateData || []);
const comparedArray = [compareProduct1, compareProduct2]; const comparedArray = [compareProduct1, compareProduct2];
if (product1 == undefined || product2 === undefined) { if (product1 == undefined || product2 === undefined) {
setShouldShowComparisonResult(false); setShouldShowComparisonResult(false);
} else if (comparedArray.length === 2) { } else if (comparedArray.length === 2) {
console.log("comparedArray: ", comparedArray);
setCompareProductsData(comparedArray); setCompareProductsData(comparedArray);
setShouldShowComparisonResult(true); setShouldShowComparisonResult(true);
} }

View File

@@ -54,7 +54,7 @@ function MainScene() {
const { assetStore, productStore } = useSceneContext(); const { assetStore, productStore } = useSceneContext();
const { products } = productStore(); const { products } = productStore();
const { setName, selectedAssets, setSelectedAssets } = assetStore(); const { setName, selectedAssets, setSelectedAssets } = assetStore();
const { projectId } = useParams() const { projectId } = useParams();
const { organization, userId } = getUserData(); const { organization, userId } = getUserData();
const { isRenameMode, setIsRenameMode } = useRenameModeStore(); const { isRenameMode, setIsRenameMode } = useRenameModeStore();
const { versionHistory } = useVersionHistoryStore(); const { versionHistory } = useVersionHistoryStore();
@@ -66,15 +66,15 @@ function MainScene() {
useEffect(() => { useEffect(() => {
return () => { return () => {
resetStates(); resetStates();
} };
}, []) }, []);
useEffect(() => { useEffect(() => {
if (activeModule !== 'simulation') { if (activeModule !== "simulation") {
clearComparisonProduct(); clearComparisonProduct();
setIsVersionSaved(false); setIsVersionSaved(false);
} }
}, [activeModule, clearComparisonProduct, setIsVersionSaved]) }, [activeModule, clearComparisonProduct, setIsVersionSaved]);
useEffect(() => { useEffect(() => {
if (versionHistory.length > 0 && organization && userId) { if (versionHistory.length > 0 && organization && userId) {
@@ -88,9 +88,9 @@ function MainScene() {
} else { } else {
setSelectedVersion(versionHistory[0]); setSelectedVersion(versionHistory[0]);
} }
}) });
} }
}, [setSelectedVersion, versionHistory, projectId]) }, [setSelectedVersion, versionHistory, projectId]);
const handleSelectVersion = (option: string) => { const handleSelectVersion = (option: string) => {
const version = versionHistory.find((version) => version.versionName === option); const version = versionHistory.find((version) => version.versionName === option);
@@ -107,33 +107,33 @@ function MainScene() {
}; };
const handleObjectRename = async (newName: string) => { const handleObjectRename = async (newName: string) => {
if (!projectId) return if (!projectId) return;
if (selectedFloorAsset) { if (selectedFloorAsset) {
setAssetsApi({ setAssetsApi({
modelUuid: selectedFloorAsset.userData.modelUuid, modelUuid: selectedFloorAsset.userData.modelUuid,
modelName: newName, modelName: newName,
projectId, projectId,
versionId: selectedVersion?.versionId || '' versionId: selectedVersion?.versionId || "",
}).then(() => { }).then(() => {
selectedFloorAsset.userData = { ...selectedFloorAsset.userData, modelName: newName }; selectedFloorAsset.userData = { ...selectedFloorAsset.userData, modelName: newName };
setSelectedFloorAsset(selectedFloorAsset); setSelectedFloorAsset(selectedFloorAsset);
setIsRenameMode(false); setIsRenameMode(false);
setName(selectedFloorAsset.userData.modelUuid, newName); setName(selectedFloorAsset.userData.modelUuid, newName);
}) });
} else if (selectedAssets.length === 1) { } else if (selectedAssets.length === 1) {
setAssetsApi({ setAssetsApi({
modelUuid: selectedAssets[0].userData.modelUuid, modelUuid: selectedAssets[0].userData.modelUuid,
modelName: newName, modelName: newName,
projectId, projectId,
versionId: selectedVersion?.versionId || '' versionId: selectedVersion?.versionId || "",
}).then(() => { }).then(() => {
selectedAssets[0].userData = { ...selectedAssets[0].userData, modelName: newName }; selectedAssets[0].userData = { ...selectedAssets[0].userData, modelName: newName };
setSelectedAssets(selectedAssets); setSelectedAssets(selectedAssets);
setIsRenameMode(false); setIsRenameMode(false);
setName(selectedAssets[0].userData.modelUuid, newName); setName(selectedAssets[0].userData.modelUuid, newName);
}) });
} }
} };
return ( return (
<> <>
@@ -150,11 +150,9 @@ function MainScene() {
)} )}
<RealTimeVisulization /> <RealTimeVisulization />
{activeModule === "market" && <MarketPlace />} {activeModule === "market" && <MarketPlace />}
{activeModule !== "market" && !isPlaying && !isVersionSaved && ( {activeModule !== "market" && !isPlaying && !isVersionSaved && <Tools />}
<Tools /> {isPlaying && activeModule === "simulation" && loadingProgress === 0 && <SimulationPlayer />}
)} {isPlaying && activeModule !== "simulation" && <ControlsPlayer />}
{(isPlaying) && activeModule === "simulation" && loadingProgress === 0 && <SimulationPlayer />}
{(isPlaying) && activeModule !== "simulation" && <ControlsPlayer />}
{isRenameMode && (selectedFloorAsset?.userData.modelName || selectedAssets.length === 1) && <RenameTooltip name={selectedFloorAsset?.userData.modelName || selectedAssets[0].userData.modelName} onSubmit={handleObjectRename} />} {isRenameMode && (selectedFloorAsset?.userData.modelName || selectedAssets.length === 1) && <RenameTooltip name={selectedFloorAsset?.userData.modelName || selectedAssets[0].userData.modelName} onSubmit={handleObjectRename} />}
{/* remove this later */} {/* remove this later */}
@@ -168,8 +166,7 @@ function MainScene() {
height: isPlaying || activeModule !== "visualization" ? "100vh" : "", height: isPlaying || activeModule !== "visualization" ? "100vh" : "",
width: isPlaying || activeModule !== "visualization" ? "100vw" : "", width: isPlaying || activeModule !== "visualization" ? "100vw" : "",
left: isPlaying || activeModule !== "visualization" ? "0%" : "", left: isPlaying || activeModule !== "visualization" ? "0%" : "",
borderRadius: borderRadius: isPlaying || activeModule !== "visualization" ? "" : "6px",
isPlaying || activeModule !== "visualization" ? "" : "6px",
}} }}
role="application" role="application"
onDrop={(event) => onDrop={(event) =>
@@ -180,7 +177,7 @@ function MainScene() {
setFloatingWidget, setFloatingWidget,
event, event,
projectId, projectId,
versionId: selectedVersion?.versionId || '', versionId: selectedVersion?.versionId || "",
}) })
} }
onDragOver={(event) => event.preventDefault()} onDragOver={(event) => event.preventDefault()}
@@ -210,11 +207,7 @@ function MainScene() {
<VersionSaved /> <VersionSaved />
{ {(commentPositionState !== null || selectedComment !== null) && <ThreadChat />}
(commentPositionState !== null || selectedComment !== null) &&
<ThreadChat />
}
</> </>
); );
} }

View File

@@ -1,14 +1,93 @@
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}`;
interface SimulationData { interface SimulationData {
key: string; key: string;
data?: object | any; data?: object | any;
} }
export const saveSimulationData = ({ key, data }: SimulationData) => { interface SimulationUsageRecord {
console.log("key: ", key); activeTime: number;
localStorage.setItem(key, JSON.stringify(data)); 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 <access_token>",
"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) => { export const getSimulationData = async (data: any) => {
const data = localStorage.getItem(key); try {
console.log("data: ", JSON.parse(data || "{}")); const response = await fetch(`${url_Backend_dwinzo}/api/V1/ValidateSimulated`, {
return data; method: "POST",
headers: {
Authorization: "Bearer <access_token>",
"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) => {}; export const clearSimulationData = ({ key, data }: SimulationData) => {};

View File

@@ -135,7 +135,6 @@ const ComparisonResult = () => {
<div className="compare-result-container"> <div className="compare-result-container">
<div className="header">Performance Comparison</div> <div className="header">Performance Comparison</div>
<div className="compare-result-wrapper"> <div className="compare-result-wrapper">
<EnergyUsage comparedProducts={comparedProducts} />
<div className="throughPutCard-container comparisionCard"> <div className="throughPutCard-container comparisionCard">
<h4>Throughput (units/hr)</h4> <h4>Throughput (units/hr)</h4>
<div className="layers-wrapper"> <div className="layers-wrapper">
@@ -179,7 +178,7 @@ const ComparisonResult = () => {
<Pie data={cycleTimePieData} options={options} /> <Pie data={cycleTimePieData} options={options} />
</div> </div>
</div> </div>
{/* <EnergyUsage comparedProducts={comparedProducts} /> */}
<div className="cycle-time-container comparisionCard"> <div className="cycle-time-container comparisionCard">
<div className="cycle-main"> <div className="cycle-main">
<div className="cycle-header">Overall Downtime</div> <div className="cycle-header">Overall Downtime</div>

View File

@@ -1,113 +1,174 @@
import React, { useMemo } from "react"; import React, { useMemo } from "react";
import { Line } from "react-chartjs-2"; import { Line } from "react-chartjs-2";
import { import { Chart as ChartJS, LineElement, PointElement, CategoryScale, LinearScale, Tooltip, Legend } from "chart.js";
Chart as ChartJS,
LineElement,
PointElement,
CategoryScale,
LinearScale,
Tooltip,
Legend,
} from "chart.js";
ChartJS.register( ChartJS.register(LineElement, PointElement, CategoryScale, LinearScale, Tooltip, Legend);
LineElement,
PointElement,
CategoryScale,
LinearScale,
Tooltip,
Legend
);
const EnergyUsage = ({comparedProducts}:any) => { // const EnergyUsage = ({comparedProducts}:any) => {
const data = useMemo(() => { // const data = useMemo(() => {
const randomizeData = () => // const randomizeData = () =>
Array.from({ length: 5 }, () => Math.floor(Math.random() * (2000 - 300 + 1)) + 300); // Array.from({ length: 5 }, () => Math.floor(Math.random() * (2000 - 300 + 1)) + 300);
return { // return {
labels: ["Mon", "Tue", "Wed", "Thu", "Fri"], // labels: ["Mon", "Tue", "Wed", "Thu", "Fri"],
datasets: [ // datasets: [
{ // {
label: "Simulation 1", // label: "Simulation 1",
data: randomizeData(), // data: randomizeData(),
borderColor: "#6a0dad", // borderColor: "#6a0dad",
fill: false, // fill: false,
tension: 0.5, // More curved line // tension: 0.5, // More curved line
pointRadius: 0, // Remove point indicators // pointRadius: 0, // Remove point indicators
}, // },
{ // {
label: "Simulation 2", // label: "Simulation 2",
data: randomizeData(), // data: randomizeData(),
borderColor: "#b19cd9", // borderColor: "#b19cd9",
fill: false, // fill: false,
tension: 0.5, // tension: 0.5,
pointRadius: 0, // pointRadius: 0,
}, // },
], // ],
}; // };
}, []); // }, []);
const options = useMemo( // const options = useMemo(
() => ({ // () => ({
responsive: true, // responsive: true,
maintainAspectRatio: false, // maintainAspectRatio: false,
plugins: { // plugins: {
title: { // title: {
display: true, // display: true,
}, // },
legend: { // legend: {
display: false, // display: false,
}, // },
}, // },
scales: { // scales: {
x: { // x: {
display: false, // Hide x-axis // display: false, // Hide x-axis
grid: { // grid: {
display: false, // display: false,
}, // },
}, // },
y: { // y: {
display: false, // Hide y-axis // display: false, // Hide y-axis
grid: { // grid: {
display: false, // display: false,
}, // },
}, // },
}, // },
}), // }),
[] // []
); // );
return ( // return (
<div className="comparisionCard energy-usage"> // <div className="comparisionCard energy-usage">
<div className="energy-usage-wrapper"> // <div className="energy-usage-wrapper">
<h4>Energy Usage</h4> // <h4>Energy Usage</h4>
<p className="value"> // <p className="value">
2500 <span>kWh</span> // 2500 <span>kWh</span>
</p> // </p>
</div> // </div>
<div className="simulation-details"> // <div className="simulation-details">
<div className="simulation-wrapper sim-1"> // <div className="simulation-wrapper sim-1">
<div className="icon"></div> // <div className="icon"></div>
<div className="simulation-details-wrapper"> // <div className="simulation-details-wrapper">
<div className="label">{comparedProducts[0]?.productName}</div> // <div className="label">{comparedProducts[0]?.productName}</div>
<div className="value">98%</div> // <div className="value">98%</div>
</div> // </div>
// </div>
// <div className="simulation-wrapper sim-2">
// <div className="icon"></div>
// <div className="simulation-details-wrapper">
// <div className="label">{comparedProducts[1]?.productName}</div>
// <div className="value">97%</div>
// </div>
// </div>
// </div>
// <div className="chart">
// <Line data={data} options={options} />
// </div>
// </div>
// );
// };
// 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 (
<div className="comparisionCard energy-usage">
<div className="energy-usage-wrapper">
<h4>Energy Usage</h4>
<p className="value">
{comparedProducts.reduce((acc: number, p: any) => acc + (p.simulationData.energyUsage || 0), 0)} <span>kWh</span>
</p>
</div>
<div className="simulation-details">
{comparedProducts.map((product: any, idx: number) => (
<div key={product.productUuid} className={`simulation-wrapper sim-${idx + 1}`}>
<div className="icon"></div>
<div className="simulation-details-wrapper">
<div className="label">{product.productName}</div>
<div className="value">{product.simulationData.energyUsage} kWh</div>
</div>
</div>
))}
</div>
<div className="chart">
<Line data={data} options={options} />
</div>
</div> </div>
<div className="simulation-wrapper sim-2"> );
<div className="icon"></div>
<div className="simulation-details-wrapper">
<div className="label">{comparedProducts[1]?.productName}</div>
<div className="value">97%</div>
</div>
</div>
</div>
<div className="chart">
<Line data={data} options={options} />
</div>
</div>
);
}; };
export default EnergyUsage; export default EnergyUsage;

View File

@@ -68,7 +68,7 @@ const SimulationPlayer: React.FC = () => {
useEffect(() => { useEffect(() => {
if (materialData.length === 0) return; if (materialData.length === 0) return;
console.log('materialData: ', materialData); console.log('materialData: ', materialData);
saveSimulationData({ key: selectedProduct.productUuid, data: materialData }); // saveSimulationData({ key: selectedProduct.productUuid, data: materialData });
}, [materialData]) }, [materialData])
// Button functions // Button functions

View File

@@ -149,7 +149,7 @@ export default function ROIData() {
} }
console.log('selectedProduct.productUuid: ', selectedProduct.productUuid); console.log('selectedProduct.productUuid: ', selectedProduct.productUuid);
saveSimulationData({ key: selectedProduct.productUuid, data: data }); // saveSimulationData({ key: selectedProduct.productUuid, data: data });
const datas = { const datas = {
roi: data roi: data
} }

View File

@@ -25,7 +25,7 @@ export default function ProductionCapacityData() {
const Monthly_working_days = workingDaysPerYear / 12; const Monthly_working_days = workingDaysPerYear / 12;
const Production_capacity_per_month = throughputData * Monthly_working_days; const Production_capacity_per_month = throughputData * Monthly_working_days;
const data = Number(Production_capacity_per_month.toFixed(2)); const data = Number(Production_capacity_per_month.toFixed(2));
saveSimulationData({ key: 'productionCapacity', data: data }); // saveSimulationData({ key: 'productionCapacity', data: data });
setMaterialData({ ...materialData, productionCapacity: data }); setMaterialData({ ...materialData, productionCapacity: data });
setProductionCapacityData(Number(Production_capacity_per_month.toFixed(2))); setProductionCapacityData(Number(Production_capacity_per_month.toFixed(2)));
} }

View File

@@ -222,7 +222,7 @@ export default function ThroughPutData() {
const Throughput_per_day = Units_per_shift * shiftsPerDay * (yieldRate / 100); const Throughput_per_day = Units_per_shift * shiftsPerDay * (yieldRate / 100);
const data = Number(Throughput_per_day.toFixed(2)) const data = Number(Throughput_per_day.toFixed(2))
console.log('data: ', data); console.log('data: ', data);
saveSimulationData({ key: selectedProduct.productUuid, data: data }); // saveSimulationData({ key: selectedProduct.productUuid, data: data });
setMaterialData({ ...materialData, throughput: data }); setMaterialData({ ...materialData, throughput: data });
setThroughputData(Number(Throughput_per_day.toFixed(2))); // Keep as number setThroughputData(Number(Throughput_per_day.toFixed(2))); // Keep as number

View File

@@ -1,4 +1,4 @@
import React, { useEffect } from "react"; import React, { useEffect, useState } from "react";
import { useSceneContext } from "../../scene/sceneContext"; import { useSceneContext } from "../../scene/sceneContext";
import { useProductContext } from "../products/productContext"; import { useProductContext } from "../products/productContext";
import { determineExecutionMachineSequences } from "./functions/determineExecutionMachineSequences"; import { determineExecutionMachineSequences } from "./functions/determineExecutionMachineSequences";
@@ -8,18 +8,13 @@ import { useParams } from "react-router-dom";
import { useVersionContext } from "../../builder/version/versionContext"; import { useVersionContext } from "../../builder/version/versionContext";
import { getSimulationData, saveSimulationData } from "../../../components/layout/scenes/functions/simulationStorage"; import { getSimulationData, saveSimulationData } from "../../../components/layout/scenes/functions/simulationStorage";
import { get } from "http"; import { get } from "http";
import { set } from "immer/dist/internal";
interface SimulationUsageRecord { interface SimulationUsageRecord {
activeTime: number; activeTime: number;
isActive: boolean; isActive: boolean;
idleTime: number; idleTime: number;
type: type: "roboticArm" | "vehicle" | "transfer" | "storageUnit" | "crane" | "human" | "machine";
| "roboticArm" assetId: string;
| "vehicle"
| "transfer"
| "storageUnit"
| "crane"
| "human"
| "machine";
} }
// Product → holds multiple usage records // Product → holds multiple usage records
@@ -40,17 +35,7 @@ interface ProjectSimulation {
versions: VersionSimulation[]; versions: VersionSimulation[];
} }
const SimulationHandler = () => { const SimulationHandler = () => {
const { const { materialStore, armBotStore, machineStore, conveyorStore, vehicleStore, storageUnitStore, productStore, craneStore, humanStore } = useSceneContext();
materialStore,
armBotStore,
machineStore,
conveyorStore,
vehicleStore,
storageUnitStore,
productStore,
craneStore,
humanStore,
} = useSceneContext();
const { armBots, getArmBotById } = armBotStore(); const { armBots, getArmBotById } = armBotStore();
const { vehicles, getVehicleById } = vehicleStore(); const { vehicles, getVehicleById } = vehicleStore();
const { getConveyorById } = conveyorStore(); const { getConveyorById } = conveyorStore();
@@ -67,6 +52,7 @@ const SimulationHandler = () => {
const { projectId } = useParams(); const { projectId } = useParams();
const { selectedVersionStore } = useVersionContext(); const { selectedVersionStore } = useVersionContext();
const { selectedVersion } = selectedVersionStore(); const { selectedVersion } = selectedVersionStore();
const [simulationEntry, setSimulationEntry] = useState<any>();
const COST_RATES: Record<SimulationUsageRecord["type"], number> = { const COST_RATES: Record<SimulationUsageRecord["type"], number> = {
roboticArm: 5, roboticArm: 5,
vehicle: 2, vehicle: 2,
@@ -135,31 +121,72 @@ const SimulationHandler = () => {
return { ...m, efficiencyScore }; 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(() => { useEffect(() => {
console.log('simulationRecords: ', simulationRecords); const fetchSimulationData = async () => {
if (!projectId || !selectedVersion || !selectedProduct.productUuid || simulationRecords.length === 0) return; if (!projectId || !selectedVersion || !selectedProduct.productUuid) return;
const data = {
const project = simulationRecords[0]; projectId: projectId,
versionId: selectedVersion.versionId,
if (project) { productUuid: selectedProduct.productUuid,
const scores = calculateEfficiencyScores(project.versions); simulatedId: simulationEntry,
console.log("Version Comparisons:", scores); };
} const datas = await getSimulationData(data);
console.log("datas: ", datas);
saveSimulationData({ };
key: selectedProduct.productUuid, fetchSimulationData();
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 { }
}, [])
useEffect(() => { useEffect(() => {
let checkTimer: ReturnType<typeof setTimeout>; let checkTimer: ReturnType<typeof setTimeout>;
@@ -169,9 +196,7 @@ const SimulationHandler = () => {
let hasActiveEntity = false; let hasActiveEntity = false;
if (currentProduct) { if (currentProduct) {
const executionSequences = await determineExecutionMachineSequences([ const executionSequences = await determineExecutionMachineSequences([currentProduct]);
currentProduct,
]);
if (executionSequences?.length > 0) { if (executionSequences?.length > 0) {
executionSequences.forEach((sequence) => { executionSequences.forEach((sequence) => {
sequence.forEach((entity) => { sequence.forEach((entity) => {
@@ -221,11 +246,7 @@ const SimulationHandler = () => {
}); });
} }
if ( if (materials.length === 0 && materialHistory.length >= 0 && !hasActiveEntity) {
materials.length === 0 &&
materialHistory.length >= 0 &&
!hasActiveEntity
) {
if (executionSequences?.length > 0) { if (executionSequences?.length > 0) {
executionSequences.forEach((sequence) => { executionSequences.forEach((sequence) => {
sequence.forEach((entity) => { sequence.forEach((entity) => {
@@ -245,25 +266,13 @@ const SimulationHandler = () => {
const obj = getter(entity.modelUuid); const obj = getter(entity.modelUuid);
if (!obj) return; // skip if not found if (!obj) return; // skip if not found
addSimulationRecord( addSimulationRecord(projectId, selectedVersion?.versionId || "", selectedProduct?.productUuid, {
projectId, activeTime: obj.activeTime ?? 0,
selectedVersion?.versionId || "", isActive: obj.isActive ?? false,
selectedProduct?.productUuid, idleTime: obj.idleTime ?? 0,
{ type: entity.type as "roboticArm" | "vehicle" | "machine" | "human" | "crane" | "storageUnit" | "transfer",
activeTime: obj.activeTime ?? 0, assetId: entity.modelUuid,
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 () => { return () => {
if (checkTimer) clearTimeout(checkTimer); if (checkTimer) clearTimeout(checkTimer);
}; };
}, [ }, [materials, materialHistory, selectedVersion, selectedProduct?.productUuid, isPlaying, armBots, vehicles, machines]);
materials,
materialHistory,
selectedVersion,
selectedProduct?.productUuid,
isPlaying,
armBots,
vehicles,
machines,
]);
return null; return null;
}; };

View File

@@ -11,7 +11,7 @@ interface SimulationUsageRecord {
// Product → holds multiple usage records // Product → holds multiple usage records
interface ProductSimulation { interface ProductSimulation {
productId: string; productId: string;
data: SimulationUsageRecord[]; simulateData: SimulationUsageRecord[];
} }
// Version → holds multiple products // Version → holds multiple products
@@ -29,7 +29,7 @@ interface ProjectSimulation {
interface SimulationManagerStore { interface SimulationManagerStore {
simulationRecords: ProjectSimulation[]; simulationRecords: ProjectSimulation[];
setSimulationRecords: (data: ProjectSimulation[]) => void; setSimulationRecords: (simulateData: ProjectSimulation[]) => void;
addSimulationRecord: (projectId: string | undefined, versionId: string, productId: string, record: SimulationUsageRecord) => void; addSimulationRecord: (projectId: string | undefined, versionId: string, productId: string, record: SimulationUsageRecord) => void;
resetProductRecords: (projectId: string, versionId: string, productId: string) => void; resetProductRecords: (projectId: string, versionId: string, productId: string) => void;
@@ -53,7 +53,7 @@ export const useSimulationManager = create<SimulationManagerStore>((set, get) =>
return { return {
...version, ...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<SimulationManagerStore>((set, get) =>
versions: [ versions: [
{ {
versionId, versionId,
products: [{ productId, data: [record] }], products: [{ productId, simulateData: [record] }],
}, },
], ],
}); });
@@ -75,12 +75,12 @@ export const useSimulationManager = create<SimulationManagerStore>((set, get) =>
if (!project.versions.find((v) => v.versionId === versionId)) { if (!project.versions.find((v) => v.versionId === versionId)) {
project.versions.push({ project.versions.push({
versionId, versionId,
products: [{ productId, data: [record] }], products: [{ productId, simulateData: [record] }],
}); });
} else { } else {
const version = project.versions.find((v) => v.versionId === versionId)!; const version = project.versions.find((v) => v.versionId === versionId)!;
if (!version.products.find((p) => p.productId === productId)) { 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<SimulationManagerStore>((set, get) =>
return { return {
...version, ...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<SimulationManagerStore>((set, get) =>
return { simulationRecords: projects }; return { simulationRecords: projects };
}), }),
setSimulationRecords: (data) => { setSimulationRecords: (simulateData) => {
set({ simulationRecords: data }); set({ simulationRecords: simulateData });
}, },
getProjectById: (projectId: string | undefined) => { getProjectById: (projectId: string | undefined) => {
return get().simulationRecords.find((p: ProjectSimulation) => p.projectId === projectId); return get().simulationRecords.find((p: ProjectSimulation) => p.projectId === projectId);