Refactor user data retrieval across visualization components

- Replaced direct localStorage access for email and organization with a centralized getUserData function in LineGraphComponent, PieGraphComponent, PolarAreaGraphComponent, ProgressCard1, ProgressCard2, Dropped3dWidgets, ProductionCapacity, ReturnOfInvestment, StateWorking, Throughput, and various floating widgets.
- Improved code readability and maintainability by consolidating user data extraction logic.
- Ensured consistent user data handling across multiple components to reduce redundancy.
This commit is contained in:
Poovizhi99 2025-06-13 17:11:28 +05:30
parent ac78309bcc
commit fcd67f4528
88 changed files with 1954 additions and 1783 deletions

View File

@ -1,7 +1,7 @@
import React, { useState, useRef, useEffect } from "react"; import React, { useState, useRef, useEffect } from "react";
import img from "../../assets/image/image.png"; import img from "../../assets/image/image.png";
import { useNavigate } from "react-router-dom"; import { useNavigate } from "react-router-dom";
import { getUserData } from "./functions/getUserData"; import { getUserData } from "../../functions/getUserData";
import { useLoadingProgress, useProjectName, useSocketStore } from "../../store/builder/store"; import { useLoadingProgress, useProjectName, useSocketStore } from "../../store/builder/store";
import { viewProject } from "../../services/dashboard/viewProject"; import { viewProject } from "../../services/dashboard/viewProject";
import OuterClick from "../../utils/outerClick"; import OuterClick from "../../utils/outerClick";

View File

@ -2,7 +2,7 @@ import React, { useEffect, useState } from "react";
import DashboardCard from "./DashboardCard"; import DashboardCard from "./DashboardCard";
import DashboardNavBar from "./DashboardNavBar"; import DashboardNavBar from "./DashboardNavBar";
import MarketPlaceBanner from "./MarketPlaceBanner"; import MarketPlaceBanner from "./MarketPlaceBanner";
import { getUserData } from "./functions/getUserData"; import { getUserData } from "../../functions/getUserData";
import { useSocketStore } from "../../store/builder/store"; import { useSocketStore } from "../../store/builder/store";
import { recentlyViewed } from "../../services/dashboard/recentlyViewed"; import { recentlyViewed } from "../../services/dashboard/recentlyViewed";
import { searchProject } from "../../services/dashboard/searchProjects"; import { searchProject } from "../../services/dashboard/searchProjects";

View File

@ -1,7 +1,7 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import DashboardNavBar from "./DashboardNavBar"; import DashboardNavBar from "./DashboardNavBar";
import DashboardCard from "./DashboardCard"; import DashboardCard from "./DashboardCard";
import { getUserData } from "./functions/getUserData"; import { getUserData } from "../../functions/getUserData";
import { useSocketStore } from "../../store/builder/store"; import { useSocketStore } from "../../store/builder/store";
import { getAllProjects } from "../../services/dashboard/getAllProjects"; import { getAllProjects } from "../../services/dashboard/getAllProjects";
import { searchProject } from "../../services/dashboard/searchProjects"; import { searchProject } from "../../services/dashboard/searchProjects";
@ -65,7 +65,7 @@ const DashboardProjects: React.FC = () => {
// console.log('deletedProject: ', deletedProject); // console.log('deletedProject: ', deletedProject);
const deleteProjects = { const deleteProjects = {
projectId, projectId,
organization: organization, organization,
userId, userId,
}; };

View File

@ -1,7 +1,7 @@
import React, { useEffect, useState } from "react"; import React, { useEffect, useState } from "react";
import DashboardCard from "./DashboardCard"; import DashboardCard from "./DashboardCard";
import DashboardNavBar from "./DashboardNavBar"; import DashboardNavBar from "./DashboardNavBar";
import { getUserData } from "./functions/getUserData"; import { getUserData } from "../../functions/getUserData";
import { trashSearchProject } from "../../services/dashboard/trashSearchProject"; import { trashSearchProject } from "../../services/dashboard/trashSearchProject";
import { restoreTrash } from "../../services/dashboard/restoreTrash"; import { restoreTrash } from "../../services/dashboard/restoreTrash";
import { getTrash } from "../../services/dashboard/getTrash"; import { getTrash } from "../../services/dashboard/getTrash";

View File

@ -12,7 +12,7 @@ import { useNavigate } from "react-router-dom";
import darkThemeImage from "../../assets/image/darkThemeProject.png"; import darkThemeImage from "../../assets/image/darkThemeProject.png";
import lightThemeImage from "../../assets/image/lightThemeProject.png"; import lightThemeImage from "../../assets/image/lightThemeProject.png";
import { SettingsIcon, TrashIcon } from "../icons/ExportCommonIcons"; import { SettingsIcon, TrashIcon } from "../icons/ExportCommonIcons";
import { getUserData } from "./functions/getUserData"; import { getUserData } from "../../functions/getUserData";
import { useLoadingProgress, useSocketStore } from "../../store/builder/store"; import { useLoadingProgress, useSocketStore } from "../../store/builder/store";
import { createProject } from "../../services/dashboard/createProject"; import { createProject } from "../../services/dashboard/createProject";

View File

@ -1,7 +1,7 @@
import React, { useEffect } from 'react'; import React, { useEffect } from 'react';
import { useSocketStore } from '../../../store/builder/store'; import { useSocketStore } from '../../../store/builder/store';
import { getUserData } from '../functions/getUserData'; import { getUserData } from '../../../functions/getUserData';
import { getAllProjects } from '../../../services/dashboard/getAllProjects'; import { getAllProjects } from '../../../services/dashboard/getAllProjects';
import { recentlyViewed } from '../../../services/dashboard/recentlyViewed'; import { recentlyViewed } from '../../../services/dashboard/recentlyViewed';

View File

@ -36,6 +36,7 @@ import RenameTooltip from "../../ui/features/RenameTooltip";
import { setFloorItemApi } from "../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi"; import { setFloorItemApi } from "../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi";
import { useAssetsStore } from "../../../store/builder/useAssetStore"; import { useAssetsStore } from "../../../store/builder/useAssetStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
function MainScene() { function MainScene() {
const { products } = useProductStore(); const { products } = useProductStore();
@ -57,6 +58,7 @@ function MainScene() {
const { setName } = useAssetsStore(); const { setName } = useAssetsStore();
const { projectId } = useParams() const { projectId } = useParams()
const { isRenameMode, setIsRenameMode } = useRenameModeStore(); const { isRenameMode, setIsRenameMode } = useRenameModeStore();
const { userName, userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
if (activeModule !== 'simulation') { if (activeModule !== 'simulation') {
@ -73,8 +75,6 @@ function MainScene() {
}; };
const handleObjectRename = async (newName: string) => { const handleObjectRename = async (newName: string) => {
if (!projectId) return if (!projectId) return
const email = localStorage.getItem("email") ?? "";
const organization = email?.split("@")[1]?.split(".")[0];
let response = await setFloorItemApi( let response = await setFloorItemApi(
organization, organization,
selectedFloorItem.userData.modelUuid, selectedFloorItem.userData.modelUuid,

View File

@ -8,10 +8,11 @@ import { useSelectedUserStore } from "../../../store/collaboration/useCollabStor
import { useToggleStore } from "../../../store/useUIToggleStore"; import { useToggleStore } from "../../../store/useUIToggleStore";
import { ToggleSidebarIcon } from "../../icons/HeaderIcons"; import { ToggleSidebarIcon } from "../../icons/HeaderIcons";
import useModuleStore from "../../../store/useModuleStore"; import useModuleStore from "../../../store/useModuleStore";
import { getUserData } from "../../../functions/getUserData";
const Header: React.FC = () => { const Header: React.FC = () => {
const { activeUsers } = useActiveUsers(); const { activeUsers } = useActiveUsers();
const userName = localStorage.getItem("userName") ?? "Anonymous"; const { userName } = getUserData();
const { toggleUILeft, toggleUIRight, setToggleUI } = useToggleStore(); const { toggleUILeft, toggleUIRight, setToggleUI } = useToggleStore();
const { activeModule } = useModuleStore(); const { activeModule } = useModuleStore();
@ -113,7 +114,7 @@ const Header: React.FC = () => {
))} ))}
</div> </div>
<div className="user-profile-container"> <div className="user-profile-container">
<div className="user-profile">{userName[0]}</div> <div className="user-profile">{userName}</div>
<div className="user-organization"> <div className="user-organization">
<img src={orgImg} alt="" /> <img src={orgImg} alt="" />
</div> </div>

View File

@ -20,6 +20,7 @@ import {
import { setEnvironment } from "../../../../services/factoryBuilder/environment/setEnvironment"; import { setEnvironment } from "../../../../services/factoryBuilder/environment/setEnvironment";
import * as CONSTANTS from "../../../../types/world/worldConstants"; import * as CONSTANTS from "../../../../types/world/worldConstants";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
const GlobalProperties: React.FC = () => { const GlobalProperties: React.FC = () => {
const { toggleView, setToggleView } = useToggleView(); const { toggleView, setToggleView } = useToggleView();
const { selectedWallItem, setSelectedWallItem } = useSelectedWallItem(); const { selectedWallItem, setSelectedWallItem } = useSelectedWallItem();
@ -38,14 +39,13 @@ const GlobalProperties: React.FC = () => {
const [limitGridDistance, setLimitGridDistance] = useState(false); const [limitGridDistance, setLimitGridDistance] = useState(false);
const [gridDistance, setGridDistance] = useState<number>(3); const [gridDistance, setGridDistance] = useState<number>(3);
const { projectId } = useParams(); const { projectId } = useParams();
const { email, userId, organization } = getUserData();
const optimizeScene = async (value: any) => { const optimizeScene = async (value: any) => {
const email = localStorage.getItem("email");
const organization = email?.split("@")[1]?.split(".")[0] || "defaultOrg";
setEnvironment( setEnvironment(
organization, organization,
localStorage.getItem("userId")!, userId,
wallVisibility, wallVisibility,
roofVisibility, roofVisibility,
shadows, shadows,
@ -58,13 +58,11 @@ const GlobalProperties: React.FC = () => {
}; };
const limitRenderDistance = async () => { const limitRenderDistance = async () => {
const email = localStorage.getItem("email");
const organization = email?.split("@")[1]?.split(".")[0] || "defaultOrg";
if (limitDistance) { if (limitDistance) {
setEnvironment( setEnvironment(
organization, organization,
localStorage.getItem("userId")!, userId,
wallVisibility, wallVisibility,
roofVisibility, roofVisibility,
shadows, shadows,
@ -76,7 +74,7 @@ const GlobalProperties: React.FC = () => {
} else { } else {
setEnvironment( setEnvironment(
organization, organization,
localStorage.getItem("userId")!, userId,
wallVisibility, wallVisibility,
roofVisibility, roofVisibility,
shadows, shadows,
@ -104,13 +102,11 @@ const GlobalProperties: React.FC = () => {
} }
const updatedDist = async (value: number) => { const updatedDist = async (value: number) => {
const email = localStorage.getItem("email");
const organization = email?.split("@")[1]?.split(".")[0] || "defaultOrg";
setRenderDistance(value); setRenderDistance(value);
// setDistance(value); // setDistance(value);
const data = await setEnvironment( const data = await setEnvironment(
organization, organization,
localStorage.getItem("userId")!, userId,
wallVisibility, wallVisibility,
roofVisibility, roofVisibility,
shadows, shadows,
@ -122,13 +118,11 @@ const GlobalProperties: React.FC = () => {
// Function to toggle roof visibility // Function to toggle roof visibility
const changeRoofVisibility = async () => { const changeRoofVisibility = async () => {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
//using REST //using REST
const data = await setEnvironment( const data = await setEnvironment(
organization, organization,
localStorage.getItem("userId")!, userId,
wallVisibility, wallVisibility,
!roofVisibility, !roofVisibility,
shadows, shadows,
@ -153,12 +147,10 @@ const GlobalProperties: React.FC = () => {
}; };
// Function to toggle wall visibility // Function to toggle wall visibility
const changeWallVisibility = async () => { const changeWallVisibility = async () => {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
//using REST //using REST
const data = await setEnvironment( const data = await setEnvironment(
organization, organization,
localStorage.getItem("userId")!, userId,
!wallVisibility, !wallVisibility,
roofVisibility, roofVisibility,
shadows, shadows,
@ -182,12 +174,10 @@ const GlobalProperties: React.FC = () => {
}; };
const shadowVisibility = async () => { const shadowVisibility = async () => {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
//using REST //using REST
const data = await setEnvironment( const data = await setEnvironment(
organization, organization,
localStorage.getItem("userId")!, userId,
wallVisibility, wallVisibility,
roofVisibility, roofVisibility,
!shadows, !shadows,

View File

@ -10,6 +10,7 @@ import {
} from "../../../../store/builder/store"; } from "../../../../store/builder/store";
import { zoneCameraUpdate } from "../../../../services/visulization/zone/zoneCameraUpdation"; import { zoneCameraUpdate } from "../../../../services/visulization/zone/zoneCameraUpdation";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
const ZoneProperties: React.FC = () => { const ZoneProperties: React.FC = () => {
const { Edit, setEdit } = useEditPosition(); const { Edit, setEdit } = useEditPosition();
@ -17,7 +18,8 @@ const ZoneProperties: React.FC = () => {
const { zonePosition, setZonePosition } = usezonePosition(); const { zonePosition, setZonePosition } = usezonePosition();
const { zoneTarget, setZoneTarget } = usezoneTarget(); const { zoneTarget, setZoneTarget } = usezoneTarget();
const { zones, setZones } = useZones(); const { zones, setZones } = useZones();
const { projectId } = useParams() const { projectId } = useParams();
const { userName, userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
setZonePosition(selectedZone.zoneViewPortPosition); setZonePosition(selectedZone.zoneViewPortPosition);
@ -26,8 +28,6 @@ const ZoneProperties: React.FC = () => {
async function handleSetView() { async function handleSetView() {
try { try {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
let zonesdata = { let zonesdata = {
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
@ -52,8 +52,6 @@ const ZoneProperties: React.FC = () => {
} }
async function handleZoneNameChange(newName: string) { async function handleZoneNameChange(newName: string) {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const zonesdata = { const zonesdata = {
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
zoneName: newName, zoneName: newName,

View File

@ -9,9 +9,10 @@ import {
import RenameInput from "../../../ui/inputs/RenameInput"; import RenameInput from "../../../ui/inputs/RenameInput";
import { useVersionStore } from "../../../../store/builder/store"; import { useVersionStore } from "../../../../store/builder/store";
import { generateUniqueId } from "../../../../functions/generateUniqueId"; import { generateUniqueId } from "../../../../functions/generateUniqueId";
import { getUserData } from "../../../../functions/getUserData";
const VersionHistory = () => { const VersionHistory = () => {
const userName = localStorage.getItem("userName") ?? "Anonymous"; const { userName, userId, organization, email } = getUserData();
const { versions, addVersion, setVersions, updateVersion } = const { versions, addVersion, setVersions, updateVersion } =
useVersionStore(); useVersionStore();
const [selectedVersion, setSelectedVersion] = useState( const [selectedVersion, setSelectedVersion] = useState(
@ -28,7 +29,7 @@ const VersionHistory = () => {
month: "long", month: "long",
day: "2-digit", day: "2-digit",
}), }),
savedBy: userName, savedBy: userName ?? "Anonymous",
}; };
const newVersions = [newVersion, ...versions]; const newVersions = [newVersion, ...versions];

View File

@ -9,6 +9,7 @@ import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useSocketStore } from "../../../../../store/builder/store"; import { useSocketStore } from "../../../../../store/builder/store";
import { getUserData } from "../../../../../functions/getUserData";
type Props = {}; type Props = {};
@ -23,8 +24,7 @@ const BarChartInput = (props: Props) => {
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
const { projectId } = useParams(); const { projectId } = useParams();
const { visualizationSocket } = useSocketStore(); const { visualizationSocket } = useSocketStore();
@ -125,7 +125,7 @@ const BarChartInput = (props: Props) => {
}, },
}, },
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -7,6 +7,7 @@ import { useSelectedZoneStore } from "../../../../../store/visualization/useZone
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios"; import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { getUserData } from "../../../../../functions/getUserData";
type Props = {}; type Props = {};
@ -22,11 +23,10 @@ const FleetEfficiencyInputComponent = (props: Props) => {
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
const isSelected = () => {}; const isSelected = () => { };
useEffect(() => { useEffect(() => {
const fetchZoneData = async () => { const fetchZoneData = async () => {
@ -89,7 +89,7 @@ const FleetEfficiencyInputComponent = (props: Props) => {
const response = await axios.post( const response = await axios.post(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/floatWidget/save`, `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/floatWidget/save`,
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -7,6 +7,7 @@ import { useSelectedZoneStore } from "../../../../../store/visualization/useZone
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios"; import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { getUserData } from "../../../../../functions/getUserData";
type Props = {}; type Props = {};
@ -22,8 +23,7 @@ const FlotingWidgetInput = (props: Props) => {
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
useEffect(() => { useEffect(() => {
@ -88,7 +88,7 @@ const FlotingWidgetInput = (props: Props) => {
const response = await axios.post( const response = await axios.post(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/floatWidget/save`, `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/floatWidget/save`,
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -125,6 +125,7 @@ import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useSocketStore } from "../../../../../store/builder/store"; import { useSocketStore } from "../../../../../store/builder/store";
import { getUserData } from "../../../../../functions/getUserData";
type Props = {}; type Props = {};
@ -139,8 +140,7 @@ const LineGrapInput = (props: Props) => {
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
const { projectId } = useParams(); const { projectId } = useParams();
const { visualizationSocket } = useSocketStore(); const { visualizationSocket } = useSocketStore();
@ -240,7 +240,7 @@ const LineGrapInput = (props: Props) => {
}, },
}, },
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -9,6 +9,7 @@ import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useSocketStore } from "../../../../../store/builder/store"; import { useSocketStore } from "../../../../../store/builder/store";
import { getUserData } from "../../../../../functions/getUserData";
type Props = {}; type Props = {};
@ -23,8 +24,7 @@ const PieChartInput = (props: Props) => {
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
const { projectId } = useParams(); const { projectId } = useParams();
const { visualizationSocket } = useSocketStore(); const { visualizationSocket } = useSocketStore();
@ -126,7 +126,7 @@ const PieChartInput = (props: Props) => {
}, },
}, },
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -9,6 +9,7 @@ import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useSocketStore } from "../../../../../store/builder/store"; import { useSocketStore } from "../../../../../store/builder/store";
import { getUserData } from "../../../../../functions/getUserData";
type Props = {}; type Props = {};
@ -23,8 +24,7 @@ const Progress1Input = (props: Props) => {
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
const { projectId } = useParams(); const { projectId } = useParams();
const { visualizationSocket } = useSocketStore(); const { visualizationSocket } = useSocketStore();
@ -125,7 +125,7 @@ const Progress1Input = (props: Props) => {
}, },
}, },
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -9,6 +9,7 @@ import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useSocketStore } from "../../../../../store/builder/store"; import { useSocketStore } from "../../../../../store/builder/store";
import { getUserData } from "../../../../../functions/getUserData";
type Props = {}; type Props = {};
@ -23,8 +24,7 @@ const Progress2Input = (props: Props) => {
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
const { projectId } = useParams(); const { projectId } = useParams();
const { visualizationSocket } = useSocketStore(); const { visualizationSocket } = useSocketStore();
@ -125,7 +125,7 @@ const Progress2Input = (props: Props) => {
}, },
}, },
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -7,6 +7,7 @@ import { useSelectedZoneStore } from "../../../../../store/visualization/useZone
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios"; import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { getUserData } from "../../../../../functions/getUserData";
type Props = {}; type Props = {};
@ -22,8 +23,7 @@ const WarehouseThroughputInputComponent = (props: Props) => {
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
useEffect(() => { useEffect(() => {
@ -86,7 +86,7 @@ const WarehouseThroughputInputComponent = (props: Props) => {
const response = await axios.post( const response = await axios.post(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/floatWidget/save`, `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/floatWidget/save`,
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -7,6 +7,7 @@ import { useSelectedZoneStore } from "../../../../../store/visualization/useZone
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios"; import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { getUserData } from "../../../../../functions/getUserData";
type Props = {}; type Props = {};
@ -21,8 +22,7 @@ const Widget2InputCard3D = (props: Props) => {
>({}); >({});
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
useEffect(() => { useEffect(() => {
@ -85,7 +85,7 @@ const Widget2InputCard3D = (props: Props) => {
const response = await axios.post( const response = await axios.post(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/widget3d/save`, `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/widget3d/save`,
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -7,6 +7,7 @@ import { useSelectedZoneStore } from "../../../../../store/visualization/useZone
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios"; import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { getUserData } from "../../../../../functions/getUserData";
const Widget3InputCard3D = () => { const Widget3InputCard3D = () => {
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
@ -19,8 +20,7 @@ const Widget3InputCard3D = () => {
>({}); >({});
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
useEffect(() => { useEffect(() => {
@ -82,7 +82,7 @@ const Widget3InputCard3D = () => {
const response = await axios.post( const response = await axios.post(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/widget3d/save`, `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/widget3d/save`,
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -7,6 +7,7 @@ import { useSelectedZoneStore } from "../../../../../store/visualization/useZone
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios"; import axios from "axios";
import RenameInput from "../../../../ui/inputs/RenameInput"; import RenameInput from "../../../../ui/inputs/RenameInput";
import { getUserData } from "../../../../../functions/getUserData";
type Props = {}; type Props = {};
@ -21,8 +22,7 @@ const Widget4InputCard3D = (props: Props) => {
>({}); >({});
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const [isLoading, setLoading] = useState<boolean>(true); const [isLoading, setLoading] = useState<boolean>(true);
useEffect(() => { useEffect(() => {
@ -85,7 +85,7 @@ const Widget4InputCard3D = (props: Props) => {
const response = await axios.post( const response = await axios.post(
`http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/widget3d/save`, `http://${process.env.REACT_APP_SERVER_REST_API_BASE_URL}/api/V1/widget3d/save`,
{ {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: { widget: {
id: selectedChartId.id, id: selectedChartId.id,

View File

@ -6,6 +6,7 @@ import RegularDropDown from "../ui/inputs/RegularDropDown";
import { access } from "fs"; import { access } from "fs";
import MultiEmailInvite from "../ui/inputs/MultiEmailInvite"; import MultiEmailInvite from "../ui/inputs/MultiEmailInvite";
import { useActiveUsers } from "../../store/builder/store"; import { useActiveUsers } from "../../store/builder/store";
import { getUserData } from "../../functions/getUserData";
interface UserListTemplateProps { interface UserListTemplateProps {
user: User; user: User;
@ -59,10 +60,10 @@ const CollaborationPopup: React.FC<CollaborateProps> = ({
setUserManagement, setUserManagement,
}) => { }) => {
const { activeUsers } = useActiveUsers(); const { activeUsers } = useActiveUsers();
const { userName } = getUserData();
useEffect(() => { useEffect(() => {
console.log("activeUsers: ", activeUsers); console.log("activeUsers: ", activeUsers);
}, [activeUsers]); }, [activeUsers]);
const userName = localStorage.getItem("userName") || "Anonymous";
const users = [ const users = [
{ {
name: "Alice Johnson", name: "Alice Johnson",
@ -140,7 +141,7 @@ const CollaborationPopup: React.FC<CollaborateProps> = ({
<div className="users-list-container"> <div className="users-list-container">
<div className="you-container"> <div className="you-container">
<div className="your-name"> <div className="your-name">
<div className="user-profile">{userName[0].toUpperCase()}</div> <div className="user-profile">{userName && userName[0].toUpperCase()}</div>
{userName} {userName}
</div> </div>
<div className="indicater">you</div> <div className="indicater">you</div>

View File

@ -5,6 +5,7 @@ import { useParams } from "react-router-dom";
import { useProjectName } from "../../store/builder/store"; import { useProjectName } from "../../store/builder/store";
import { getAllProjects } from "../../services/dashboard/getAllProjects"; import { getAllProjects } from "../../services/dashboard/getAllProjects";
import { useComparisonProduct } from "../../store/simulation/useSimulationStore"; import { useComparisonProduct } from "../../store/simulation/useSimulationStore";
import { getUserData } from "../../functions/getUserData";
interface LoadingPageProps { interface LoadingPageProps {
progress: number; // Expect progress as a percentage (0-100) progress: number; // Expect progress as a percentage (0-100)
@ -14,32 +15,23 @@ const LoadingPage: React.FC<LoadingPageProps> = ({ progress }) => {
const { projectName, setProjectName } = useProjectName(); const { projectName, setProjectName } = useProjectName();
const { projectId } = useParams(); const { projectId } = useParams();
const { comparisonProduct } = useComparisonProduct(); const { comparisonProduct } = useComparisonProduct();
const { userId, organization, email } = getUserData();
const validatedProgress = Math.min(100, Math.max(0, progress)); const validatedProgress = Math.min(100, Math.max(0, progress));
const generateThumbnail = async () => { const generateThumbnail = async () => {
const email = localStorage.getItem("email");
const userId = localStorage.getItem("userId");
try { try {
if (!email || !userId) { if (!email || !userId) {
console.error("User data not found in localStorage"); console.error("User data not found in localStorage");
return; return;
} }
const emailParts = email.split("@"); const projects = await getAllProjects(userId, organization);
if (emailParts.length < 2) {
console.error("Invalid email format");
return;
}
const domainParts = emailParts[1].split(".");
const Organization = domainParts[0];
const projects = await getAllProjects(userId, Organization);
const filterProject = projects?.Projects.find( const filterProject = projects?.Projects.find(
(val: any) => val.projectUuid === projectId || val._id === projectId (val: any) => val.projectUuid === projectId || val._id === projectId
); );
setProjectName(filterProject.projectName); setProjectName(filterProject.projectName);
} catch {} } catch { }
}; };
useEffect(() => { useEffect(() => {
generateThumbnail(); generateThumbnail();
@ -47,9 +39,8 @@ const LoadingPage: React.FC<LoadingPageProps> = ({ progress }) => {
return ( return (
<RenderOverlay> <RenderOverlay>
<div <div
className={`loading-wrapper ${ className={`loading-wrapper ${comparisonProduct != null ? "comparisionLoading" : ""
comparisonProduct != null ? "comparisionLoading" : "" }`}
}`}
> >
<div className="loading-container"> <div className="loading-container">
<div className="project-name">{projectName}</div> <div className="project-name">{projectName}</div>

View File

@ -7,6 +7,7 @@ import { useProjectName, useSocketStore } from "../../store/builder/store";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getAllProjects } from "../../services/dashboard/getAllProjects"; import { getAllProjects } from "../../services/dashboard/getAllProjects";
import { updateProject } from "../../services/dashboard/updateProject"; import { updateProject } from "../../services/dashboard/updateProject";
import { getUserData } from "../../functions/getUserData";
const FileMenu: React.FC = () => { const FileMenu: React.FC = () => {
const [openMenu, setOpenMenu] = useState(false); const [openMenu, setOpenMenu] = useState(false);
@ -15,6 +16,7 @@ const FileMenu: React.FC = () => {
const { projectName, setProjectName } = useProjectName(); const { projectName, setProjectName } = useProjectName();
const { dashBoardSocket } = useSocketStore(); const { dashBoardSocket } = useSocketStore();
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
const handleClick = () => { const handleClick = () => {
if (clickTimeout) return; if (clickTimeout) return;
@ -58,31 +60,20 @@ const FileMenu: React.FC = () => {
if (!projectId) return if (!projectId) return
// localStorage.setItem("projectName", newName); // localStorage.setItem("projectName", newName);
try { try {
const email = localStorage.getItem("email");
const userId = localStorage.getItem("userId");
if (!email || !userId) { if (!email || !userId) {
return; return;
} }
const emailParts = email.split("@");
if (emailParts.length < 2) {
return;
}
const domainParts = emailParts[1].split(".");
const Organization = domainParts[0];
const projects = await getAllProjects( const projects = await getAllProjects(
userId, Organization userId, organization
); );
console.log('projects: ', projects); console.log('projects: ', projects);
let projectUuid = projects.Projects.find((val: any) => val.projectUuid === projectId || val._id let projectUuid = projects.Projects.find((val: any) => val.projectUuid === projectId || val._id
=== projectId) === projectId)
const updateProjects = { const updateProjects = {
projectId: projectUuid, projectId: projectUuid,
organization: Organization, organization,
userId, userId,
projectName, projectName,
thumbnail: undefined thumbnail: undefined
@ -101,12 +92,12 @@ const FileMenu: React.FC = () => {
const updatedProjectName = await updateProject( const updatedProjectName = await updateProject(
projectId, projectId,
userId, userId,
Organization, organization,
undefined, undefined,
projectName projectName
); );
// //
} catch (error) {} } catch (error) { }
}; };
return ( return (
<button <button

View File

@ -20,6 +20,7 @@ import { zoneCameraUpdate } from "../../../services/visulization/zone/zoneCamera
import { setFloorItemApi } from "../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi"; import { setFloorItemApi } from "../../../services/factoryBuilder/assest/floorAsset/setFloorItemApi";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useAssetsStore } from "../../../store/builder/useAssetStore"; import { useAssetsStore } from "../../../store/builder/useAssetStore";
import { getUserData } from "../../../functions/getUserData";
interface Asset { interface Asset {
id: string; id: string;
@ -52,7 +53,7 @@ const List: React.FC<ListProps> = ({ items = [], remove }) => {
const { projectId } = useParams(); const { projectId } = useParams();
const { setName } = useAssetsStore(); const { setName } = useAssetsStore();
const { userName, userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
useSelectedZoneStore.getState().setSelectedZone({ useSelectedZoneStore.getState().setSelectedZone({
zoneName: "", zoneName: "",
@ -81,8 +82,6 @@ const List: React.FC<ListProps> = ({ items = [], remove }) => {
setSubModule("zoneProperties"); setSubModule("zoneProperties");
const email = localStorage.getItem("email");
const organization = email?.split("@")[1]?.split(".")[0] ?? "";
let response = await getZoneData(id, organization, projectId); let response = await getZoneData(id, organization, projectId);
setSelectedZone({ setSelectedZone({
@ -105,9 +104,6 @@ const List: React.FC<ListProps> = ({ items = [], remove }) => {
} }
async function handleZoneNameChange(newName: string) { async function handleZoneNameChange(newName: string) {
const email = localStorage.getItem("email") ?? "";
const organization = email?.split("@")[1]?.split(".")[0];
const isDuplicate = zones.some( const isDuplicate = zones.some(
(zone: any) => (zone: any) =>
zone.zoneName?.trim().toLowerCase() === newName?.trim().toLowerCase() && zone.zoneName?.trim().toLowerCase() === newName?.trim().toLowerCase() &&
@ -136,8 +132,6 @@ const List: React.FC<ListProps> = ({ items = [], remove }) => {
} }
async function handleZoneAssetName(newName: string) { async function handleZoneAssetName(newName: string) {
const email = localStorage.getItem("email") ?? "";
const organization = email?.split("@")[1]?.split(".")[0];
if (zoneAssetId?.id) { if (zoneAssetId?.id) {
let response = await setFloorItemApi( let response = await setFloorItemApi(

View File

@ -8,6 +8,7 @@ import useVersionHistoryStore, {
} from "../../../store/builder/store"; } from "../../../store/builder/store";
import { useSubModuleStore } from "../../../store/useModuleStore"; import { useSubModuleStore } from "../../../store/useModuleStore";
import { generateUniqueId } from "../../../functions/generateUniqueId"; import { generateUniqueId } from "../../../functions/generateUniqueId";
import { getUserData } from "../../../functions/getUserData";
interface MenuBarProps { interface MenuBarProps {
setOpenMenu: (isOpen: boolean) => void; setOpenMenu: (isOpen: boolean) => void;
@ -22,7 +23,7 @@ interface MenuItem {
} }
const MenuBar: React.FC<MenuBarProps> = ({ setOpenMenu }) => { const MenuBar: React.FC<MenuBarProps> = ({ setOpenMenu }) => {
const userName = localStorage.getItem("userName") ?? "Anonymous"; const { userName } = getUserData();
const navigate = useNavigate(); const navigate = useNavigate();
const [activeMenu, setActiveMenu] = useState<string | null>(null); const [activeMenu, setActiveMenu] = useState<string | null>(null);
@ -82,7 +83,7 @@ const MenuBar: React.FC<MenuBarProps> = ({ setOpenMenu }) => {
day: "2-digit", day: "2-digit",
})}`, })}`,
savedBy: userName, savedBy: userName ?? "Anonymous",
}; };
console.log("newVersion: ", newVersion); console.log("newVersion: ", newVersion);

View File

@ -1,103 +1,108 @@
import { GLTF, GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { GLTF, GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'; import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import * as THREE from 'three'; import * as THREE from "three";
import * as Types from "../../../types/world/worldTypes"; import * as Types from "../../../types/world/worldTypes";
import { getWallItems } from '../../../services/factoryBuilder/assest/wallAsset/getWallItemsApi'; import { getWallItems } from "../../../services/factoryBuilder/assest/wallAsset/getWallItemsApi";
import { retrieveGLTF, storeGLTF } from '../../../utils/indexDB/idbUtils'; import { retrieveGLTF, storeGLTF } from "../../../utils/indexDB/idbUtils";
import { getUserData } from "../../../functions/getUserData";
async function loadInitialWallItems( async function loadInitialWallItems(
setWallItems: Types.setWallItemSetState, setWallItems: Types.setWallItemSetState,
projectId?: string projectId?: string
): Promise<void> { ): Promise<void> {
try { try {
const email = localStorage.getItem('email'); const { userId, organization, email } = getUserData();
if (!email) {
throw new Error('No email found in localStorage');
}
const organization = email.split("@")[1].split(".")[0]; if (!email) {
const items = await getWallItems(organization, projectId); throw new Error("No email found in localStorage");
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_MARKETPLACE_URL}`;
if (!items || items.length === 0) {
localStorage.removeItem("WallItems");
return;
}
localStorage.setItem("WallItems", JSON.stringify(items));
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/');
loader.setDRACOLoader(dracoLoader);
const loadedWallItems = await Promise.all(items.map(async (item: Types.WallItem) => {
// Check THREE.js cache first
const cachedModel = THREE.Cache.get(item.assetId!);
if (cachedModel) {
return processModel(cachedModel, item);
}
// Check IndexedDB cache
const cachedModelBlob = await retrieveGLTF(item.assetId!);
if (cachedModelBlob) {
const blobUrl = URL.createObjectURL(cachedModelBlob);
return new Promise<Types.WallItem>((resolve) => {
loader.load(blobUrl, (gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.add(item.assetId!, gltf);
resolve(processModel(gltf, item));
});
});
}
// Load from original URL if not cached
const modelUrl = `${url_Backend_dwinzo}/api/v2/AssetFile/${item.assetId!}`;
return new Promise<Types.WallItem>((resolve) => {
loader.load(modelUrl, async (gltf) => {
try {
// Cache the model
const modelBlob = await fetch(modelUrl).then((res) => res.blob());
await storeGLTF(item.assetId!, modelBlob);
THREE.Cache.add(item.assetId!, gltf);
resolve(processModel(gltf, item));
} catch (error) {
console.error('Failed to cache model:', error);
resolve(processModel(gltf, item));
}
});
});
}));
setWallItems(loadedWallItems);
} catch (error) {
console.error('Failed to load wall items:', error);
} }
const items = await getWallItems(organization, projectId);
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_MARKETPLACE_URL}`;
if (!items || items.length === 0) {
localStorage.removeItem("WallItems");
return;
}
localStorage.setItem("WallItems", JSON.stringify(items));
const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath(
"https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/"
);
loader.setDRACOLoader(dracoLoader);
const loadedWallItems = await Promise.all(
items.map(async (item: Types.WallItem) => {
// Check THREE.js cache first
const cachedModel = THREE.Cache.get(item.assetId!);
if (cachedModel) {
return processModel(cachedModel, item);
}
// Check IndexedDB cache
const cachedModelBlob = await retrieveGLTF(item.assetId!);
if (cachedModelBlob) {
const blobUrl = URL.createObjectURL(cachedModelBlob);
return new Promise<Types.WallItem>((resolve) => {
loader.load(blobUrl, (gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.add(item.assetId!, gltf);
resolve(processModel(gltf, item));
});
});
}
// Load from original URL if not cached
const modelUrl = `${url_Backend_dwinzo}/api/v2/AssetFile/${item.assetId!}`;
return new Promise<Types.WallItem>((resolve) => {
loader.load(modelUrl, async (gltf) => {
try {
// Cache the model
const modelBlob = await fetch(modelUrl).then((res) => res.blob());
await storeGLTF(item.assetId!, modelBlob);
THREE.Cache.add(item.assetId!, gltf);
resolve(processModel(gltf, item));
} catch (error) {
console.error("Failed to cache model:", error);
resolve(processModel(gltf, item));
}
});
});
})
);
setWallItems(loadedWallItems);
} catch (error) {
console.error("Failed to load wall items:", error);
}
} }
function processModel(gltf: GLTF, item: Types.WallItem): Types.WallItem { function processModel(gltf: GLTF, item: Types.WallItem): Types.WallItem {
const model = gltf.scene.clone(); const model = gltf.scene.clone();
model.uuid = item.modelUuid!; model.uuid = item.modelUuid!;
model.children[0]?.children?.forEach((child: THREE.Object3D) => { model.children[0]?.children?.forEach((child: THREE.Object3D) => {
if (child.name !== "CSG_REF") { if (child.name !== "CSG_REF") {
child.castShadow = true; child.castShadow = true;
child.receiveShadow = true; child.receiveShadow = true;
} }
}); });
return { return {
type: item.type, type: item.type,
model: model, model: model,
modelName: item.modelName, modelName: item.modelName,
assetId: item.assetId, assetId: item.assetId,
scale: item.scale, scale: item.scale,
csgscale: item.csgscale, csgscale: item.csgscale,
csgposition: item.csgposition, csgposition: item.csgposition,
position: item.position, position: item.position,
quaternion: item.quaternion, quaternion: item.quaternion,
}; };
} }
export default loadInitialWallItems; export default loadInitialWallItems;

View File

@ -14,6 +14,7 @@ import { CameraControls } from "@react-three/drei";
import addAssetModel from "./functions/addAssetModel"; import addAssetModel from "./functions/addAssetModel";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useLeftData, useTopData } from "../../../store/visualization/useZone3DWidgetStore"; import { useLeftData, useTopData } from "../../../store/visualization/useZone3DWidgetStore";
import { getUserData } from "../../../functions/getUserData";
const gltfLoaderWorker = new Worker( const gltfLoaderWorker = new Worker(
new URL( new URL(
@ -33,9 +34,7 @@ function AssetsGroup({ floorGroup, plane }: { readonly floorGroup: RefGroup, rea
const { selectedItem, setSelectedItem } = useSelectedItem(); const { selectedItem, setSelectedItem } = useSelectedItem();
const { projectId } = useParams(); const { projectId } = useParams();
const { isRenameMode, setIsRenameMode } = useRenameModeStore(); const { isRenameMode, setIsRenameMode } = useRenameModeStore();
const email = localStorage.getItem("email"); const { userId, organization, email } = getUserData();
const organization = email!.split("@")[1].split(".")[0];
const userId = localStorage.getItem("userId")!;
const { setTop } = useTopData(); const { setTop } = useTopData();
const { setLeft } = useLeftData(); const { setLeft } = useLeftData();

View File

@ -7,421 +7,485 @@ import { retrieveGLTF, storeGLTF } from "../../../../utils/indexDB/idbUtils";
import { Socket } from "socket.io-client"; import { Socket } from "socket.io-client";
import * as CONSTANTS from "../../../../types/world/worldConstants"; import * as CONSTANTS from "../../../../types/world/worldConstants";
import PointsCalculator from "../../../simulation/events/points/functions/pointsCalculator"; import PointsCalculator from "../../../simulation/events/points/functions/pointsCalculator";
import { getUserData } from "../../../../functions/getUserData";
async function addAssetModel( async function addAssetModel(
raycaster: THREE.Raycaster, raycaster: THREE.Raycaster,
camera: THREE.Camera, camera: THREE.Camera,
pointer: THREE.Vector2, pointer: THREE.Vector2,
floorGroup: Types.RefGroup, floorGroup: Types.RefGroup,
socket: Socket<any>, socket: Socket<any>,
selectedItem: any, selectedItem: any,
setSelectedItem: any, setSelectedItem: any,
addEvent: (event: EventsSchema) => void, addEvent: (event: EventsSchema) => void,
addAsset: (asset: Asset) => void, addAsset: (asset: Asset) => void,
plane: Types.RefMesh, plane: Types.RefMesh,
projectId?: string, projectId?: string,
userId?: string userId?: string
): Promise<void> { ): Promise<void> {
////////// Load Floor GLtf's and set the positions, rotation, type etc. in state and store in localstorage ////////// ////////// Load Floor GLtf's and set the positions, rotation, type etc. in state and store in localstorage //////////
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_MARKETPLACE_URL}`; let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_MARKETPLACE_URL}`;
try { try {
const loader = new GLTFLoader(); const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader(); const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath("https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/"); dracoLoader.setDecoderPath(
loader.setDRACOLoader(dracoLoader); "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/"
);
loader.setDRACOLoader(dracoLoader);
raycaster.setFromCamera(pointer, camera); raycaster.setFromCamera(pointer, camera);
const floorIntersections = raycaster.intersectObjects(floorGroup.current.children, true); const floorIntersections = raycaster.intersectObjects(
const intersectedFloor = floorIntersections.find((intersect) => intersect.object.name.includes("Floor")); floorGroup.current.children,
true
);
const intersectedFloor = floorIntersections.find((intersect) =>
intersect.object.name.includes("Floor")
);
const planeIntersections = raycaster.intersectObject(plane.current!, true); const planeIntersections = raycaster.intersectObject(plane.current!, true);
const intersectedPlane = planeIntersections[0]; const intersectedPlane = planeIntersections[0];
let intersectPoint: THREE.Vector3 | null = null; let intersectPoint: THREE.Vector3 | null = null;
if (intersectedFloor && intersectedPlane) { if (intersectedFloor && intersectedPlane) {
intersectPoint = intersectPoint =
intersectedFloor.distance < intersectedPlane.distance intersectedFloor.distance < intersectedPlane.distance
? new THREE.Vector3(intersectedFloor.point.x, Math.round(intersectedFloor.point.y), intersectedFloor.point.z) ? new THREE.Vector3(
: new THREE.Vector3(intersectedPlane.point.x, 0, intersectedPlane.point.z); intersectedFloor.point.x,
} else if (intersectedFloor) { Math.round(intersectedFloor.point.y),
intersectPoint = new THREE.Vector3(intersectedFloor.point.x, Math.round(intersectedFloor.point.y), intersectedFloor.point.z); intersectedFloor.point.z
} else if (intersectedPlane) { )
intersectPoint = new THREE.Vector3(intersectedPlane.point.x, 0, intersectedPlane.point.z); : new THREE.Vector3(
} intersectedPlane.point.x,
0,
if (intersectPoint) { intersectedPlane.point.z
if (intersectPoint.y < 0) { );
intersectPoint = new THREE.Vector3(intersectPoint.x, 0, intersectPoint.z); } else if (intersectedFloor) {
} intersectPoint = new THREE.Vector3(
const cachedModel = THREE.Cache.get(selectedItem.id); intersectedFloor.point.x,
if (cachedModel) { Math.round(intersectedFloor.point.y),
handleModelLoad(cachedModel, intersectPoint!, selectedItem, addEvent, addAsset, socket, projectId, userId); intersectedFloor.point.z
return; );
} else { } else if (intersectedPlane) {
const cachedModelBlob = await retrieveGLTF(selectedItem.id); intersectPoint = new THREE.Vector3(
if (cachedModelBlob) { intersectedPlane.point.x,
const blobUrl = URL.createObjectURL(cachedModelBlob); 0,
loader.load(blobUrl, (gltf) => { intersectedPlane.point.z
URL.revokeObjectURL(blobUrl); );
THREE.Cache.remove(blobUrl);
THREE.Cache.add(selectedItem.id, gltf);
handleModelLoad(gltf, intersectPoint!, selectedItem, addEvent, addAsset, socket, projectId, userId);
});
} else {
loader.load(`${url_Backend_dwinzo}/api/v2/AssetFile/${selectedItem.id}`, async (gltf) => {
const modelBlob = await fetch(`${url_Backend_dwinzo}/api/v2/AssetFile/${selectedItem.id}`).then((res) => res.blob());
await storeGLTF(selectedItem.id, modelBlob);
THREE.Cache.add(selectedItem.id, gltf);
await handleModelLoad(gltf, intersectPoint!, selectedItem, addEvent, addAsset, socket, projectId, userId);
}
);
}
}
}
} catch (error) {
echo.error("Failed to add asset");
} finally {
setSelectedItem({});
} }
if (intersectPoint) {
if (intersectPoint.y < 0) {
intersectPoint = new THREE.Vector3(
intersectPoint.x,
0,
intersectPoint.z
);
}
const cachedModel = THREE.Cache.get(selectedItem.id);
if (cachedModel) {
handleModelLoad(
cachedModel,
intersectPoint!,
selectedItem,
addEvent,
addAsset,
socket,
projectId,
userId
);
return;
} else {
const cachedModelBlob = await retrieveGLTF(selectedItem.id);
if (cachedModelBlob) {
const blobUrl = URL.createObjectURL(cachedModelBlob);
loader.load(blobUrl, (gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.remove(blobUrl);
THREE.Cache.add(selectedItem.id, gltf);
handleModelLoad(
gltf,
intersectPoint!,
selectedItem,
addEvent,
addAsset,
socket,
projectId,
userId
);
});
} else {
loader.load(
`${url_Backend_dwinzo}/api/v2/AssetFile/${selectedItem.id}`,
async (gltf) => {
const modelBlob = await fetch(
`${url_Backend_dwinzo}/api/v2/AssetFile/${selectedItem.id}`
).then((res) => res.blob());
await storeGLTF(selectedItem.id, modelBlob);
THREE.Cache.add(selectedItem.id, gltf);
await handleModelLoad(
gltf,
intersectPoint!,
selectedItem,
addEvent,
addAsset,
socket,
projectId,
userId
);
}
);
}
}
}
} catch (error) {
echo.error("Failed to add asset");
} finally {
setSelectedItem({});
}
} }
async function handleModelLoad( async function handleModelLoad(
gltf: any, gltf: any,
intersectPoint: THREE.Vector3, intersectPoint: THREE.Vector3,
selectedItem: any, selectedItem: any,
addEvent: (event: EventsSchema) => void, addEvent: (event: EventsSchema) => void,
addAsset: (asset: Asset) => void, addAsset: (asset: Asset) => void,
socket: Socket<any>, socket: Socket<any>,
projectId?: string, projectId?: string,
userId?: string userId?: string
) { ) {
const model = gltf.scene.clone(); const { userName, organization, email } = getUserData();
model.userData = { const model = gltf.scene.clone();
name: selectedItem.name, model.userData = {
modelId: selectedItem.id, name: selectedItem.name,
modelUuid: model.uuid, modelId: selectedItem.id,
}; modelUuid: model.uuid,
model.position.set(intersectPoint!.x, intersectPoint!.y, intersectPoint!.z); };
model.scale.set(...CONSTANTS.assetConfig.defaultScaleAfterGsap); model.position.set(intersectPoint!.x, intersectPoint!.y, intersectPoint!.z);
model.scale.set(...CONSTANTS.assetConfig.defaultScaleAfterGsap);
model.traverse((child: any) => { model.traverse((child: any) => {
if (child) { if (child) {
child.castShadow = true; child.castShadow = true;
child.receiveShadow = true; child.receiveShadow = true;
}
});
const newFloorItem: Asset = {
modelUuid: model.uuid,
modelName: selectedItem.name,
assetId: selectedItem.id,
position: [intersectPoint!.x, intersectPoint!.y, intersectPoint!.z],
rotation: [0, 0, 0],
isLocked: false,
isVisible: true,
isCollidable: false,
opacity: 1,
};
const email = localStorage.getItem("email");
const organization = email ? email.split("@")[1].split(".")[0] : "";
// API
// await setFloorItemApi(
// organization,
// newFloorItem.modelUuid,
// newFloorItem.modelName,
// newFloorItem.assetId,
// newFloorItem.position,
// { x: 0, y: 0, z: 0 },
// false,
// true,
// );
// SOCKET
if (selectedItem.type) {
const data = PointsCalculator(
selectedItem.type,
gltf.scene.clone(),
new THREE.Vector3(...model.rotation)
);
if (!data || !data.points) return;
const eventData: any = {
type: selectedItem.type,
};
if (selectedItem.type === "Conveyor") {
const ConveyorEvent: ConveyorEventSchema = {
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
position: newFloorItem.position,
rotation: newFloorItem.rotation,
state: "idle",
type: "transfer",
speed: 1,
points: data.points.map((point: THREE.Vector3, index: number) => {
const triggers: TriggerSchema[] = [];
if (data.points && index < data.points.length - 1) {
triggers.push({
triggerUuid: THREE.MathUtils.generateUUID(),
triggerName: `Trigger 1`,
triggerType: "onComplete",
delay: 0,
triggeredAsset: {
triggeredModel: {
modelName: newFloorItem.modelName,
modelUuid: newFloorItem.modelUuid,
},
triggeredPoint: {
pointName: `Point`,
pointUuid: "",
},
triggeredAction: {
actionName: `Action 1`,
actionUuid: "",
},
},
});
}
return {
uuid: THREE.MathUtils.generateUUID(),
position: [point.x, point.y, point.z],
rotation: [0, 0, 0],
action: {
actionUuid: THREE.MathUtils.generateUUID(),
actionName: `Action 1`,
actionType: "default",
material: "Default Material",
delay: 0,
spawnInterval: 5,
spawnCount: 1,
triggers: triggers,
},
};
}),
};
for (let i = 0; i < ConveyorEvent.points.length - 1; i++) {
const currentPoint = ConveyorEvent.points[i];
const nextPoint = ConveyorEvent.points[i + 1];
if (currentPoint.action.triggers.length > 0) {
currentPoint.action.triggers[0].triggeredAsset!.triggeredPoint!.pointUuid = nextPoint.uuid;
currentPoint.action.triggers[0].triggeredAsset!.triggeredAction!.actionUuid = nextPoint.action.actionUuid;
}
}
addEvent(ConveyorEvent);
eventData.points = ConveyorEvent.points.map((point) => ({
uuid: point.uuid,
position: point.position,
rotation: point.rotation,
}));
} else if (selectedItem.type === "Vehicle") {
const vehicleEvent: VehicleEventSchema = {
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
position: newFloorItem.position,
rotation: newFloorItem.rotation,
state: "idle",
type: "vehicle",
speed: 1,
point: {
uuid: THREE.MathUtils.generateUUID(),
position: [data.points[0].x, data.points[0].y, data.points[0].z],
rotation: [0, 0, 0],
action: {
actionUuid: THREE.MathUtils.generateUUID(),
actionName: "Action 1",
actionType: "travel",
unLoadDuration: 5,
loadCapacity: 1,
steeringAngle: 0,
pickUpPoint: null,
unLoadPoint: null,
triggers: [],
},
},
};
addEvent(vehicleEvent);
eventData.point = {
uuid: vehicleEvent.point.uuid,
position: vehicleEvent.point.position,
rotation: vehicleEvent.point.rotation,
};
} else if (selectedItem.type === "ArmBot") {
const roboticArmEvent: RoboticArmEventSchema = {
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
position: newFloorItem.position,
rotation: newFloorItem.rotation,
state: "idle",
type: "roboticArm",
speed: 1,
point: {
uuid: THREE.MathUtils.generateUUID(),
position: [data.points[0].x, data.points[0].y, data.points[0].z],
rotation: [0, 0, 0],
actions: [
{
actionUuid: THREE.MathUtils.generateUUID(),
actionName: "Action 1",
actionType: "pickAndPlace",
process: {
startPoint: null,
endPoint: null,
},
triggers: [],
},
],
},
};
addEvent(roboticArmEvent);
eventData.point = {
uuid: roboticArmEvent.point.uuid,
position: roboticArmEvent.point.position,
rotation: roboticArmEvent.point.rotation,
};
} else if (selectedItem.type === "StaticMachine") {
const machineEvent: MachineEventSchema = {
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
position: newFloorItem.position,
rotation: newFloorItem.rotation,
state: "idle",
type: "machine",
point: {
uuid: THREE.MathUtils.generateUUID(),
position: [data.points[0].x, data.points[0].y, data.points[0].z],
rotation: [0, 0, 0],
action: {
actionUuid: THREE.MathUtils.generateUUID(),
actionName: "Action 1",
actionType: "process",
processTime: 10,
swapMaterial: "Default Material",
triggers: [],
},
},
};
addEvent(machineEvent);
eventData.point = {
uuid: machineEvent.point.uuid,
position: machineEvent.point.position,
rotation: machineEvent.point.rotation,
};
} else if (selectedItem.type === "Storage") {
const storageEvent: StorageEventSchema = {
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
position: newFloorItem.position,
rotation: newFloorItem.rotation,
state: "idle",
type: "storageUnit",
point: {
uuid: THREE.MathUtils.generateUUID(),
position: [data.points[0].x, data.points[0].y, data.points[0].z],
rotation: [0, 0, 0],
action: {
actionUuid: THREE.MathUtils.generateUUID(),
actionName: "Action 1",
actionType: "store",
storageCapacity: 10,
triggers: [],
},
},
};
addEvent(storageEvent);
eventData.point = {
uuid: storageEvent.point.uuid,
position: storageEvent.point.position,
rotation: storageEvent.point.rotation,
};
}
const completeData = {
organization,
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
assetId: newFloorItem.assetId,
position: newFloorItem.position,
rotation: {
x: model.rotation.x,
y: model.rotation.y,
z: model.rotation.z,
},
isLocked: false,
isVisible: true,
socketId: socket.id,
eventData: eventData,
projectId: projectId,
userId: userId,
};
socket.emit("v1:model-asset:add", completeData);
const asset: Asset = {
modelUuid: completeData.modelUuid,
modelName: completeData.modelName,
assetId: completeData.assetId,
position: completeData.position,
rotation: [
completeData.rotation.x,
completeData.rotation.y,
completeData.rotation.z,
] as [number, number, number],
isLocked: completeData.isLocked,
isCollidable: false,
isVisible: completeData.isVisible,
opacity: 1,
eventData: completeData.eventData,
};
addAsset(asset);
} else {
const data = {
organization,
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
assetId: newFloorItem.assetId,
position: newFloorItem.position,
rotation: {
x: model.rotation.x,
y: model.rotation.y,
z: model.rotation.z,
},
isLocked: false,
isVisible: true,
socketId: socket.id,
projectId: projectId,
userId: userId,
};
socket.emit("v1:model-asset:add", data);
const asset = {
modelUuid: data.modelUuid,
modelName: data.modelName,
assetId: data.assetId,
position: data.position,
rotation: [data.rotation.x, data.rotation.y, data.rotation.z] as [number, number, number],
isLocked: data.isLocked,
isCollidable: false,
isVisible: data.isVisible,
opacity: 1,
};
addAsset(asset);
} }
});
const newFloorItem: Asset = {
modelUuid: model.uuid,
modelName: selectedItem.name,
assetId: selectedItem.id,
position: [intersectPoint!.x, intersectPoint!.y, intersectPoint!.z],
rotation: [0, 0, 0],
isLocked: false,
isVisible: true,
isCollidable: false,
opacity: 1,
};
// API
// await setFloorItemApi(
// organization,
// newFloorItem.modelUuid,
// newFloorItem.modelName,
// newFloorItem.assetId,
// newFloorItem.position,
// { x: 0, y: 0, z: 0 },
// false,
// true,
// );
// SOCKET
if (selectedItem.type) {
const data = PointsCalculator(
selectedItem.type,
gltf.scene.clone(),
new THREE.Vector3(...model.rotation)
);
if (!data || !data.points) return;
const eventData: any = {
type: selectedItem.type,
};
if (selectedItem.type === "Conveyor") {
const ConveyorEvent: ConveyorEventSchema = {
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
position: newFloorItem.position,
rotation: newFloorItem.rotation,
state: "idle",
type: "transfer",
speed: 1,
points: data.points.map((point: THREE.Vector3, index: number) => {
const triggers: TriggerSchema[] = [];
if (data.points && index < data.points.length - 1) {
triggers.push({
triggerUuid: THREE.MathUtils.generateUUID(),
triggerName: `Trigger 1`,
triggerType: "onComplete",
delay: 0,
triggeredAsset: {
triggeredModel: {
modelName: newFloorItem.modelName,
modelUuid: newFloorItem.modelUuid,
},
triggeredPoint: {
pointName: `Point`,
pointUuid: "",
},
triggeredAction: {
actionName: `Action 1`,
actionUuid: "",
},
},
});
}
return {
uuid: THREE.MathUtils.generateUUID(),
position: [point.x, point.y, point.z],
rotation: [0, 0, 0],
action: {
actionUuid: THREE.MathUtils.generateUUID(),
actionName: `Action 1`,
actionType: "default",
material: "Default Material",
delay: 0,
spawnInterval: 5,
spawnCount: 1,
triggers: triggers,
},
};
}),
};
for (let i = 0; i < ConveyorEvent.points.length - 1; i++) {
const currentPoint = ConveyorEvent.points[i];
const nextPoint = ConveyorEvent.points[i + 1];
if (currentPoint.action.triggers.length > 0) {
currentPoint.action.triggers[0].triggeredAsset!.triggeredPoint!.pointUuid =
nextPoint.uuid;
currentPoint.action.triggers[0].triggeredAsset!.triggeredAction!.actionUuid =
nextPoint.action.actionUuid;
}
}
addEvent(ConveyorEvent);
eventData.points = ConveyorEvent.points.map((point) => ({
uuid: point.uuid,
position: point.position,
rotation: point.rotation,
}));
} else if (selectedItem.type === "Vehicle") {
const vehicleEvent: VehicleEventSchema = {
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
position: newFloorItem.position,
rotation: newFloorItem.rotation,
state: "idle",
type: "vehicle",
speed: 1,
point: {
uuid: THREE.MathUtils.generateUUID(),
position: [data.points[0].x, data.points[0].y, data.points[0].z],
rotation: [0, 0, 0],
action: {
actionUuid: THREE.MathUtils.generateUUID(),
actionName: "Action 1",
actionType: "travel",
unLoadDuration: 5,
loadCapacity: 1,
steeringAngle: 0,
pickUpPoint: null,
unLoadPoint: null,
triggers: [],
},
},
};
addEvent(vehicleEvent);
eventData.point = {
uuid: vehicleEvent.point.uuid,
position: vehicleEvent.point.position,
rotation: vehicleEvent.point.rotation,
};
} else if (selectedItem.type === "ArmBot") {
const roboticArmEvent: RoboticArmEventSchema = {
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
position: newFloorItem.position,
rotation: newFloorItem.rotation,
state: "idle",
type: "roboticArm",
speed: 1,
point: {
uuid: THREE.MathUtils.generateUUID(),
position: [data.points[0].x, data.points[0].y, data.points[0].z],
rotation: [0, 0, 0],
actions: [
{
actionUuid: THREE.MathUtils.generateUUID(),
actionName: "Action 1",
actionType: "pickAndPlace",
process: {
startPoint: null,
endPoint: null,
},
triggers: [],
},
],
},
};
addEvent(roboticArmEvent);
eventData.point = {
uuid: roboticArmEvent.point.uuid,
position: roboticArmEvent.point.position,
rotation: roboticArmEvent.point.rotation,
};
} else if (selectedItem.type === "StaticMachine") {
const machineEvent: MachineEventSchema = {
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
position: newFloorItem.position,
rotation: newFloorItem.rotation,
state: "idle",
type: "machine",
point: {
uuid: THREE.MathUtils.generateUUID(),
position: [data.points[0].x, data.points[0].y, data.points[0].z],
rotation: [0, 0, 0],
action: {
actionUuid: THREE.MathUtils.generateUUID(),
actionName: "Action 1",
actionType: "process",
processTime: 10,
swapMaterial: "Default Material",
triggers: [],
},
},
};
addEvent(machineEvent);
eventData.point = {
uuid: machineEvent.point.uuid,
position: machineEvent.point.position,
rotation: machineEvent.point.rotation,
};
} else if (selectedItem.type === "Storage") {
const storageEvent: StorageEventSchema = {
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
position: newFloorItem.position,
rotation: newFloorItem.rotation,
state: "idle",
type: "storageUnit",
point: {
uuid: THREE.MathUtils.generateUUID(),
position: [data.points[0].x, data.points[0].y, data.points[0].z],
rotation: [0, 0, 0],
action: {
actionUuid: THREE.MathUtils.generateUUID(),
actionName: "Action 1",
actionType: "store",
storageCapacity: 10,
triggers: [],
},
},
};
addEvent(storageEvent);
eventData.point = {
uuid: storageEvent.point.uuid,
position: storageEvent.point.position,
rotation: storageEvent.point.rotation,
};
}
const completeData = {
organization,
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
assetId: newFloorItem.assetId,
position: newFloorItem.position,
rotation: {
x: model.rotation.x,
y: model.rotation.y,
z: model.rotation.z,
},
isLocked: false,
isVisible: true,
socketId: socket.id,
eventData: eventData,
projectId: projectId,
userId: userId,
};
socket.emit("v1:model-asset:add", completeData);
const asset: Asset = {
modelUuid: completeData.modelUuid,
modelName: completeData.modelName,
assetId: completeData.assetId,
position: completeData.position,
rotation: [
completeData.rotation.x,
completeData.rotation.y,
completeData.rotation.z,
] as [number, number, number],
isLocked: completeData.isLocked,
isCollidable: false,
isVisible: completeData.isVisible,
opacity: 1,
eventData: completeData.eventData,
};
addAsset(asset);
} else {
const data = {
organization,
modelUuid: newFloorItem.modelUuid,
modelName: newFloorItem.modelName,
assetId: newFloorItem.assetId,
position: newFloorItem.position,
rotation: {
x: model.rotation.x,
y: model.rotation.y,
z: model.rotation.z,
},
isLocked: false,
isVisible: true,
socketId: socket.id,
projectId: projectId,
userId: userId,
};
socket.emit("v1:model-asset:add", data);
const asset = {
modelUuid: data.modelUuid,
modelName: data.modelName,
assetId: data.assetId,
position: data.position,
rotation: [data.rotation.x, data.rotation.y, data.rotation.z] as [
number,
number,
number
],
isLocked: data.isLocked,
isCollidable: false,
isVisible: data.isVisible,
opacity: 1,
};
addAsset(asset);
}
} }
export default addAssetModel; export default addAssetModel;

View File

@ -15,6 +15,7 @@ import { useLeftData, useTopData } from '../../../../../store/visualization/useZ
import { useSelectedAsset } from '../../../../../store/simulation/useSimulationStore'; import { useSelectedAsset } from '../../../../../store/simulation/useSimulationStore';
import { useProductContext } from '../../../../simulation/products/productContext'; import { useProductContext } from '../../../../simulation/products/productContext';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
import { getUserData } from '../../../../../functions/getUserData';
function Model({ asset }: { readonly asset: Asset }) { function Model({ asset }: { readonly asset: Asset }) {
const { camera, controls, gl } = useThree(); const { camera, controls, gl } = useThree();
@ -41,6 +42,7 @@ function Model({ asset }: { readonly asset: Asset }) {
const groupRef = useRef<THREE.Group>(null); const groupRef = useRef<THREE.Group>(null);
const { toolMode } = useToolMode(); const { toolMode } = useToolMode();
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
setDeletableFloorItem(null); setDeletableFloorItem(null);
@ -162,9 +164,7 @@ function Model({ asset }: { readonly asset: Asset }) {
const handleClick = (asset: Asset) => { const handleClick = (asset: Asset) => {
if (activeTool === 'delete' && deletableFloorItem && deletableFloorItem.uuid === asset.modelUuid) { if (activeTool === 'delete' && deletableFloorItem && deletableFloorItem.uuid === asset.modelUuid) {
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
//REST //REST
@ -173,7 +173,7 @@ function Model({ asset }: { readonly asset: Asset }) {
//SOCKET //SOCKET
const data = { const data = {
organization: organization, organization,
modelUuid: asset.modelUuid, modelUuid: asset.modelUuid,
modelName: asset.modelName, modelName: asset.modelName,
socketId: socket.id, socketId: socket.id,

View File

@ -51,6 +51,7 @@ import { useParams } from "react-router-dom";
import AislesGroup from "./aisle/aislesGroup"; import AislesGroup from "./aisle/aislesGroup";
import WallGroup from "./wall/wallGroup"; import WallGroup from "./wall/wallGroup";
import { useBuilderStore } from "../../store/builder/useBuilderStore"; import { useBuilderStore } from "../../store/builder/useBuilderStore";
import { getUserData } from "../../functions/getUserData";
export default function Builder() { export default function Builder() {
const state = useThree<Types.ThreeState>(); // Importing the state from the useThree hook, which contains the scene, camera, and other Three.js elements. const state = useThree<Types.ThreeState>(); // Importing the state from the useThree hook, which contains the scene, camera, and other Three.js elements.
@ -104,6 +105,7 @@ export default function Builder() {
const { refTextupdate, setRefTextUpdate } = useRefTextUpdate(); const { refTextupdate, setRefTextUpdate } = useRefTextUpdate();
const { projectId } = useParams(); const { projectId } = useParams();
const { setHoveredPoint } = useBuilderStore(); const { setHoveredPoint } = useBuilderStore();
const { userId, organization, email } = getUserData();
// const loader = new GLTFLoader(); // const loader = new GLTFLoader();
// const dracoLoader = new DRACOLoader(); // const dracoLoader = new DRACOLoader();
@ -134,8 +136,6 @@ export default function Builder() {
}, [toggleView]); }, [toggleView]);
useEffect(() => { useEffect(() => {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
async function fetchVisibility() { async function fetchVisibility() {
const data = await findEnvironment(organization, localStorage.getItem("userId")!, projectId); const data = await findEnvironment(organization, localStorage.getItem("userId")!, projectId);

View File

@ -8,6 +8,7 @@ import { getWallPointsFromBlueprint } from './functions/getWallPointsFromBluepri
import * as Types from '../../../types/world/worldTypes'; import * as Types from '../../../types/world/worldTypes';
import arrayLineToObject from '../geomentries/lines/lineConvertions/arrayLineToObject'; import arrayLineToObject from '../geomentries/lines/lineConvertions/arrayLineToObject';
import { useParams } from 'react-router-dom'; import { useParams } from 'react-router-dom';
import { getUserData } from '../../../functions/getUserData';
// Interface defining the props for the DxfFile component // Interface defining the props for the DxfFile component
interface DxfFileProps { interface DxfFileProps {
@ -36,6 +37,7 @@ const DxfFile = ({
const { toggleView } = useToggleView(); const { toggleView } = useToggleView();
const { socket } = useSocketStore(); const { socket } = useSocketStore();
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
// Refs for storing line objects // Refs for storing line objects
const lineRefs = useRef<Line[]>([]); const lineRefs = useRef<Line[]>([]);
@ -56,9 +58,6 @@ const DxfFile = ({
lines.current.push(...dfxWallGenerate); lines.current.push(...dfxWallGenerate);
dfxWallGenerate.map((line: any) => { dfxWallGenerate.map((line: any) => {
const lineData = arrayLineToObject(line as Types.Line); const lineData = arrayLineToObject(line as Types.Line);
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
//REST //REST
@ -67,7 +66,7 @@ const DxfFile = ({
//SOCKET //SOCKET
const input = { const input = {
organization: organization, organization,
layer: lineData.layer, layer: lineData.layer,
line: lineData.line, line: lineData.line,
type: lineData.type, type: lineData.type,

View File

@ -1,84 +1,98 @@
import * as THREE from 'three'; import * as THREE from "three";
import { DragControls } from 'three/examples/jsm/controls/DragControls'; import { DragControls } from "three/examples/jsm/controls/DragControls";
import * as CONSTANTS from '../../../types/world/worldConstants'; import * as CONSTANTS from "../../../types/world/worldConstants";
import DragPoint from '../geomentries/points/dragPoint'; import DragPoint from "../geomentries/points/dragPoint";
import * as Types from "../../../types/world/worldTypes"; import * as Types from "../../../types/world/worldTypes";
// import { updatePoint } from '../../../services/factoryBuilder/lines/updatePointApi'; // import { updatePoint } from '../../../services/factoryBuilder/lines/updatePointApi';
import { Socket } from 'socket.io-client'; import { Socket } from "socket.io-client";
import { getUserData } from "../../../functions/getUserData";
export default async function addDragControl( export default async function addDragControl(
dragPointControls: Types.RefDragControl, dragPointControls: Types.RefDragControl,
currentLayerPoint: Types.RefMeshArray, currentLayerPoint: Types.RefMeshArray,
state: Types.ThreeState, state: Types.ThreeState,
floorPlanGroupPoint: Types.RefGroup, floorPlanGroupPoint: Types.RefGroup,
floorPlanGroupLine: Types.RefGroup, floorPlanGroupLine: Types.RefGroup,
lines: Types.RefLines, lines: Types.RefLines,
onlyFloorlines: Types.RefOnlyFloorLines, onlyFloorlines: Types.RefOnlyFloorLines,
socket: Socket<any>, socket: Socket<any>,
projectId?:string projectId?: string
) { ) {
////////// Dragging Point and also change the size to indicate during hover //////////
////////// Dragging Point and also change the size to indicate during hover ////////// dragPointControls.current = new DragControls(
currentLayerPoint.current,
state.camera,
state.gl.domElement
);
dragPointControls.current.enabled = false;
const { userId, organization, email } = getUserData();
dragPointControls.current.addEventListener("drag", function (event) {
const object = event.object;
if (object.visible) {
(state.controls as any).enabled = false;
DragPoint(
event as any,
floorPlanGroupPoint,
floorPlanGroupLine,
state.scene,
lines,
onlyFloorlines
);
} else {
(state.controls as any).enabled = true;
}
});
dragPointControls.current = new DragControls(currentLayerPoint.current, state.camera, state.gl.domElement); dragPointControls.current.addEventListener("dragstart", function (event) {});
dragPointControls.current.enabled = false;
dragPointControls.current.addEventListener('drag', function (event) { dragPointControls.current.addEventListener("dragend", async function (event) {
const object = event.object; if (!dragPointControls.current) return;
if (object.visible) {
(state.controls as any).enabled = false;
DragPoint(event as any, floorPlanGroupPoint, floorPlanGroupLine, state.scene, lines, onlyFloorlines)
} else {
(state.controls as any).enabled = true;
}
});
dragPointControls.current.addEventListener('dragstart', function (event) { //REST
});
dragPointControls.current.addEventListener('dragend', async function (event) { // await updatePoint(
if (!dragPointControls.current) return; // organization,
const email = localStorage.getItem('email') // { "x": event.object.position.x, "y": 0.01, "z": event.object.position.z },
const organization = (email!.split("@")[1]).split(".")[0]; // event.object.uuid,
const userId = localStorage.getItem("userId"); // )
//REST //SOCKET
// await updatePoint( const data = {
// organization, organization,
// { "x": event.object.position.x, "y": 0.01, "z": event.object.position.z }, position: {
// event.object.uuid, x: event.object.position.x,
// ) y: 0.01,
z: event.object.position.z,
},
uuid: event.object.uuid,
socketId: socket.id,
projectId,
userId,
};
//SOCKET socket.emit("v1:Line:update", data);
const data = { if (state.controls) {
organization: organization, (state.controls as any).enabled = true;
position: { "x": event.object.position.x, "y": 0.01, "z": event.object.position.z }, }
uuid: event.object.uuid, });
socketId: socket.id,
projectId,
userId
}
socket.emit('v1:Line:update', data); dragPointControls.current.addEventListener("hoveron", function (event: any) {
if ((event.object as Types.Mesh).name === "point") {
if (state.controls) { event.object.material.uniforms.uInnerColor.value.set(
(state.controls as any).enabled = true; event.object.userData.color
} );
}); }
});
dragPointControls.current.addEventListener('hoveron', function (event: any) {
if ((event.object as Types.Mesh).name === "point") {
event.object.material.uniforms.uInnerColor.value.set(event.object.userData.color)
}
});
dragPointControls.current.addEventListener('hoveroff', function (event: any) {
if ((event.object as Types.Mesh).name === "point") {
event.object.material.uniforms.uInnerColor.value.set(new THREE.Color(CONSTANTS.pointConfig.defaultInnerColor))
}
});
dragPointControls.current.addEventListener("hoveroff", function (event: any) {
if ((event.object as Types.Mesh).name === "point") {
event.object.material.uniforms.uInnerColor.value.set(
new THREE.Color(CONSTANTS.pointConfig.defaultInnerColor)
);
}
});
} }

View File

@ -1,157 +1,145 @@
import * as THREE from 'three'; import * as THREE from "three";
import * as Types from "../../../../types/world/worldTypes"; import * as Types from "../../../../types/world/worldTypes";
import * as CONSTANTS from '../../../../types/world/worldConstants'; import * as CONSTANTS from "../../../../types/world/worldConstants";
import addPointToScene from '../points/addPointToScene'; import addPointToScene from "../points/addPointToScene";
import addLineToScene from '../lines/addLineToScene'; import addLineToScene from "../lines/addLineToScene";
import splitLine from '../lines/splitLine'; import splitLine from "../lines/splitLine";
import removeReferenceLine from '../lines/removeReferenceLine'; import removeReferenceLine from "../lines/removeReferenceLine";
import getClosestIntersection from '../lines/getClosestIntersection'; import getClosestIntersection from "../lines/getClosestIntersection";
import arrayLineToObject from '../lines/lineConvertions/arrayLineToObject'; import arrayLineToObject from "../lines/lineConvertions/arrayLineToObject";
// import { setLine } from '../../../../services/factoryBuilder/lines/setLineApi'; // import { setLine } from '../../../../services/factoryBuilder/lines/setLineApi';
import { Socket } from 'socket.io-client'; import { Socket } from "socket.io-client";
import { getUserData } from "../../../../functions/getUserData";
async function drawOnlyFloor( async function drawOnlyFloor(
raycaster: THREE.Raycaster, raycaster: THREE.Raycaster,
state: Types.ThreeState, state: Types.ThreeState,
camera: THREE.Camera, camera: THREE.Camera,
plane: Types.RefMesh, plane: Types.RefMesh,
floorPlanGroupPoint: Types.RefGroup, floorPlanGroupPoint: Types.RefGroup,
snappedPoint: Types.RefVector3, snappedPoint: Types.RefVector3,
isSnapped: Types.RefBoolean, isSnapped: Types.RefBoolean,
isSnappedUUID: Types.RefString, isSnappedUUID: Types.RefString,
line: Types.RefLine, line: Types.RefLine,
ispreSnapped: Types.RefBoolean, ispreSnapped: Types.RefBoolean,
anglesnappedPoint: Types.RefVector3, anglesnappedPoint: Types.RefVector3,
isAngleSnapped: Types.RefBoolean, isAngleSnapped: Types.RefBoolean,
onlyFloorline: Types.RefOnlyFloorLine, onlyFloorline: Types.RefOnlyFloorLine,
onlyFloorlines: Types.RefOnlyFloorLines, onlyFloorlines: Types.RefOnlyFloorLines,
lines: Types.RefLines, lines: Types.RefLines,
floorPlanGroupLine: Types.RefGroup, floorPlanGroupLine: Types.RefGroup,
floorPlanGroup: Types.RefGroup, floorPlanGroup: Types.RefGroup,
ReferenceLineMesh: Types.RefMesh, ReferenceLineMesh: Types.RefMesh,
LineCreated: Types.RefBoolean, LineCreated: Types.RefBoolean,
currentLayerPoint: Types.RefMeshArray, currentLayerPoint: Types.RefMeshArray,
dragPointControls: Types.RefDragControl, dragPointControls: Types.RefDragControl,
setNewLines: any, setNewLines: any,
setDeletedLines: any, setDeletedLines: any,
activeLayer: Types.Number, activeLayer: Types.Number,
socket: Socket<any>, socket: Socket<any>,
projectId?:string projectId?: string
): Promise<void> { ): Promise<void> {
////////// Creating lines Based on the positions clicked //////////
////////// Creating lines Based on the positions clicked ////////// if (!plane.current) return;
const { userId, organization, email } = getUserData();
const intersects = raycaster.intersectObject(plane.current, true);
const intersectsLines = raycaster.intersectObjects(
floorPlanGroupLine.current.children,
true
);
const intersectsPoint = raycaster.intersectObjects(
floorPlanGroupPoint.current.children,
true
);
const VisibleintersectsPoint = intersectsPoint.find(
(intersect) => intersect.object.visible
);
const visibleIntersect = intersectsLines.find(
(intersect) =>
intersect.object.visible &&
intersect.object.name !== CONSTANTS.lineConfig.referenceName
);
if (
(intersectsPoint.length === 0 || VisibleintersectsPoint === undefined) &&
intersectsLines.length > 0 &&
!isSnapped.current &&
!ispreSnapped.current
) {
////////// Clicked on a preexisting Line //////////
if (!plane.current) return if (
const intersects = raycaster.intersectObject(plane.current, true); visibleIntersect &&
const intersectsLines = raycaster.intersectObjects(floorPlanGroupLine.current.children, true); (intersectsLines[0].object.userData.linePoints[0][3] ===
const intersectsPoint = raycaster.intersectObjects(floorPlanGroupPoint.current.children, true); CONSTANTS.lineConfig.floorName ||
const VisibleintersectsPoint = intersectsPoint.find(intersect => intersect.object.visible); intersectsLines[0].object.userData.linePoints[0][3] ===
const visibleIntersect = intersectsLines.find(intersect => intersect.object.visible && intersect.object.name !== CONSTANTS.lineConfig.referenceName); CONSTANTS.lineConfig.wallName)
) {
let pointColor, lineColor;
if (
intersectsLines[0].object.userData.linePoints[0][3] ===
CONSTANTS.lineConfig.wallName
) {
pointColor = CONSTANTS.pointConfig.wallOuterColor;
lineColor = CONSTANTS.lineConfig.wallColor;
} else {
pointColor = CONSTANTS.pointConfig.floorOuterColor;
lineColor = CONSTANTS.lineConfig.floorColor;
}
let IntersectsPoint = new THREE.Vector3(
intersects[0].point.x,
0.01,
intersects[0].point.z
);
if (
isAngleSnapped.current &&
line.current.length > 0 &&
anglesnappedPoint.current
) {
IntersectsPoint = anglesnappedPoint.current;
}
if (visibleIntersect.object instanceof THREE.Mesh) {
const ThroughPoint =
visibleIntersect.object.geometry.parameters.path.getPoints(
CONSTANTS.lineConfig.lineIntersectionPoints
);
let intersectionPoint = getClosestIntersection(
ThroughPoint,
IntersectsPoint
);
if ((intersectsPoint.length === 0 || VisibleintersectsPoint === undefined) && intersectsLines.length > 0 && !isSnapped.current && !ispreSnapped.current) { if (intersectionPoint) {
const newLines = splitLine(
visibleIntersect,
intersectionPoint,
currentLayerPoint,
floorPlanGroupPoint,
dragPointControls,
isSnappedUUID,
lines,
setDeletedLines,
floorPlanGroupLine,
socket,
pointColor,
lineColor,
intersectsLines[0].object.userData.linePoints[0][3],
projectId
);
setNewLines([newLines[0], newLines[1]]);
////////// Clicked on a preexisting Line ////////// (line.current as Types.Line).push([
new THREE.Vector3(intersectionPoint.x, 0.01, intersectionPoint.z),
isSnappedUUID.current!,
activeLayer,
CONSTANTS.lineConfig.floorName,
]);
if (visibleIntersect && (intersectsLines[0].object.userData.linePoints[0][3] === CONSTANTS.lineConfig.floorName || intersectsLines[0].object.userData.linePoints[0][3] === CONSTANTS.lineConfig.wallName)) { if (line.current.length >= 2 && line.current[0] && line.current[1]) {
let pointColor, lineColor;
if (intersectsLines[0].object.userData.linePoints[0][3] === CONSTANTS.lineConfig.wallName) {
pointColor = CONSTANTS.pointConfig.wallOuterColor;
lineColor = CONSTANTS.lineConfig.wallColor;
} else {
pointColor = CONSTANTS.pointConfig.floorOuterColor;
lineColor = CONSTANTS.lineConfig.floorColor;
}
let IntersectsPoint = new THREE.Vector3(intersects[0].point.x, 0.01, intersects[0].point.z);
if (isAngleSnapped.current && line.current.length > 0 && anglesnappedPoint.current) {
IntersectsPoint = anglesnappedPoint.current;
}
if (visibleIntersect.object instanceof THREE.Mesh) {
const ThroughPoint = (visibleIntersect.object.geometry.parameters.path).getPoints(CONSTANTS.lineConfig.lineIntersectionPoints);
let intersectionPoint = getClosestIntersection(ThroughPoint, IntersectsPoint);
if (intersectionPoint) {
const newLines = splitLine(visibleIntersect, intersectionPoint, currentLayerPoint, floorPlanGroupPoint, dragPointControls, isSnappedUUID, lines, setDeletedLines, floorPlanGroupLine, socket, pointColor, lineColor, intersectsLines[0].object.userData.linePoints[0][3],projectId);
setNewLines([newLines[0], newLines[1]]);
(line.current as Types.Line).push([new THREE.Vector3(intersectionPoint.x, 0.01, intersectionPoint.z), isSnappedUUID.current!, activeLayer, CONSTANTS.lineConfig.floorName]);
if (line.current.length >= 2 && line.current[0] && line.current[1]) {
lines.current.push(line.current as Types.Line);
const data = arrayLineToObject(line.current as Types.Line);
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
//REST
// setLine(organization, data.layer!, data.line!, data.type!);
//SOCKET
const input = {
organization: organization,
layer: data.layer,
line: data.line,
type: data.type,
socketId: socket.id,
projectId,
userId
}
socket.emit('v1:Line:create', input);
setNewLines([newLines[0], newLines[1], line.current]);
onlyFloorline.current.push(line.current as Types.Line);
onlyFloorlines.current.push(onlyFloorline.current);
onlyFloorline.current = [];
addLineToScene(line.current[0][0], line.current[1][0], CONSTANTS.lineConfig.floorColor, line.current, floorPlanGroupLine);
removeReferenceLine(floorPlanGroup, ReferenceLineMesh, LineCreated, line);
}
return;
}
}
}
}
if (intersects.length > 0 && intersectsLines.length === 0) {
////////// Clicked on an empty place or a point //////////
let intersectionPoint = intersects[0].point;
if (isAngleSnapped.current && line.current.length > 0 && anglesnappedPoint.current) {
intersectionPoint = anglesnappedPoint.current;
}
if (isSnapped.current && line.current.length > 0 && snappedPoint.current) {
intersectionPoint = snappedPoint.current;
}
if (ispreSnapped.current && snappedPoint.current) {
intersectionPoint = snappedPoint.current;
}
if (!isSnapped.current && !ispreSnapped.current) {
addPointToScene(intersectionPoint, CONSTANTS.pointConfig.floorOuterColor, currentLayerPoint, floorPlanGroupPoint, dragPointControls, isSnappedUUID, CONSTANTS.lineConfig.floorName);
} else {
ispreSnapped.current = false;
isSnapped.current = false;
}
(line.current as Types.Line).push([new THREE.Vector3(intersectionPoint.x, 0.01, intersectionPoint.z), isSnappedUUID.current!, activeLayer, CONSTANTS.lineConfig.floorName]);
if (line.current.length >= 2 && line.current[0] && line.current[1]) {
onlyFloorline.current.push(line.current as Types.Line);
lines.current.push(line.current as Types.Line); lines.current.push(line.current as Types.Line);
const data = arrayLineToObject(line.current as Types.Line); const data = arrayLineToObject(line.current as Types.Line);
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
//REST //REST
// setLine(organization, data.layer!, data.line!, data.type!); // setLine(organization, data.layer!, data.line!, data.type!);
@ -159,28 +147,124 @@ async function drawOnlyFloor(
//SOCKET //SOCKET
const input = { const input = {
organization: organization, organization,
layer: data.layer, layer: data.layer,
line: data.line, line: data.line,
type: data.type, type: data.type,
socketId: socket.id, socketId: socket.id,
projectId, projectId,
userId userId,
} };
socket.emit('v1:Line:create', input); socket.emit("v1:Line:create", input);
setNewLines([line.current]); setNewLines([newLines[0], newLines[1], line.current]);
addLineToScene(line.current[0][0], line.current[1][0], CONSTANTS.lineConfig.floorColor, line.current, floorPlanGroupLine); onlyFloorline.current.push(line.current as Types.Line);
const lastPoint = line.current[line.current.length - 1];
line.current = [lastPoint];
}
if (isSnapped.current) { ////////// Add this to stop the drawing mode after snapping //////////
removeReferenceLine(floorPlanGroup, ReferenceLineMesh, LineCreated, line);
onlyFloorlines.current.push(onlyFloorline.current); onlyFloorlines.current.push(onlyFloorline.current);
onlyFloorline.current = []; onlyFloorline.current = [];
addLineToScene(
line.current[0][0],
line.current[1][0],
CONSTANTS.lineConfig.floorColor,
line.current,
floorPlanGroupLine
);
removeReferenceLine(
floorPlanGroup,
ReferenceLineMesh,
LineCreated,
line
);
}
return;
} }
}
} }
}
if (intersects.length > 0 && intersectsLines.length === 0) {
////////// Clicked on an empty place or a point //////////
let intersectionPoint = intersects[0].point;
if (
isAngleSnapped.current &&
line.current.length > 0 &&
anglesnappedPoint.current
) {
intersectionPoint = anglesnappedPoint.current;
}
if (isSnapped.current && line.current.length > 0 && snappedPoint.current) {
intersectionPoint = snappedPoint.current;
}
if (ispreSnapped.current && snappedPoint.current) {
intersectionPoint = snappedPoint.current;
}
if (!isSnapped.current && !ispreSnapped.current) {
addPointToScene(
intersectionPoint,
CONSTANTS.pointConfig.floorOuterColor,
currentLayerPoint,
floorPlanGroupPoint,
dragPointControls,
isSnappedUUID,
CONSTANTS.lineConfig.floorName
);
} else {
ispreSnapped.current = false;
isSnapped.current = false;
}
(line.current as Types.Line).push([
new THREE.Vector3(intersectionPoint.x, 0.01, intersectionPoint.z),
isSnappedUUID.current!,
activeLayer,
CONSTANTS.lineConfig.floorName,
]);
if (line.current.length >= 2 && line.current[0] && line.current[1]) {
onlyFloorline.current.push(line.current as Types.Line);
lines.current.push(line.current as Types.Line);
const data = arrayLineToObject(line.current as Types.Line);
//REST
// setLine(organization, data.layer!, data.line!, data.type!);
//SOCKET
const input = {
organization,
layer: data.layer,
line: data.line,
type: data.type,
socketId: socket.id,
projectId,
userId,
};
socket.emit("v1:Line:create", input);
setNewLines([line.current]);
addLineToScene(
line.current[0][0],
line.current[1][0],
CONSTANTS.lineConfig.floorColor,
line.current,
floorPlanGroupLine
);
const lastPoint = line.current[line.current.length - 1];
line.current = [lastPoint];
}
if (isSnapped.current) {
////////// Add this to stop the drawing mode after snapping //////////
removeReferenceLine(floorPlanGroup, ReferenceLineMesh, LineCreated, line);
onlyFloorlines.current.push(onlyFloorline.current);
onlyFloorline.current = [];
}
}
} }
export default drawOnlyFloor; export default drawOnlyFloor;

View File

@ -1,93 +1,102 @@
import { toast } from 'react-toastify'; import { toast } from "react-toastify";
import RemoveConnectedLines from '../lines/removeConnectedLines'; import RemoveConnectedLines from "../lines/removeConnectedLines";
import * as Types from '../../../../types/world/worldTypes'; import * as Types from "../../../../types/world/worldTypes";
import { Socket } from 'socket.io-client'; import { Socket } from "socket.io-client";
import { getUserData } from "../../../../functions/getUserData";
// import { deleteLayer } from '../../../../services/factoryBuilder/lines/deleteLayerApi'; // import { deleteLayer } from '../../../../services/factoryBuilder/lines/deleteLayerApi';
async function DeleteLayer( async function DeleteLayer(
removedLayer: Types.Number, removedLayer: Types.Number,
lines: Types.RefLines, lines: Types.RefLines,
floorPlanGroupLine: Types.RefGroup, floorPlanGroupLine: Types.RefGroup,
floorPlanGroupPoint: Types.RefGroup, floorPlanGroupPoint: Types.RefGroup,
onlyFloorlines: Types.RefOnlyFloorLines, onlyFloorlines: Types.RefOnlyFloorLines,
floorGroup: Types.RefGroup, floorGroup: Types.RefGroup,
setDeletedLines: any, setDeletedLines: any,
setRemovedLayer: Types.setRemoveLayerSetState, setRemovedLayer: Types.setRemoveLayerSetState,
socket: Socket<any>, socket: Socket<any>,
projectId?:string projectId?: string
): Promise<void> { ): Promise<void> {
////////// Remove the Lines from the lines.current based on the removed layer and rearrange the layer number that are higher than the removed layer //////////
////////// Remove the Lines from the lines.current based on the removed layer and rearrange the layer number that are higher than the removed layer ////////// const removedLines: Types.Lines = lines.current.filter(
(line) => line[0][2] === removedLayer
);
const { userId, organization, email } = getUserData();
const removedLines: Types.Lines = lines.current.filter(line => line[0][2] === removedLayer); //REST
const email = localStorage.getItem('email') // await deleteLayer(organization, removedLayer);
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
//REST //SOCKET
// await deleteLayer(organization, removedLayer); const data = {
organization,
layer: removedLayer,
socketId: socket.id,
projectId,
userId,
};
//SOCKET socket.emit("v1:Line:delete:layer", data);
const data = { ////////// Remove Points and lines from the removed layer //////////
organization: organization,
layer: removedLayer, removedLines.forEach((line) => {
socketId: socket.id, line.forEach((removedPoint) => {
projectId, RemoveConnectedLines(
userId removedPoint[1],
floorPlanGroupLine,
floorPlanGroupPoint,
setDeletedLines,
lines
);
});
});
////////// Update the remaining lines layer values in the userData and in lines.current //////////
let remaining = lines.current.filter((line) => line[0][2] !== removedLayer);
let updatedLines: Types.Lines = [];
remaining.forEach((line) => {
let newLines: Types.Line = [...line];
if (newLines[0][2] > removedLayer) {
newLines[0][2] -= 1;
newLines[1][2] -= 1;
} }
socket.emit('v1:Line:delete:layer', data); const matchingLine = floorPlanGroupLine.current.children.find(
(l) =>
////////// Remove Points and lines from the removed layer ////////// l.userData.linePoints[0][1] === line[0][1] &&
l.userData.linePoints[1][1] === line[1][1]
removedLines.forEach((line) => {
line.forEach((removedPoint) => {
RemoveConnectedLines(removedPoint[1], floorPlanGroupLine, floorPlanGroupPoint, setDeletedLines, lines);
});
});
////////// Update the remaining lines layer values in the userData and in lines.current //////////
let remaining = lines.current.filter(line => line[0][2] !== removedLayer);
let updatedLines: Types.Lines = [];
remaining.forEach(line => {
let newLines: Types.Line = [...line];
if (newLines[0][2] > removedLayer) {
newLines[0][2] -= 1;
newLines[1][2] -= 1;
}
const matchingLine = floorPlanGroupLine.current.children.find(l => l.userData.linePoints[0][1] === line[0][1] && l.userData.linePoints[1][1] === line[1][1]);
if (matchingLine) {
const updatedUserData = matchingLine.userData;
updatedUserData.linePoints[0][2] = newLines[0][2];
updatedUserData.linePoints[1][2] = newLines[1][2];
}
updatedLines.push(newLines);
});
lines.current = updatedLines;
localStorage.setItem("Lines", JSON.stringify(lines.current));
////////// Also remove OnlyFloorLines and update it in localstorage //////////
onlyFloorlines.current = onlyFloorlines.current.filter((floor) => {
return floor[0][0][2] !== removedLayer;
});
const meshToRemove: any = floorGroup.current?.children.find((mesh) =>
mesh.name === `Only_Floor_Line_${removedLayer}`
); );
if (meshToRemove) { if (matchingLine) {
(<any>meshToRemove.material).dispose(); const updatedUserData = matchingLine.userData;
(<any>meshToRemove.geometry).dispose(); updatedUserData.linePoints[0][2] = newLines[0][2];
floorGroup.current?.remove(meshToRemove); updatedUserData.linePoints[1][2] = newLines[1][2];
} }
updatedLines.push(newLines);
});
echo.success("Layer Removed!"); lines.current = updatedLines;
setRemovedLayer(null); localStorage.setItem("Lines", JSON.stringify(lines.current));
////////// Also remove OnlyFloorLines and update it in localstorage //////////
onlyFloorlines.current = onlyFloorlines.current.filter((floor) => {
return floor[0][0][2] !== removedLayer;
});
const meshToRemove: any = floorGroup.current?.children.find(
(mesh) => mesh.name === `Only_Floor_Line_${removedLayer}`
);
if (meshToRemove) {
(<any>meshToRemove.material).dispose();
(<any>meshToRemove.geometry).dispose();
floorGroup.current?.remove(meshToRemove);
}
echo.success("Layer Removed!");
setRemovedLayer(null);
} }
export default DeleteLayer; export default DeleteLayer;

View File

@ -2,91 +2,89 @@ import { Socket } from "socket.io-client";
// import { deleteLineApi } from "../../../../services/factoryBuilder/lines/deleteLineApi"; // import { deleteLineApi } from "../../../../services/factoryBuilder/lines/deleteLineApi";
import * as Types from "../../../../types/world/worldTypes"; import * as Types from "../../../../types/world/worldTypes";
import { toast } from 'react-toastify'; import { toast } from "react-toastify";
import { getUserData } from "../../../../functions/getUserData";
function deleteLine( function deleteLine(
hoveredDeletableLine: Types.RefMesh, hoveredDeletableLine: Types.RefMesh,
onlyFloorlines: Types.RefOnlyFloorLines, onlyFloorlines: Types.RefOnlyFloorLines,
lines: Types.RefLines, lines: Types.RefLines,
floorPlanGroupLine: Types.RefGroup, floorPlanGroupLine: Types.RefGroup,
floorPlanGroupPoint: Types.RefGroup, floorPlanGroupPoint: Types.RefGroup,
setDeletedLines: any, setDeletedLines: any,
socket: Socket<any>, socket: Socket<any>,
projectId?: string projectId?: string
): void { ): void {
const { userId, organization, email } = getUserData();
////////// Deleting a line and the points if they are not connected to any other line //////////
////////// Deleting a line and the points if they are not connected to any other line ////////// if (!hoveredDeletableLine.current) {
return;
}
if (!hoveredDeletableLine.current) { const linePoints = hoveredDeletableLine.current.userData.linePoints;
return; const connectedpoints = [linePoints[0][1], linePoints[1][1]];
}
const linePoints = hoveredDeletableLine.current.userData.linePoints; //REST
const connectedpoints = [linePoints[0][1], linePoints[1][1]];
const email = localStorage.getItem('email') // deleteLineApi(
const organization = (email!.split("@")[1]).split(".")[0]; // organization,
const userId = localStorage.getItem("userId"); // [
// { "uuid": linePoints[0][1] },
// { "uuid": linePoints[1][1] }
// ]
// )
//REST //SOCKET
// deleteLineApi( const data = {
// organization, organization,
// [ line: [{ uuid: linePoints[0][1] }, { uuid: linePoints[1][1] }],
// { "uuid": linePoints[0][1] }, socketId: socket.id,
// { "uuid": linePoints[1][1] } projectId,
// ] userId,
// ) };
//SOCKET socket.emit("v1:Line:delete", data);
const data = { onlyFloorlines.current = onlyFloorlines.current
organization: organization, .map((floorline) =>
line: [ floorline.filter(
{ "uuid": linePoints[0][1] }, (line) =>
{ "uuid": linePoints[1][1] } line[0][1] !== connectedpoints[0] && line[1][1] !== connectedpoints[1]
], )
socketId: socket.id, )
projectId, .filter((floorline) => floorline.length > 0);
userId
}
socket.emit('v1:Line:delete', data); lines.current = lines.current.filter((item) => item !== linePoints);
(<any>hoveredDeletableLine.current.material).dispose();
(<any>hoveredDeletableLine.current.geometry).dispose();
floorPlanGroupLine.current.remove(hoveredDeletableLine.current);
setDeletedLines([linePoints]);
connectedpoints.forEach((pointUUID) => {
onlyFloorlines.current = onlyFloorlines.current.map(floorline => let isConnected = false;
floorline.filter(line => line[0][1] !== connectedpoints[0] && line[1][1] !== connectedpoints[1]) floorPlanGroupLine.current.children.forEach((line) => {
).filter(floorline => floorline.length > 0); const linePoints = line.userData.linePoints;
const uuid1 = linePoints[0][1];
lines.current = lines.current.filter(item => item !== linePoints); const uuid2 = linePoints[1][1];
(<any>hoveredDeletableLine.current.material).dispose(); if (uuid1 === pointUUID || uuid2 === pointUUID) {
(<any>hoveredDeletableLine.current.geometry).dispose(); isConnected = true;
floorPlanGroupLine.current.remove(hoveredDeletableLine.current); }
setDeletedLines([linePoints]);
connectedpoints.forEach((pointUUID) => {
let isConnected = false;
floorPlanGroupLine.current.children.forEach((line) => {
const linePoints = line.userData.linePoints;
const uuid1 = linePoints[0][1];
const uuid2 = linePoints[1][1];
if (uuid1 === pointUUID || uuid2 === pointUUID) {
isConnected = true;
}
});
if (!isConnected) {
floorPlanGroupPoint.current.children.forEach((point: any) => {
if (point.uuid === pointUUID) {
(<any>point.material).dispose();
(<any>point.geometry).dispose();
floorPlanGroupPoint.current.remove(point);
}
});
}
}); });
echo.success("Line Removed!"); if (!isConnected) {
floorPlanGroupPoint.current.children.forEach((point: any) => {
if (point.uuid === pointUUID) {
(<any>point.material).dispose();
(<any>point.geometry).dispose();
floorPlanGroupPoint.current.remove(point);
}
});
}
});
echo.success("Line Removed!");
} }
export default deleteLine; export default deleteLine;

View File

@ -15,6 +15,7 @@ import * as Types from "../../../../../types/world/worldTypes";
import getRoomsFromLines from "../getRoomsFromLines"; import getRoomsFromLines from "../getRoomsFromLines";
import * as turf from '@turf/turf'; import * as turf from '@turf/turf';
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../../functions/getUserData";
const DistanceText = () => { const DistanceText = () => {
const [lines, setLines] = useState< const [lines, setLines] = useState<
@ -32,7 +33,7 @@ const DistanceText = () => {
const [linesState, setLinesState] = useState<Types.Lines>([]); const [linesState, setLinesState] = useState<Types.Lines>([]);
const { roomsState, setRoomsState } = useRoomsState(); const { roomsState, setRoomsState } = useRoomsState();
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
if (linesState.length === 0) return; if (linesState.length === 0) return;
@ -93,11 +94,9 @@ const DistanceText = () => {
useEffect(() => { useEffect(() => {
const email = localStorage.getItem("email");
if (!email) return; if (!email) return;
const organization = email.split("@")[1].split(".")[0];
getLines(organization,projectId).then((data) => { getLines(organization, projectId).then((data) => {
data = objectLinesToArray(data); data = objectLinesToArray(data);
setLinesState(data); setLinesState(data);

View File

@ -1,146 +1,127 @@
import * as THREE from 'three'; import * as THREE from "three";
import * as CONSTANTS from '../../../../types/world/worldConstants'; import * as CONSTANTS from "../../../../types/world/worldConstants";
import addPointToScene from '../points/addPointToScene'; import addPointToScene from "../points/addPointToScene";
import addLineToScene from './addLineToScene'; import addLineToScene from "./addLineToScene";
import splitLine from './splitLine'; import splitLine from "./splitLine";
import removeReferenceLine from './removeReferenceLine'; import removeReferenceLine from "./removeReferenceLine";
import getClosestIntersection from './getClosestIntersection'; import getClosestIntersection from "./getClosestIntersection";
import * as Types from "../../../../types/world/worldTypes"; import * as Types from "../../../../types/world/worldTypes";
import arrayLineToObject from './lineConvertions/arrayLineToObject'; import arrayLineToObject from "./lineConvertions/arrayLineToObject";
// import { setLine } from '../../../../services/factoryBuilder/lines/setLineApi'; // import { setLine } from '../../../../services/factoryBuilder/lines/setLineApi';
import { Socket } from 'socket.io-client'; import { Socket } from "socket.io-client";
import { getUserData } from "../../../../functions/getUserData";
async function drawWall( async function drawWall(
raycaster: THREE.Raycaster, raycaster: THREE.Raycaster,
plane: Types.RefMesh, plane: Types.RefMesh,
floorPlanGroupPoint: Types.RefGroup, floorPlanGroupPoint: Types.RefGroup,
snappedPoint: Types.RefVector3, snappedPoint: Types.RefVector3,
isSnapped: Types.RefBoolean, isSnapped: Types.RefBoolean,
isSnappedUUID: Types.RefString, isSnappedUUID: Types.RefString,
line: Types.RefLine, line: Types.RefLine,
ispreSnapped: Types.RefBoolean, ispreSnapped: Types.RefBoolean,
anglesnappedPoint: Types.RefVector3, anglesnappedPoint: Types.RefVector3,
isAngleSnapped: Types.RefBoolean, isAngleSnapped: Types.RefBoolean,
lines: Types.RefLines, lines: Types.RefLines,
floorPlanGroupLine: Types.RefGroup, floorPlanGroupLine: Types.RefGroup,
floorPlanGroup: Types.RefGroup, floorPlanGroup: Types.RefGroup,
ReferenceLineMesh: Types.RefMesh, ReferenceLineMesh: Types.RefMesh,
LineCreated: Types.RefBoolean, LineCreated: Types.RefBoolean,
currentLayerPoint: Types.RefMeshArray, currentLayerPoint: Types.RefMeshArray,
dragPointControls: Types.RefDragControl, dragPointControls: Types.RefDragControl,
setNewLines: any, setNewLines: any,
setDeletedLines: any, setDeletedLines: any,
activeLayer: Types.Number, activeLayer: Types.Number,
socket: Socket<any>, socket: Socket<any>,
projectId?: string projectId?: string
): Promise<void> { ): Promise<void> {
const { userId, organization, email } = getUserData();
////////// Creating lines Based on the positions clicked //////////
////////// Creating lines Based on the positions clicked ////////// ////////// Allows the user lines that represents walls and roof, floor if forms a polygon //////////
////////// Allows the user lines that represents walls and roof, floor if forms a polygon ////////// if (!plane.current) return;
let intersects = raycaster.intersectObject(plane.current, true);
let intersectsLines = raycaster.intersectObjects(
floorPlanGroupLine.current.children,
true
);
let intersectsPoint = raycaster.intersectObjects(
floorPlanGroupPoint.current.children,
true
);
if (!plane.current) return const VisibleintersectsPoint = intersectsPoint.find(
let intersects = raycaster.intersectObject(plane.current, true); (intersect) => intersect.object.visible
);
const visibleIntersect = intersectsLines.find(
(intersect) =>
intersect.object.visible &&
intersect.object.name !== CONSTANTS.lineConfig.referenceName &&
intersect.object.userData.linePoints[0][3] ===
CONSTANTS.lineConfig.wallName
);
let intersectsLines = raycaster.intersectObjects(floorPlanGroupLine.current.children, true); if (
let intersectsPoint = raycaster.intersectObjects(floorPlanGroupPoint.current.children, true); (intersectsPoint.length === 0 || VisibleintersectsPoint === undefined) &&
intersectsLines.length > 0 &&
!isSnapped.current &&
!ispreSnapped.current
) {
////////// Clicked on a preexisting Line //////////
const VisibleintersectsPoint = intersectsPoint.find(intersect => intersect.object.visible); if (visibleIntersect && intersects) {
const visibleIntersect = intersectsLines.find(intersect => intersect.object.visible && intersect.object.name !== CONSTANTS.lineConfig.referenceName && intersect.object.userData.linePoints[0][3] === CONSTANTS.lineConfig.wallName); let IntersectsPoint = new THREE.Vector3(
intersects[0].point.x,
0.01,
intersects[0].point.z
);
if ((intersectsPoint.length === 0 || VisibleintersectsPoint === undefined) && intersectsLines.length > 0 && !isSnapped.current && !ispreSnapped.current) { if (isAngleSnapped.current && anglesnappedPoint.current) {
IntersectsPoint = anglesnappedPoint.current;
}
if (visibleIntersect.object instanceof THREE.Mesh) {
const ThroughPoint =
visibleIntersect.object.geometry.parameters.path.getPoints(
CONSTANTS.lineConfig.lineIntersectionPoints
);
let intersectionPoint = getClosestIntersection(
ThroughPoint,
IntersectsPoint
);
////////// Clicked on a preexisting Line ////////// if (intersectionPoint) {
const newLines = splitLine(
visibleIntersect,
intersectionPoint,
currentLayerPoint,
floorPlanGroupPoint,
dragPointControls,
isSnappedUUID,
lines,
setDeletedLines,
floorPlanGroupLine,
socket,
CONSTANTS.pointConfig.wallOuterColor,
CONSTANTS.lineConfig.wallColor,
CONSTANTS.lineConfig.wallName,
projectId
);
setNewLines([newLines[0], newLines[1]]);
if (visibleIntersect && intersects) { (line.current as Types.Line).push([
let IntersectsPoint = new THREE.Vector3(intersects[0].point.x, 0.01, intersects[0].point.z); new THREE.Vector3(intersectionPoint.x, 0.01, intersectionPoint.z),
isSnappedUUID.current!,
activeLayer,
CONSTANTS.lineConfig.wallName,
]);
if (isAngleSnapped.current && anglesnappedPoint.current) { if (line.current.length >= 2 && line.current[0] && line.current[1]) {
IntersectsPoint = anglesnappedPoint.current;
}
if (visibleIntersect.object instanceof THREE.Mesh) {
const ThroughPoint = (visibleIntersect.object.geometry.parameters.path).getPoints(CONSTANTS.lineConfig.lineIntersectionPoints);
let intersectionPoint = getClosestIntersection(ThroughPoint, IntersectsPoint);
if (intersectionPoint) {
const newLines = splitLine(visibleIntersect, intersectionPoint, currentLayerPoint, floorPlanGroupPoint, dragPointControls, isSnappedUUID, lines, setDeletedLines, floorPlanGroupLine, socket, CONSTANTS.pointConfig.wallOuterColor, CONSTANTS.lineConfig.wallColor, CONSTANTS.lineConfig.wallName,projectId);
setNewLines([newLines[0], newLines[1]]);
(line.current as Types.Line).push([new THREE.Vector3(intersectionPoint.x, 0.01, intersectionPoint.z), isSnappedUUID.current!, activeLayer, CONSTANTS.lineConfig.wallName,]);
if (line.current.length >= 2 && line.current[0] && line.current[1]) {
const data = arrayLineToObject(line.current as Types.Line);
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
//REST
// setLine(organization, data.layer!, data.line!, data.type!);
//SOCKET
const input = {
organization: organization,
layer: data.layer,
line: data.line,
type: data.type,
socketId: socket.id,
projectId,
userId
}
socket.emit('v1:Line:create', input);
setNewLines([newLines[0], newLines[1], line.current]);
lines.current.push(line.current as Types.Line);
addLineToScene(line.current[0][0], line.current[1][0], CONSTANTS.lineConfig.wallColor, line.current, floorPlanGroupLine);
let lastPoint = line.current[line.current.length - 1];
line.current = [lastPoint];
}
return;
}
}
}
}
if (intersects && intersects.length > 0) {
////////// Clicked on a emply place or a point //////////
let intersectionPoint = intersects[0].point;
if (isAngleSnapped.current && line.current.length > 0 && anglesnappedPoint.current) {
intersectionPoint = anglesnappedPoint.current;
}
if (isSnapped.current && line.current.length > 0 && snappedPoint.current) {
intersectionPoint = snappedPoint.current;
}
if (ispreSnapped.current && snappedPoint.current) {
intersectionPoint = snappedPoint.current;
}
if (!isSnapped.current && !ispreSnapped.current) {
addPointToScene(intersectionPoint, CONSTANTS.pointConfig.wallOuterColor, currentLayerPoint, floorPlanGroupPoint, dragPointControls, isSnappedUUID, CONSTANTS.lineConfig.wallName);
} else {
ispreSnapped.current = false;
isSnapped.current = false;
}
(line.current as Types.Line).push([new THREE.Vector3(intersectionPoint.x, 0.01, intersectionPoint.z), isSnappedUUID.current!, activeLayer, CONSTANTS.lineConfig.wallName,]);
if (line.current.length >= 2 && line.current[0] && line.current[1]) {
const data = arrayLineToObject(line.current as Types.Line); const data = arrayLineToObject(line.current as Types.Line);
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
//REST //REST
// setLine(organization, data.layer!, data.line!, data.type!); // setLine(organization, data.layer!, data.line!, data.type!);
@ -148,27 +129,113 @@ async function drawWall(
//SOCKET //SOCKET
const input = { const input = {
organization: organization, organization,
layer: data.layer, layer: data.layer,
line: data.line, line: data.line,
type: data.type, type: data.type,
socketId: socket.id, socketId: socket.id,
projectId, projectId,
userId userId,
} };
socket.emit('v1:Line:create', input); socket.emit("v1:Line:create", input);
setNewLines([line.current]) setNewLines([newLines[0], newLines[1], line.current]);
lines.current.push(line.current as Types.Line); lines.current.push(line.current as Types.Line);
addLineToScene(line.current[0][0], line.current[1][0], CONSTANTS.lineConfig.wallColor, line.current, floorPlanGroupLine); addLineToScene(
line.current[0][0],
line.current[1][0],
CONSTANTS.lineConfig.wallColor,
line.current,
floorPlanGroupLine
);
let lastPoint = line.current[line.current.length - 1]; let lastPoint = line.current[line.current.length - 1];
line.current = [lastPoint]; line.current = [lastPoint];
}
return;
} }
if (isSnapped.current) { }
removeReferenceLine(floorPlanGroup, ReferenceLineMesh, LineCreated, line);
}
} }
}
if (intersects && intersects.length > 0) {
////////// Clicked on a emply place or a point //////////
let intersectionPoint = intersects[0].point;
if (
isAngleSnapped.current &&
line.current.length > 0 &&
anglesnappedPoint.current
) {
intersectionPoint = anglesnappedPoint.current;
}
if (isSnapped.current && line.current.length > 0 && snappedPoint.current) {
intersectionPoint = snappedPoint.current;
}
if (ispreSnapped.current && snappedPoint.current) {
intersectionPoint = snappedPoint.current;
}
if (!isSnapped.current && !ispreSnapped.current) {
addPointToScene(
intersectionPoint,
CONSTANTS.pointConfig.wallOuterColor,
currentLayerPoint,
floorPlanGroupPoint,
dragPointControls,
isSnappedUUID,
CONSTANTS.lineConfig.wallName
);
} else {
ispreSnapped.current = false;
isSnapped.current = false;
}
(line.current as Types.Line).push([
new THREE.Vector3(intersectionPoint.x, 0.01, intersectionPoint.z),
isSnappedUUID.current!,
activeLayer,
CONSTANTS.lineConfig.wallName,
]);
if (line.current.length >= 2 && line.current[0] && line.current[1]) {
const data = arrayLineToObject(line.current as Types.Line);
//REST
// setLine(organization, data.layer!, data.line!, data.type!);
//SOCKET
const input = {
organization,
layer: data.layer,
line: data.line,
type: data.type,
socketId: socket.id,
projectId,
userId,
};
socket.emit("v1:Line:create", input);
setNewLines([line.current]);
lines.current.push(line.current as Types.Line);
addLineToScene(
line.current[0][0],
line.current[1][0],
CONSTANTS.lineConfig.wallColor,
line.current,
floorPlanGroupLine
);
let lastPoint = line.current[line.current.length - 1];
line.current = [lastPoint];
}
if (isSnapped.current) {
removeReferenceLine(floorPlanGroup, ReferenceLineMesh, LineCreated, line);
}
}
} }
export default drawWall; export default drawWall;

View File

@ -1,132 +1,147 @@
import * as THREE from 'three'; import * as THREE from "three";
import addLineToScene from './addLineToScene'; import addLineToScene from "./addLineToScene";
import addPointToScene from '../points/addPointToScene'; import addPointToScene from "../points/addPointToScene";
import * as Types from "../../../../types/world/worldTypes"; import * as Types from "../../../../types/world/worldTypes";
import arrayLineToObject from '../lines/lineConvertions/arrayLineToObject'; import arrayLineToObject from "../lines/lineConvertions/arrayLineToObject";
import { Socket } from 'socket.io-client'; import { Socket } from "socket.io-client";
import { getUserData } from "../../../../functions/getUserData";
// import { deleteLineApi } from '../../../../services/factoryBuilder/lines/deleteLineApi'; // import { deleteLineApi } from '../../../../services/factoryBuilder/lines/deleteLineApi';
// import { setLine } from '../../../../services/factoryBuilder/lines/setLineApi'; // import { setLine } from '../../../../services/factoryBuilder/lines/setLineApi';
function splitLine( function splitLine(
visibleIntersect: Types.IntersectionEvent, visibleIntersect: Types.IntersectionEvent,
intersectionPoint: Types.Vector3, intersectionPoint: Types.Vector3,
currentLayerPoint: Types.RefMeshArray, currentLayerPoint: Types.RefMeshArray,
floorPlanGroupPoint: Types.RefGroup, floorPlanGroupPoint: Types.RefGroup,
dragPointControls: Types.RefDragControl, dragPointControls: Types.RefDragControl,
isSnappedUUID: Types.RefString, isSnappedUUID: Types.RefString,
lines: Types.RefLines, lines: Types.RefLines,
setDeletedLines: any, setDeletedLines: any,
floorPlanGroupLine: { current: THREE.Group }, floorPlanGroupLine: { current: THREE.Group },
socket: Socket<any>, socket: Socket<any>,
pointColor: Types.String, pointColor: Types.String,
lineColor: Types.String, lineColor: Types.String,
lineType: Types.String, lineType: Types.String,
projectId?: string projectId?: string
): [Types.Line, Types.Line] { ): [Types.Line, Types.Line] {
////////// Removing the clicked line and splitting it with the clicked position adding a new point and two new lines //////////
////////// Removing the clicked line and splitting it with the clicked position adding a new point and two new lines ////////// const { userId, organization, email } = getUserData();
(visibleIntersect.object as any).material.dispose();
(visibleIntersect.object as any).geometry.dispose();
floorPlanGroupLine.current.remove(visibleIntersect.object);
setDeletedLines([visibleIntersect.object.userData.linePoints]);
//REST
((visibleIntersect.object as any).material).dispose(); // deleteLineApi(
((visibleIntersect.object as any).geometry).dispose(); // organization,
floorPlanGroupLine.current.remove(visibleIntersect.object); // [
setDeletedLines([visibleIntersect.object.userData.linePoints]); // { "uuid": visibleIntersect.object.userData.linePoints[0][1] },
// { "uuid": visibleIntersect.object.userData.linePoints[1][1] }
// ]
// )
const email = localStorage.getItem('email') //SOCKET
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
//REST const data = {
organization,
line: [
{ uuid: visibleIntersect.object.userData.linePoints[0][1] },
{ uuid: visibleIntersect.object.userData.linePoints[1][1] },
],
socketId: socket.id,
projectId,
userId,
};
// deleteLineApi( socket.emit("v1:Line:delete", data);
// organization,
// [
// { "uuid": visibleIntersect.object.userData.linePoints[0][1] },
// { "uuid": visibleIntersect.object.userData.linePoints[1][1] }
// ]
// )
//SOCKET const point = addPointToScene(
intersectionPoint,
pointColor,
currentLayerPoint,
floorPlanGroupPoint,
dragPointControls,
isSnappedUUID,
lineType
);
const oldLinePoints = visibleIntersect.object.userData.linePoints;
lines.current = lines.current.filter((item) => item !== oldLinePoints);
const data = { const clickedPoint: Types.Point = [
organization: organization, new THREE.Vector3(intersectionPoint.x, 0.01, intersectionPoint.z),
line: [ point.uuid,
{ "uuid": visibleIntersect.object.userData.linePoints[0][1] }, oldLinePoints[0][2],
{ "uuid": visibleIntersect.object.userData.linePoints[1][1] } lineType,
], ];
socketId: socket.id,
projectId,
userId
}
socket.emit('v1:Line:delete', data); const start = oldLinePoints[0];
const end = oldLinePoints[1];
const point = addPointToScene(intersectionPoint, pointColor, currentLayerPoint, floorPlanGroupPoint, dragPointControls, isSnappedUUID, lineType); const newLine1: Types.Line = [start, clickedPoint];
const newLine2: Types.Line = [clickedPoint, end];
const oldLinePoints = visibleIntersect.object.userData.linePoints; const line1 = arrayLineToObject(newLine1);
lines.current = lines.current.filter(item => item !== oldLinePoints); const line2 = arrayLineToObject(newLine2);
const clickedPoint: Types.Point = [ //REST
new THREE.Vector3(intersectionPoint.x, 0.01, intersectionPoint.z),
point.uuid,
oldLinePoints[0][2],
lineType
];
const start = oldLinePoints[0]; // setLine(organization, line1.layer!, line1.line!, line1.type!);
const end = oldLinePoints[1];
const newLine1: Types.Line = [start, clickedPoint]; //SOCKET
const newLine2: Types.Line = [clickedPoint, end];
const line1 = arrayLineToObject(newLine1); const input1 = {
const line2 = arrayLineToObject(newLine2); organization,
layer: line1.layer,
line: line1.line,
type: line1.type,
socketId: socket.id,
projectId,
userId,
};
//REST socket.emit("v1:Line:create", input1);
// setLine(organization, line1.layer!, line1.line!, line1.type!); //REST
//SOCKET // setLine(organization, line2.layer!, line2.line!, line2.type!);
const input1 = { //SOCKET
organization: organization,
layer: line1.layer,
line: line1.line,
type: line1.type,
socketId: socket.id,
projectId,
userId
}
socket.emit('v1:Line:create', input1); const input2 = {
organization,
layer: line2.layer,
line: line2.line,
type: line2.type,
socketId: socket.id,
projectId,
userId,
};
//REST socket.emit("v1:Line:create", input2);
// setLine(organization, line2.layer!, line2.line!, line2.type!); lines.current.push(newLine1, newLine2);
//SOCKET addLineToScene(
newLine1[0][0],
newLine1[1][0],
lineColor,
newLine1,
floorPlanGroupLine
);
addLineToScene(
newLine2[0][0],
newLine2[1][0],
lineColor,
newLine2,
floorPlanGroupLine
);
const input2 = { return [newLine1, newLine2];
organization: organization,
layer: line2.layer,
line: line2.line,
type: line2.type,
socketId: socket.id,
projectId,
userId
}
socket.emit('v1:Line:create', input2);
lines.current.push(newLine1, newLine2);
addLineToScene(newLine1[0][0], newLine1[1][0], lineColor, newLine1, floorPlanGroupLine);
addLineToScene(newLine2[0][0], newLine2[1][0], lineColor, newLine2, floorPlanGroupLine);
return [newLine1, newLine2];
} }
export default splitLine; export default splitLine;

View File

@ -1,62 +1,70 @@
import * as Types from "../../../../types/world/worldTypes"; import * as Types from "../../../../types/world/worldTypes";
import { toast } from 'react-toastify'; import { toast } from "react-toastify";
import RemoveConnectedLines from "../lines/removeConnectedLines"; import RemoveConnectedLines from "../lines/removeConnectedLines";
// import { deletePointApi } from "../../../../services/factoryBuilder/lines/deletePointApi"; // import { deletePointApi } from "../../../../services/factoryBuilder/lines/deletePointApi";
import { Socket } from "socket.io-client"; import { Socket } from "socket.io-client";
import { getUserData } from "../../../../functions/getUserData";
function deletePoint( function deletePoint(
hoveredDeletablePoint: Types.RefMesh, hoveredDeletablePoint: Types.RefMesh,
onlyFloorlines: Types.RefOnlyFloorLines, onlyFloorlines: Types.RefOnlyFloorLines,
floorPlanGroupPoint: Types.RefGroup, floorPlanGroupPoint: Types.RefGroup,
floorPlanGroupLine: Types.RefGroup, floorPlanGroupLine: Types.RefGroup,
lines: Types.RefLines, lines: Types.RefLines,
setDeletedLines: any, setDeletedLines: any,
socket: Socket<any>, socket: Socket<any>,
projectId?:string projectId?: string
): void { ): void {
////////// Deleting a Point and the lines that are connected to it ////////// ////////// Deleting a Point and the lines that are connected to it //////////
if (!hoveredDeletablePoint.current) { if (!hoveredDeletablePoint.current) {
return; return;
} }
const { userId, organization, email } = getUserData();
(<any>hoveredDeletablePoint.current.material).dispose();
(<any>hoveredDeletablePoint.current.geometry).dispose();
floorPlanGroupPoint.current.remove(hoveredDeletablePoint.current);
const DeletedPointUUID = hoveredDeletablePoint.current.uuid;
(<any>hoveredDeletablePoint.current.material).dispose(); //REST
(<any>hoveredDeletablePoint.current.geometry).dispose();
floorPlanGroupPoint.current.remove(hoveredDeletablePoint.current);
const DeletedPointUUID = hoveredDeletablePoint.current.uuid;
const email = localStorage.getItem('email') // deletePointApi(organization, DeletedPointUUID);
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
//REST //SOCKET
// deletePointApi(organization, DeletedPointUUID); const data = {
organization,
uuid: DeletedPointUUID,
socketId: socket.id,
projectId,
userId,
};
//SOCKET // console.log('data: ', data);
socket.emit("v1:Line:delete:point", data);
const data = { ////////// Update onlyFloorlines.current to remove references to the deleted point //////////
organization: organization,
uuid: DeletedPointUUID,
socketId: socket.id,
projectId,
userId
}
// console.log('data: ', data); onlyFloorlines.current = onlyFloorlines.current
socket.emit('v1:Line:delete:point', data); .map((floorline) =>
floorline.filter(
(line) =>
line[0][1] !== DeletedPointUUID && line[1][1] !== DeletedPointUUID
)
)
.filter((floorline) => floorline.length > 0);
////////// Update onlyFloorlines.current to remove references to the deleted point ////////// RemoveConnectedLines(
DeletedPointUUID,
floorPlanGroupLine,
floorPlanGroupPoint,
setDeletedLines,
lines
);
onlyFloorlines.current = onlyFloorlines.current.map(floorline => echo.success("Point Removed!");
floorline.filter(line => line[0][1] !== DeletedPointUUID && line[1][1] !== DeletedPointUUID)
).filter(floorline => floorline.length > 0);
RemoveConnectedLines(DeletedPointUUID, floorPlanGroupLine, floorPlanGroupPoint, setDeletedLines, lines);
echo.success("Point Removed!");
} }
export default deletePoint; export default deletePoint;

View File

@ -1,142 +1,161 @@
import { GLTF, GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'; import { GLTF, GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader";
import { toast } from 'react-toastify'; import { toast } from "react-toastify";
import * as THREE from 'three'; import * as THREE from "three";
import * as Types from "../../../../types/world/worldTypes"; import * as Types from "../../../../types/world/worldTypes";
import * as CONSTANTS from '../../../../types/world/worldConstants'; import * as CONSTANTS from "../../../../types/world/worldConstants";
import { Socket } from 'socket.io-client'; import { Socket } from "socket.io-client";
import { retrieveGLTF, storeGLTF } from '../../../../utils/indexDB/idbUtils'; import { retrieveGLTF, storeGLTF } from "../../../../utils/indexDB/idbUtils";
import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader'; import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { getUserData } from "../../../../functions/getUserData";
async function AddWallItems( async function AddWallItems(
selected: any, selected: any,
raycaster: THREE.Raycaster, raycaster: THREE.Raycaster,
CSGGroup: Types.RefMesh, CSGGroup: Types.RefMesh,
setWallItems: Types.setWallItemSetState, setWallItems: Types.setWallItemSetState,
socket: Socket<any>, socket: Socket<any>,
projectId?: string projectId?: string
): Promise<void> { ): Promise<void> {
let intersects = raycaster?.intersectObject(CSGGroup.current!, true); const { userId, organization, email } = getUserData();
const wallRaycastIntersection = intersects?.find((child) => child.object.name.includes("WallRaycastReference")); let intersects = raycaster?.intersectObject(CSGGroup.current!, true);
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_MARKETPLACE_URL}`; const wallRaycastIntersection = intersects?.find((child) =>
child.object.name.includes("WallRaycastReference")
);
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_MARKETPLACE_URL}`;
if (!wallRaycastIntersection) return; if (!wallRaycastIntersection) return;
const intersectionPoint = wallRaycastIntersection; const intersectionPoint = wallRaycastIntersection;
const loader = new GLTFLoader(); const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader(); const dracoLoader = new DRACOLoader();
dracoLoader.setDecoderPath('https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/'); dracoLoader.setDecoderPath(
loader.setDRACOLoader(dracoLoader); "https://cdn.jsdelivr.net/npm/three@0.160.0/examples/jsm/libs/draco/gltf/"
);
loader.setDRACOLoader(dracoLoader);
// Check THREE.js cache first // Check THREE.js cache first
const cachedModel = THREE.Cache.get(selected.id); const cachedModel = THREE.Cache.get(selected.id);
if (cachedModel) { if (cachedModel) {
handleModelLoad(cachedModel); handleModelLoad(cachedModel);
return; return;
}
// Check IndexedDB cache
const cachedModelBlob = await retrieveGLTF(selected.id);
if (cachedModelBlob) {
const blobUrl = URL.createObjectURL(cachedModelBlob);
loader.load(blobUrl, (gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.remove(blobUrl);
THREE.Cache.add(selected.id, gltf);
handleModelLoad(gltf);
});
return;
}
// Load from backend if not in any cache
loader.load(
`${url_Backend_dwinzo}/api/v2/AssetFile/${selected.id}`,
async (gltf) => {
try {
const modelBlob = await fetch(
`${url_Backend_dwinzo}/api/v2/AssetFile/${selected.id}`
).then((res) => res.blob());
await storeGLTF(selected.id, modelBlob);
THREE.Cache.add(selected.id, gltf);
await handleModelLoad(gltf);
} catch (error) {
console.error("Failed to cache model:", error);
handleModelLoad(gltf);
}
} }
);
// Check IndexedDB cache async function handleModelLoad(gltf: GLTF) {
const cachedModelBlob = await retrieveGLTF(selected.id); const model = gltf.scene.clone();
if (cachedModelBlob) { model.userData = { wall: intersectionPoint.object.parent };
const blobUrl = URL.createObjectURL(cachedModelBlob);
loader.load(blobUrl, (gltf) => {
URL.revokeObjectURL(blobUrl);
THREE.Cache.remove(blobUrl);
THREE.Cache.add(selected.id, gltf);
handleModelLoad(gltf);
});
return;
}
// Load from backend if not in any cache model.children[0].children.forEach((child) => {
loader.load(`${url_Backend_dwinzo}/api/v2/AssetFile/${selected.id}`, async (gltf) => { if (child.name !== "CSG_REF") {
try { child.castShadow = true;
const modelBlob = await fetch(`${url_Backend_dwinzo}/api/v2/AssetFile/${selected.id}`).then((res) => res.blob()); child.receiveShadow = true;
await storeGLTF(selected.id, modelBlob); }
THREE.Cache.add(selected.id, gltf);
await handleModelLoad(gltf);
} catch (error) {
console.error('Failed to cache model:', error);
handleModelLoad(gltf);
}
}); });
async function handleModelLoad(gltf: GLTF) { const boundingBox = new THREE.Box3().setFromObject(model);
const model = gltf.scene.clone(); const size = new THREE.Vector3();
model.userData = { wall: intersectionPoint.object.parent }; boundingBox.getSize(size);
model.children[0].children.forEach((child) => { const csgscale = [size.x, size.y, size.z] as [number, number, number];
if (child.name !== "CSG_REF") {
child.castShadow = true;
child.receiveShadow = true;
}
});
const boundingBox = new THREE.Box3().setFromObject(model); const center = new THREE.Vector3();
const size = new THREE.Vector3(); boundingBox.getCenter(center);
boundingBox.getSize(size); const csgposition = [center.x, center.y, center.z] as [
number,
number,
number
];
const csgscale = [size.x, size.y, size.z] as [number, number, number]; let positionY =
selected.subCategory === "fixed-move" ? 0 : intersectionPoint.point.y;
const center = new THREE.Vector3(); if (positionY === 0) {
boundingBox.getCenter(center); positionY =
const csgposition = [center.x, center.y, center.z] as [number, number, number]; Math.floor(intersectionPoint.point.y / CONSTANTS.wallConfig.height) *
CONSTANTS.wallConfig.height;
let positionY = selected.subCategory === 'fixed-move' ? 0 : intersectionPoint.point.y;
if (positionY === 0) {
positionY = Math.floor(intersectionPoint.point.y / CONSTANTS.wallConfig.height) * CONSTANTS.wallConfig.height;
}
const newWallItem = {
type: selected.subCategory,
model: model,
modelName: selected.name,
assetId: selected.id,
scale: [1, 1, 1] as [number, number, number],
csgscale: csgscale,
csgposition: csgposition,
position: [intersectionPoint.point.x, positionY, intersectionPoint.point.z] as [number, number, number],
quaternion: intersectionPoint.object.quaternion.clone() as Types.QuaternionType
};
const email = localStorage.getItem('email');
const organization = email ? (email.split("@")[1]).split(".")[0] : 'default';
const userId = localStorage.getItem("userId");
const data = {
organization: organization,
modelUuid: model.uuid,
modelName: newWallItem.modelName,
assetId: selected.id,
type: selected.subCategory,
csgposition: newWallItem.csgposition,
csgscale: newWallItem.csgscale,
position: newWallItem.position,
quaternion: newWallItem.quaternion,
scale: newWallItem.scale,
socketId: socket.id,
projectId,
userId
};
socket.emit('v1:wallItems:set', data);
setWallItems((prevItems) => {
const updatedItems = [...prevItems, newWallItem];
const WallItemsForStorage = updatedItems.map(item => {
const { model, ...rest } = item;
return {
...rest,
modelUuid: model?.uuid,
};
});
localStorage.setItem("WallItems", JSON.stringify(WallItemsForStorage));
echo.success("Model Added!");
return updatedItems;
});
} }
const newWallItem = {
type: selected.subCategory,
model: model,
modelName: selected.name,
assetId: selected.id,
scale: [1, 1, 1] as [number, number, number],
csgscale: csgscale,
csgposition: csgposition,
position: [
intersectionPoint.point.x,
positionY,
intersectionPoint.point.z,
] as [number, number, number],
quaternion:
intersectionPoint.object.quaternion.clone() as Types.QuaternionType,
};
const data = {
organization,
modelUuid: model.uuid,
modelName: newWallItem.modelName,
assetId: selected.id,
type: selected.subCategory,
csgposition: newWallItem.csgposition,
csgscale: newWallItem.csgscale,
position: newWallItem.position,
quaternion: newWallItem.quaternion,
scale: newWallItem.scale,
socketId: socket.id,
projectId,
userId,
};
socket.emit("v1:wallItems:set", data);
setWallItems((prevItems) => {
const updatedItems = [...prevItems, newWallItem];
const WallItemsForStorage = updatedItems.map((item) => {
const { model, ...rest } = item;
return {
...rest,
modelUuid: model?.uuid,
};
});
localStorage.setItem("WallItems", JSON.stringify(WallItemsForStorage));
echo.success("Model Added!");
return updatedItems;
});
}
} }
export default AddWallItems; export default AddWallItems;

View File

@ -1,60 +1,60 @@
import { getUserData } from "../../../../functions/getUserData";
import * as Types from "../../../../types/world/worldTypes"; import * as Types from "../../../../types/world/worldTypes";
// import { deleteWallItem } from '../../../../services/factoryBuilder/assest/wallAsset/deleteWallItemApi'; // import { deleteWallItem } from '../../../../services/factoryBuilder/assest/wallAsset/deleteWallItemApi';
import { Socket } from 'socket.io-client'; import { Socket } from "socket.io-client";
function DeleteWallItems( function DeleteWallItems(
hoveredDeletableWallItem: Types.RefMesh, hoveredDeletableWallItem: Types.RefMesh,
setWallItems: Types.setWallItemSetState, setWallItems: Types.setWallItemSetState,
wallItems: Types.wallItems, wallItems: Types.wallItems,
socket: Socket<any>, socket: Socket<any>,
projectId?: string projectId?: string
): void { ): void {
////////// Deleting the hovered Wall GLTF from thewallItems and also update it in the localstorage //////////
const { userId, organization, email } = getUserData();
if (hoveredDeletableWallItem.current && hoveredDeletableWallItem.current) {
setWallItems([]);
let WallItemsRef = wallItems;
const removedItem = WallItemsRef.find(
(item) => item.model?.uuid === hoveredDeletableWallItem.current?.uuid
);
const Items = WallItemsRef.filter(
(item) => item.model?.uuid !== hoveredDeletableWallItem.current?.uuid
);
////////// Deleting the hovered Wall GLTF from thewallItems and also update it in the localstorage ////////// setTimeout(async () => {
WallItemsRef = Items;
setWallItems(WallItemsRef);
if (hoveredDeletableWallItem.current && hoveredDeletableWallItem.current) { //REST
setWallItems([]);
let WallItemsRef = wallItems;
const removedItem = WallItemsRef.find((item) => item.model?.uuid === hoveredDeletableWallItem.current?.uuid);
const Items = WallItemsRef.filter((item) => item.model?.uuid !== hoveredDeletableWallItem.current?.uuid);
setTimeout(async () => { // await deleteWallItem(organization, removedItem?.model?.uuid!, removedItem?.modelName!)
WallItemsRef = Items;
setWallItems(WallItemsRef);
const email = localStorage.getItem('email') //SOCKET
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
//REST const data = {
organization,
modelUuid: removedItem?.model?.uuid!,
modelName: removedItem?.modelName!,
socketId: socket.id,
projectId,
userId,
};
// await deleteWallItem(organization, removedItem?.model?.uuid!, removedItem?.modelName!) socket.emit("v1:wallItems:delete", data);
//SOCKET const WallItemsForStorage = WallItemsRef.map((item) => {
const { model, ...rest } = item;
return {
...rest,
modelUuid: model?.uuid,
};
});
const data = { localStorage.setItem("WallItems", JSON.stringify(WallItemsForStorage));
organization: organization, hoveredDeletableWallItem.current = null;
modelUuid: removedItem?.model?.uuid!, }, 50);
modelName: removedItem?.modelName!, }
socketId: socket.id,
projectId,
userId
}
socket.emit('v1:wallItems:delete', data);
const WallItemsForStorage = WallItemsRef.map(item => {
const { model, ...rest } = item;
return {
...rest,
modelUuid: model?.uuid,
};
});
localStorage.setItem("WallItems", JSON.stringify(WallItemsForStorage));
hoveredDeletableWallItem.current = null;
}, 50);
}
} }
export default DeleteWallItems; export default DeleteWallItems;

View File

@ -17,6 +17,7 @@ import drawWall from "../geomentries/lines/drawWall";
import drawOnlyFloor from "../geomentries/floors/drawOnlyFloor"; import drawOnlyFloor from "../geomentries/floors/drawOnlyFloor";
import addDragControl from "../eventDeclaration/dragControlDeclaration"; import addDragControl from "../eventDeclaration/dragControlDeclaration";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
const FloorPlanGroup = ({ floorPlanGroup, floorPlanGroupLine, floorPlanGroupPoint, floorGroup, currentLayerPoint, dragPointControls, hoveredDeletablePoint, hoveredDeletableLine, plane, line, lines, onlyFloorline, onlyFloorlines, ReferenceLineMesh, LineCreated, isSnapped, ispreSnapped, snappedPoint, isSnappedUUID, isAngleSnapped, anglesnappedPoint }: any) => { const FloorPlanGroup = ({ floorPlanGroup, floorPlanGroupLine, floorPlanGroupPoint, floorGroup, currentLayerPoint, dragPointControls, hoveredDeletablePoint, hoveredDeletableLine, plane, line, lines, onlyFloorline, onlyFloorlines, ReferenceLineMesh, LineCreated, isSnapped, ispreSnapped, snappedPoint, isSnappedUUID, isAngleSnapped, anglesnappedPoint }: any) => {
const state = useThree(); const state = useThree();
@ -30,6 +31,8 @@ const FloorPlanGroup = ({ floorPlanGroup, floorPlanGroupLine, floorPlanGroupPoin
const { setDeletedLines } = useDeletedLines(); const { setDeletedLines } = useDeletedLines();
const { socket } = useSocketStore(); const { socket } = useSocketStore();
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
if (toolMode === 'move') { if (toolMode === 'move') {
@ -44,8 +47,6 @@ const FloorPlanGroup = ({ floorPlanGroup, floorPlanGroupLine, floorPlanGroupPoin
}, [toolMode, state]); }, [toolMode, state]);
useEffect(() => { useEffect(() => {
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
// Load data from localStorage if available // Load data from localStorage if available
getLines(organization, projectId).then((data) => { getLines(organization, projectId).then((data) => {

View File

@ -19,6 +19,7 @@ import loadInitialWallItems from "../IntialLoad/loadInitialWallItems";
import AddWallItems from "../geomentries/walls/addWallItems"; import AddWallItems from "../geomentries/walls/addWallItems";
import useModuleStore from "../../../store/useModuleStore"; import useModuleStore from "../../../store/useModuleStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
const WallItemsGroup = ({ const WallItemsGroup = ({
currentWallItem, currentWallItem,
@ -38,6 +39,7 @@ const WallItemsGroup = ({
const { activeModule } = useModuleStore(); const { activeModule } = useModuleStore();
const { selectedItem } = useSelectedItem(); const { selectedItem } = useSelectedItem();
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
// Load Wall Items from the backend // Load Wall Items from the backend
@ -120,9 +122,6 @@ const WallItemsGroup = ({
}); });
setTimeout(async () => { setTimeout(async () => {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
const userId = localStorage.getItem("userId");
//REST //REST
@ -142,7 +141,7 @@ const WallItemsGroup = ({
//SOCKET //SOCKET
const data = { const data = {
organization: organization, organization,
modelUuid: currentItem.model?.uuid!, modelUuid: currentItem.model?.uuid!,
assetId: currentItem.assetId, assetId: currentItem.assetId,
modelName: currentItem.modelName!, modelName: currentItem.modelName!,

View File

@ -10,18 +10,18 @@ import objectLinesToArray from "../geomentries/lines/lineConvertions/objectLines
import loadWalls from "../geomentries/walls/loadWalls"; import loadWalls from "../geomentries/walls/loadWalls";
import texturePath from "../../../assets/textures/floor/wall-tex.png"; import texturePath from "../../../assets/textures/floor/wall-tex.png";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
const WallsMeshComponent = ({ lines }: any) => { const WallsMeshComponent = ({ lines }: any) => {
const { walls, setWalls } = useWalls(); const { walls, setWalls } = useWalls();
const { updateScene, setUpdateScene } = useUpdateScene(); const { updateScene, setUpdateScene } = useUpdateScene();
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
if (updateScene) { if (updateScene) {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
getLines(organization,projectId).then((data) => { getLines(organization, projectId).then((data) => {
const Lines: Types.Lines = objectLinesToArray(data); const Lines: Types.Lines = objectLinesToArray(data);
localStorage.setItem("Lines", JSON.stringify(Lines)); localStorage.setItem("Lines", JSON.stringify(Lines));

View File

@ -18,6 +18,7 @@ import * as turf from "@turf/turf";
import { computeArea } from "../functions/computeArea"; import { computeArea } from "../functions/computeArea";
import { useSelectedZoneStore } from "../../../store/visualization/useZoneStore"; import { useSelectedZoneStore } from "../../../store/visualization/useZoneStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
const ZoneGroup: React.FC = () => { const ZoneGroup: React.FC = () => {
const { camera, pointer, gl, raycaster, scene, controls } = useThree(); const { camera, pointer, gl, raycaster, scene, controls } = useThree();
@ -40,6 +41,7 @@ const ZoneGroup: React.FC = () => {
const { activeLayer } = useActiveLayer(); const { activeLayer } = useActiveLayer();
const { socket } = useSocketStore(); const { socket } = useSocketStore();
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
const groupsRef = useRef<any>(); const groupsRef = useRef<any>();
@ -73,10 +75,8 @@ const ZoneGroup: React.FC = () => {
useEffect(() => { useEffect(() => {
const fetchZones = async () => { const fetchZones = async () => {
const email = localStorage.getItem("email");
if (!email) return; if (!email) return;
const organization = email.split("@")[1].split(".")[0];
const data = await getZonesApi(organization, projectId); const data = await getZonesApi(organization, projectId);
// console.log('data: ', data); // console.log('data: ', data);
@ -142,9 +142,6 @@ const ZoneGroup: React.FC = () => {
points: [number, number, number][]; points: [number, number, number][];
layer: string; layer: string;
}) => { }) => {
const email = localStorage.getItem("email");
const userId = localStorage.getItem("userId");
const organization = email!.split("@")[1].split(".")[0];
const calculateCenter = (points: number[][]) => { const calculateCenter = (points: number[][]) => {
if (!points || points.length === 0) return null; if (!points || points.length === 0) return null;
@ -172,7 +169,7 @@ const ZoneGroup: React.FC = () => {
const input = { const input = {
userId: userId, userId: userId,
projectId, projectId,
organization: organization, organization,
zoneData: { zoneData: {
zoneName: zone.zoneName, zoneName: zone.zoneName,
zoneUuid: zone.zoneUuid, zoneUuid: zone.zoneUuid,
@ -193,9 +190,6 @@ const ZoneGroup: React.FC = () => {
points: [number, number, number][]; points: [number, number, number][];
layer: string; layer: string;
}) => { }) => {
const email = localStorage.getItem("email");
const userId = localStorage.getItem("userId");
const organization = email!.split("@")[1].split(".")[0];
const calculateCenter = (points: number[][]) => { const calculateCenter = (points: number[][]) => {
if (!points || points.length === 0) return null; if (!points || points.length === 0) return null;
@ -223,7 +217,7 @@ const ZoneGroup: React.FC = () => {
const input = { const input = {
userId: userId, userId: userId,
projectId, projectId,
organization: organization, organization,
zoneData: { zoneData: {
zoneName: zone.zoneName, zoneName: zone.zoneName,
zoneUuid: zone.zoneUuid, zoneUuid: zone.zoneUuid,
@ -238,14 +232,11 @@ const ZoneGroup: React.FC = () => {
}; };
const deleteZoneFromBackend = async (zoneUuid: string) => { const deleteZoneFromBackend = async (zoneUuid: string) => {
const email = localStorage.getItem("email");
const userId = localStorage.getItem("userId");
const organization = email!.split("@")[1].split(".")[0];
const input = { const input = {
userId: userId, userId: userId,
projectId, projectId,
organization: organization, organization,
zoneUuid: zoneUuid, zoneUuid: zoneUuid,
}; };

View File

@ -14,17 +14,17 @@ import { getAvatarColor } from "../functions/getAvatarColor";
import { useSelectedUserStore } from "../../../store/collaboration/useCollabStore"; import { useSelectedUserStore } from "../../../store/collaboration/useCollabStore";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore"; import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
import setCameraView from "../functions/setCameraView"; import setCameraView from "../functions/setCameraView";
import { getUserData } from "../../../functions/getUserData";
const CamModelsGroup = () => { const CamModelsGroup = () => {
const navigate = useNavigate(); const navigate = useNavigate();
const groupRef = useRef<THREE.Group>(null); const groupRef = useRef<THREE.Group>(null);
const email = localStorage.getItem("email"); const { userId, organization, email } = getUserData();
const { setActiveUsers } = useActiveUsers(); const { setActiveUsers } = useActiveUsers();
const { socket } = useSocketStore(); const { socket } = useSocketStore();
const { activeModule } = useModuleStore(); const { activeModule } = useModuleStore();
const { selectedUser, setSelectedUser } = useSelectedUserStore(); const { selectedUser, setSelectedUser } = useSelectedUserStore();
const { isPlaying } = usePlayButtonStore(); const { isPlaying } = usePlayButtonStore();
// eslint-disable-next-line react-hooks/exhaustive-deps // eslint-disable-next-line react-hooks/exhaustive-deps
const loader = new GLTFLoader(); const loader = new GLTFLoader();
const dracoLoader = new DRACOLoader(); const dracoLoader = new DRACOLoader();
@ -87,7 +87,6 @@ const CamModelsGroup = () => {
if (!email) navigate("/"); if (!email) navigate("/");
if (!socket) return; if (!socket) return;
const organization = email!.split("@")[1].split(".")[0];
socket.on("userConnectResponse", (data: any) => { socket.on("userConnectResponse", (data: any) => {
if (!groupRef.current) return; if (!groupRef.current) return;
@ -222,7 +221,6 @@ const CamModelsGroup = () => {
useEffect(() => { useEffect(() => {
if (!groupRef.current) return; if (!groupRef.current) return;
const organization = email!.split("@")[1].split(".")[0];
getActiveUsersData(organization).then((data) => { getActiveUsersData(organization).then((data) => {
const filteredData = data.cameraDatas.filter( const filteredData = data.cameraDatas.filter(

View File

@ -35,6 +35,7 @@ import { useParams } from "react-router-dom";
import { useAssetsStore } from "../../../store/builder/useAssetStore"; import { useAssetsStore } from "../../../store/builder/useAssetStore";
import { useEventsStore } from "../../../store/simulation/useEventsStore"; import { useEventsStore } from "../../../store/simulation/useEventsStore";
import { useProductStore } from "../../../store/simulation/useProductStore"; import { useProductStore } from "../../../store/simulation/useProductStore";
import { getUserData } from "../../../functions/getUserData";
export default function SocketResponses({ export default function SocketResponses({
floorPlanGroup, floorPlanGroup,
@ -59,10 +60,8 @@ export default function SocketResponses({
const { zonePoints, setZonePoints } = useZonePoints(); const { zonePoints, setZonePoints } = useZonePoints();
const { projectId } = useParams(); const { projectId } = useParams();
const { addAsset, updateAsset, removeAsset } = useAssetsStore(); const { addAsset, updateAsset, removeAsset } = useAssetsStore();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
if (!socket) return; if (!socket) return;
@ -464,8 +463,6 @@ export default function SocketResponses({
useEffect(() => { useEffect(() => {
if (!socket) return; if (!socket) return;
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_MARKETPLACE_URL}`; let url_Backend_dwinzo = `http://${process.env.REACT_APP_SERVER_MARKETPLACE_URL}`;
socket.on("v1:wallItem:Response:Delete", (data: any) => { socket.on("v1:wallItem:Response:Delete", (data: any) => {
@ -660,8 +657,6 @@ export default function SocketResponses({
useEffect(() => { useEffect(() => {
if (!socket) return; if (!socket) return;
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
socket.on("v1:Line:response:create", async (data: any) => { socket.on("v1:Line:response:create", async (data: any) => {
// //
@ -778,8 +773,6 @@ export default function SocketResponses({
useEffect(() => { useEffect(() => {
if (!socket) return; if (!socket) return;
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
socket.on("v1:zone:response:updates", (data: any) => { socket.on("v1:zone:response:updates", (data: any) => {
// console.log('data: ', data); // console.log('data: ', data);

View File

@ -5,6 +5,7 @@ import { useThree } from "@react-three/fiber";
import { getCamera } from "../../../services/factoryBuilder/camera/getCameraApi"; import { getCamera } from "../../../services/factoryBuilder/camera/getCameraApi";
import * as CONSTANTS from '../../../types/world/worldConstants'; import * as CONSTANTS from '../../../types/world/worldConstants';
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
export default function SwitchView() { export default function SwitchView() {
const { toggleView } = useToggleView(); const { toggleView } = useToggleView();
@ -15,6 +16,7 @@ export default function SwitchView() {
orthoCamera.current = new THREE.OrthographicCamera(-window.innerWidth / 2, window.innerWidth / 2, window.innerHeight / 2, -window.innerHeight / 2, 0.01, 1000); orthoCamera.current = new THREE.OrthographicCamera(-window.innerWidth / 2, window.innerWidth / 2, window.innerHeight / 2, -window.innerHeight / 2, 0.01, 1000);
perspectiveCamera.current = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 1000); perspectiveCamera.current = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.01, 1000);
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
if (!perspectiveCamera.current || !orthoCamera.current) return; if (!perspectiveCamera.current || !orthoCamera.current) return;
@ -38,9 +40,7 @@ export default function SwitchView() {
state.controls.mouseButtons.right = CONSTANTS.twoDimension.rightMouse; state.controls.mouseButtons.right = CONSTANTS.twoDimension.rightMouse;
} else { } else {
try { try {
const email = localStorage.getItem('email'); getCamera(organization, localStorage.getItem('userId')!, projectId).then((data) => {
const organization = (email!.split("@")[1]).split(".")[0];
getCamera(organization, localStorage.getItem('userId')!,projectId).then((data) => {
if (data && data.position && data.target) { if (data && data.position && data.target) {
state.controls?.setPosition(data.position.x, data.position.y, data.position.z); state.controls?.setPosition(data.position.x, data.position.y, data.position.z);
state.controls?.setTarget(data.target.x, data.target.y, data.target.z); state.controls?.setTarget(data.target.x, data.target.y, data.target.z);

View File

@ -1,29 +1,32 @@
import { Socket } from "socket.io-client"; import { Socket } from "socket.io-client";
import * as THREE from 'three'; import * as THREE from "three";
import { getUserData } from "../../../functions/getUserData";
export default function updateCamPosition( export default function updateCamPosition(
controls: any, controls: any,
socket: Socket, socket: Socket,
position: THREE.Vector3, position: THREE.Vector3,
rotation: THREE.Euler, rotation: THREE.Euler,
projectId?:string projectId?: string
) { ) {
if (!controls.current) return; const { userId, organization, email } = getUserData();
const target = controls.current.getTarget(new THREE.Vector3()); if (!controls.current) return;
const email = localStorage.getItem("email"); const target = controls.current.getTarget(new THREE.Vector3());
const organization = email!.split("@")[1].split(".")[0];
const camData = { const camData = {
organization: organization, organization,
userId: localStorage.getItem("userId")!, userId: userId,
position: position, position: position,
target: new THREE.Vector3(target.x, 0, target.z), target: new THREE.Vector3(target.x, 0, target.z),
rotation: new THREE.Vector3(rotation.x, rotation.y, rotation.z), rotation: new THREE.Vector3(rotation.x, rotation.y, rotation.z),
socketId: socket.id, socketId: socket.id,
projectId projectId,
}; };
// console.log('CameracamData: ', camData); // console.log('CameracamData: ', camData);
socket.emit("v1:Camera:set", camData); socket.emit("v1:Camera:set", camData);
localStorage.setItem("cameraPosition", JSON.stringify(position)); localStorage.setItem("cameraPosition", JSON.stringify(position));
localStorage.setItem("controlTarget", JSON.stringify(new THREE.Vector3(target.x, 0, target.z))); localStorage.setItem(
"controlTarget",
JSON.stringify(new THREE.Vector3(target.x, 0, target.z))
);
} }

View File

@ -12,6 +12,7 @@ import SwitchView from "../camera/switchView";
import SelectionControls from "./selectionControls/selectionControls"; import SelectionControls from "./selectionControls/selectionControls";
import TransformControl from "./transformControls/transformControls"; import TransformControl from "./transformControls/transformControls";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
export default function Controls() { export default function Controls() {
const controlsRef = useRef<CameraControls>(null); const controlsRef = useRef<CameraControls>(null);
@ -21,16 +22,14 @@ export default function Controls() {
const { socket } = useSocketStore(); const { socket } = useSocketStore();
const state = useThree(); const state = useThree();
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
if (controlsRef.current) { if (controlsRef.current) {
(controlsRef.current as any).mouseButtons.left = CONSTANTS.thirdPersonControls.leftMouse; (controlsRef.current as any).mouseButtons.left = CONSTANTS.thirdPersonControls.leftMouse;
(controlsRef.current as any).mouseButtons.right = CONSTANTS.thirdPersonControls.rightMouse; (controlsRef.current as any).mouseButtons.right = CONSTANTS.thirdPersonControls.rightMouse;
} }
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
const userId = localStorage.getItem("userId")!;
getCamera(organization, userId, projectId).then((data) => { getCamera(organization, userId, projectId).then((data) => {
// console.log('data: ', data); // console.log('data: ', data);
@ -54,12 +53,9 @@ export default function Controls() {
localStorage.setItem("cameraPosition", JSON.stringify(new THREE.Vector3(...CONSTANTS.threeDimension.defaultPosition))); localStorage.setItem("cameraPosition", JSON.stringify(new THREE.Vector3(...CONSTANTS.threeDimension.defaultPosition)));
localStorage.setItem("controlTarget", JSON.stringify(new THREE.Vector3(...CONSTANTS.threeDimension.defaultTarget))); localStorage.setItem("controlTarget", JSON.stringify(new THREE.Vector3(...CONSTANTS.threeDimension.defaultTarget)));
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
const camData = { const camData = {
organization: organization, organization,
userId: userId, userId: userId,
position: new THREE.Vector3(...CONSTANTS.threeDimension.defaultPosition), position: new THREE.Vector3(...CONSTANTS.threeDimension.defaultPosition),
target: new THREE.Vector3(...CONSTANTS.threeDimension.defaultTarget), target: new THREE.Vector3(...CONSTANTS.threeDimension.defaultTarget),

View File

@ -8,6 +8,7 @@ import { detectModifierKeys } from "../../../../utils/shortcutkeys/detectModifie
import { useEventsStore } from "../../../../store/simulation/useEventsStore"; import { useEventsStore } from "../../../../store/simulation/useEventsStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useAssetsStore } from "../../../../store/builder/useAssetStore"; import { useAssetsStore } from "../../../../store/builder/useAssetStore";
import { getUserData } from "../../../../functions/getUserData";
const CopyPasteControls = ({ const CopyPasteControls = ({
copiedObjects, copiedObjects,
@ -30,6 +31,7 @@ const CopyPasteControls = ({
const { addEvent } = useEventsStore(); const { addEvent } = useEventsStore();
const { projectId } = useParams(); const { projectId } = useParams();
const { assets, addAsset } = useAssetsStore(); const { assets, addAsset } = useAssetsStore();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
if (!camera || !scene || toggleView) return; if (!camera || !scene || toggleView) return;
@ -146,8 +148,6 @@ const CopyPasteControls = ({
const addPastedObjects = () => { const addPastedObjects = () => {
if (pastedObjects.length === 0) return; if (pastedObjects.length === 0) return;
const email = localStorage.getItem("email");
const organization = email ? email.split("@")[1].split(".")[0] : "default";
pastedObjects.forEach(async (obj: THREE.Object3D) => { pastedObjects.forEach(async (obj: THREE.Object3D) => {
if (obj) { if (obj) {
@ -332,8 +332,7 @@ const CopyPasteControls = ({
} }
newFloorItem.eventData = eventData; newFloorItem.eventData = eventData;
//REST
const userId = localStorage.getItem("userId"); //REST
// await setFloorItemApi( // await setFloorItemApi(
// organization, // organization,
@ -404,7 +403,6 @@ const CopyPasteControls = ({
// ); // );
//SOCKET //SOCKET
const userId = localStorage.getItem("userId");
const data = { const data = {
organization, organization,
modelUuid: newFloorItem.modelUuid, modelUuid: newFloorItem.modelUuid,

View File

@ -8,6 +8,7 @@ import { detectModifierKeys } from "../../../../utils/shortcutkeys/detectModifie
import { useEventsStore } from "../../../../store/simulation/useEventsStore"; import { useEventsStore } from "../../../../store/simulation/useEventsStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useAssetsStore } from "../../../../store/builder/useAssetStore"; import { useAssetsStore } from "../../../../store/builder/useAssetStore";
import { getUserData } from "../../../../functions/getUserData";
const DuplicationControls = ({ const DuplicationControls = ({
duplicatedObjects, duplicatedObjects,
@ -28,6 +29,7 @@ const DuplicationControls = ({
const { addEvent } = useEventsStore(); const { addEvent } = useEventsStore();
const { projectId } = useParams(); const { projectId } = useParams();
const { assets, addAsset } = useAssetsStore(); const { assets, addAsset } = useAssetsStore();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
if (!camera || !scene || toggleView) return; if (!camera || !scene || toggleView) return;
@ -121,8 +123,6 @@ const DuplicationControls = ({
const addDuplicatedAssets = () => { const addDuplicatedAssets = () => {
if (duplicatedObjects.length === 0) return; if (duplicatedObjects.length === 0) return;
const email = localStorage.getItem("email");
const organization = email ? email.split("@")[1].split(".")[0] : "default";
duplicatedObjects.forEach(async (obj: THREE.Object3D) => { duplicatedObjects.forEach(async (obj: THREE.Object3D) => {
if (obj) { if (obj) {
@ -307,7 +307,6 @@ const DuplicationControls = ({
newFloorItem.eventData = eventData; newFloorItem.eventData = eventData;
const userId = localStorage.getItem("userId");
//REST //REST
// await setFloorItemApi( // await setFloorItemApi(
@ -358,7 +357,6 @@ const DuplicationControls = ({
} else { } else {
const userId = localStorage.getItem("userId");
//REST //REST
// await setFloorItemApi( // await setFloorItemApi(

View File

@ -13,6 +13,7 @@ import DistanceFindingControls from "./distanceFindingControls";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useAssetsStore } from "../../../../store/builder/useAssetStore"; import { useAssetsStore } from "../../../../store/builder/useAssetStore";
import { useProductContext } from "../../../simulation/products/productContext"; import { useProductContext } from "../../../simulation/products/productContext";
import { getUserData } from "../../../../functions/getUserData";
function MoveControls({ function MoveControls({
movedObjects, movedObjects,
@ -35,9 +36,7 @@ function MoveControls({
const { selectedProduct } = selectedProductStore(); const { selectedProduct } = selectedProductStore();
const { socket } = useSocketStore(); const { socket } = useSocketStore();
const [keyEvent, setKeyEvent] = useState<"Ctrl" | "Shift" | "Ctrl+Shift" | "">(""); const [keyEvent, setKeyEvent] = useState<"Ctrl" | "Shift" | "Ctrl+Shift" | "">("");
const email = localStorage.getItem("email"); const { userId, organization, email } = getUserData();
const organization = email!.split("@")[1].split(".")[0];
const userId = localStorage.getItem("userId");
const { projectId } = useParams(); const { projectId } = useParams();
const { updateAsset } = useAssetsStore(); const { updateAsset } = useAssetsStore();
const AssetGroup = useRef<THREE.Group | undefined>(undefined); const AssetGroup = useRef<THREE.Group | undefined>(undefined);

View File

@ -10,6 +10,7 @@ import { upsertProductOrEventApi } from "../../../../services/simulation/product
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useAssetsStore } from "../../../../store/builder/useAssetStore"; import { useAssetsStore } from "../../../../store/builder/useAssetStore";
import { useProductContext } from "../../../simulation/products/productContext"; import { useProductContext } from "../../../simulation/products/productContext";
import { getUserData } from "../../../../functions/getUserData";
function RotateControls({ function RotateControls({
rotatedObjects, rotatedObjects,
@ -31,10 +32,7 @@ function RotateControls({
const { selectedProductStore } = useProductContext(); const { selectedProductStore } = useProductContext();
const { selectedProduct } = selectedProductStore(); const { selectedProduct } = selectedProductStore();
const { socket } = useSocketStore(); const { socket } = useSocketStore();
const { userId, organization, email } = getUserData();
const email = localStorage.getItem('email')
const organization = (email?.split("@")[1])?.split(".")[0] ?? null;
const userId = localStorage.getItem("userId");
const { projectId } = useParams(); const { projectId } = useParams();
const { updateAsset } = useAssetsStore(); const { updateAsset } = useAssetsStore();
const AssetGroup = useRef<THREE.Group | undefined>(undefined); const AssetGroup = useRef<THREE.Group | undefined>(undefined);

View File

@ -17,6 +17,7 @@ import { useEventsStore } from "../../../../store/simulation/useEventsStore";
import { useProductStore } from "../../../../store/simulation/useProductStore"; import { useProductStore } from "../../../../store/simulation/useProductStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useAssetsStore } from "../../../../store/builder/useAssetStore"; import { useAssetsStore } from "../../../../store/builder/useAssetStore";
import { getUserData } from "../../../../functions/getUserData";
const SelectionControls: React.FC = () => { const SelectionControls: React.FC = () => {
const { camera, controls, gl, scene, raycaster, pointer } = useThree(); const { camera, controls, gl, scene, raycaster, pointer } = useThree();
@ -43,6 +44,7 @@ const SelectionControls: React.FC = () => {
const rightClickMoved = useRef(false); const rightClickMoved = useRef(false);
const isCtrlSelecting = useRef(false); const isCtrlSelecting = useRef(false);
const isShiftSelecting = useRef(false); const isShiftSelecting = useRef(false);
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
if (!camera || !scene || toggleView) return; if (!camera || !scene || toggleView) return;
@ -251,9 +253,6 @@ const SelectionControls: React.FC = () => {
const deleteSelection = () => { const deleteSelection = () => {
if (selectedAssets.length > 0 && duplicatedObjects.length === 0) { if (selectedAssets.length > 0 && duplicatedObjects.length === 0) {
const email = localStorage.getItem("email");
const organization = email!.split("@")[1].split(".")[0];
const userId = localStorage.getItem("userId");
const storedItems = JSON.parse(localStorage.getItem("FloorItems") ?? "[]"); const storedItems = JSON.parse(localStorage.getItem("FloorItems") ?? "[]");
const selectedUUIDs = selectedAssets.map((mesh: THREE.Object3D) => mesh.uuid); const selectedUUIDs = selectedAssets.map((mesh: THREE.Object3D) => mesh.uuid);
@ -269,7 +268,7 @@ const SelectionControls: React.FC = () => {
//SOCKET //SOCKET
const data = { const data = {
organization: organization, organization,
modelUuid: selectedMesh.userData.modelUuid, modelUuid: selectedMesh.userData.modelUuid,
modelName: selectedMesh.userData.modelName, modelName: selectedMesh.userData.modelName,
socketId: socket.id, socketId: socket.id,

View File

@ -12,6 +12,7 @@ import { setFloorItemApi } from "../../../../services/factoryBuilder/assest/floo
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useAssetsStore } from "../../../../store/builder/useAssetStore"; import { useAssetsStore } from "../../../../store/builder/useAssetStore";
import { useProductContext } from "../../../simulation/products/productContext"; import { useProductContext } from "../../../simulation/products/productContext";
import { getUserData } from "../../../../functions/getUserData";
export default function TransformControl() { export default function TransformControl() {
const state = useThree(); const state = useThree();
@ -24,10 +25,7 @@ export default function TransformControl() {
const { selectedProductStore } = useProductContext(); const { selectedProductStore } = useProductContext();
const { selectedProduct } = selectedProductStore(); const { selectedProduct } = selectedProductStore();
const { updateAsset, getAssetById } = useAssetsStore(); const { updateAsset, getAssetById } = useAssetsStore();
const { userId, organization, email } = getUserData();
const email = localStorage.getItem('email')
const organization = (email!.split("@")[1]).split(".")[0];
const userId = localStorage.getItem("userId");
const { projectId } = useParams(); const { projectId } = useParams();
const updateBackend = ( const updateBackend = (

View File

@ -11,7 +11,7 @@ import Collaboration from "../collaboration/collaboration";
import useModuleStore from "../../store/useModuleStore"; import useModuleStore from "../../store/useModuleStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getAllProjects } from "../../services/dashboard/getAllProjects"; import { getAllProjects } from "../../services/dashboard/getAllProjects";
import { getUserData } from "../../components/Dashboard/functions/getUserData"; import { getUserData } from "../../functions/getUserData";
import { useLoadingProgress, useSocketStore } from "../../store/builder/store"; import { useLoadingProgress, useSocketStore } from "../../store/builder/store";
import { useAssetsStore } from "../../store/builder/useAssetStore"; import { useAssetsStore } from "../../store/builder/useAssetStore";

View File

@ -15,6 +15,7 @@ import { useEditWidgetOptionsStore, useRightClickSelected, useRightSelected, } f
import OuterClick from "../../utils/outerClick"; import OuterClick from "../../utils/outerClick";
import { useWidgetStore } from "../../store/useWidgetStore"; import { useWidgetStore } from "../../store/useWidgetStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../functions/getUserData";
type Side = "top" | "bottom" | "left" | "right"; type Side = "top" | "bottom" | "left" | "right";
@ -72,11 +73,9 @@ const RealTimeVisulization: React.FC = () => {
], ],
setMenuVisible: () => setSelectedChartId(null), setMenuVisible: () => setSelectedChartId(null),
}); });
const { userName, userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
async function GetZoneData() { async function GetZoneData() {
const email = localStorage.getItem("email") ?? "";
const organization = email?.split("@")[1]?.split(".")[0];
try { try {
const response = await getZone2dData(organization, projectId); const response = await getZone2dData(organization, projectId);
// console.log('responseRt: ', response); // console.log('responseRt: ', response);

View File

@ -1,3 +1,4 @@
import { getUserData } from "../../../functions/getUserData";
import { Template } from "../../../store/useTemplateStore"; import { Template } from "../../../store/useTemplateStore";
import { captureVisualization } from "./captureVisualization"; import { captureVisualization } from "./captureVisualization";
@ -11,7 +12,7 @@ type HandleSaveTemplateProps = {
}; };
templates?: Template[]; templates?: Template[];
visualizationSocket: any; visualizationSocket: any;
projectId?:string projectId?: string;
}; };
// Generate a unique ID // Generate a unique ID
@ -26,9 +27,10 @@ export const handleSaveTemplate = async ({
selectedZone, selectedZone,
templates = [], templates = [],
visualizationSocket, visualizationSocket,
projectId projectId,
}: HandleSaveTemplateProps): Promise<void> => { }: HandleSaveTemplateProps): Promise<void> => {
try { try {
const { userId, organization, email } = getUserData();
// Check if the selected zone has any widgets // Check if the selected zone has any widgets
if (!selectedZone.panelOrder || selectedZone.panelOrder.length === 0) { if (!selectedZone.panelOrder || selectedZone.panelOrder.length === 0) {
return; return;
@ -66,18 +68,14 @@ export const handleSaveTemplate = async ({
}; };
// Extract organization from email // Extract organization from email
const email = localStorage.getItem("email") || "";
const organization = email.includes("@")
? email.split("@")[1]?.split(".")[0]
: "";
const userId = localStorage.getItem("userId");
if (!organization) { if (!organization) {
return; return;
} }
let saveTemplate = { let saveTemplate = {
organization: organization, organization,
template: newTemplate, template: newTemplate,
userId,projectId userId,
projectId,
}; };
if (visualizationSocket) { if (visualizationSocket) {
visualizationSocket.emit("v1:viz-template:add", saveTemplate); visualizationSocket.emit("v1:viz-template:add", saveTemplate);

View File

@ -1,5 +1,5 @@
import { generateUniqueId } from "../../../functions/generateUniqueId"; import { generateUniqueId } from "../../../functions/generateUniqueId";
import { getUserData } from "../../../functions/getUserData";
import { useDroppedObjectsStore } from "../../../store/visualization/useDroppedObjectsStore"; import { useDroppedObjectsStore } from "../../../store/visualization/useDroppedObjectsStore";
import { determinePosition } from "./determinePosition"; import { determinePosition } from "./determinePosition";
import { getActiveProperties } from "./getActiveProperties"; import { getActiveProperties } from "./getActiveProperties";
@ -10,7 +10,7 @@ interface HandleDropProps {
selectedZone: any; selectedZone: any;
setFloatingWidget: (value: any) => void; setFloatingWidget: (value: any) => void;
event: React.DragEvent<HTMLDivElement>; event: React.DragEvent<HTMLDivElement>;
projectId?:string projectId?: string;
} }
export const createHandleDrop = ({ export const createHandleDrop = ({
@ -18,14 +18,12 @@ export const createHandleDrop = ({
visualizationSocket, visualizationSocket,
selectedZone, selectedZone,
setFloatingWidget, setFloatingWidget,
event,projectId event,
projectId,
}: HandleDropProps) => { }: HandleDropProps) => {
event.preventDefault(); event.preventDefault();
try { try {
const email = localStorage.getItem("email") ?? ""; const { userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
const data = event.dataTransfer.getData("text/plain"); const data = event.dataTransfer.getData("text/plain");
if (widgetSubOption === "3D") return; if (widgetSubOption === "3D") return;
@ -98,11 +96,12 @@ export const createHandleDrop = ({
organization, organization,
widget: newObject, widget: newObject,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
projectId,userId projectId,
userId,
}; };
console.log('addFloatingWidget: ', addFloatingWidget); console.log("addFloatingWidget: ", addFloatingWidget);
console.log('visualizationSocket: ', visualizationSocket); console.log("visualizationSocket: ", visualizationSocket);
if (visualizationSocket) { if (visualizationSocket) {
visualizationSocket.emit("v1:viz-float:add", addFloatingWidget); visualizationSocket.emit("v1:viz-float:add", addFloatingWidget);
} }

View File

@ -6,6 +6,7 @@ import { getTemplateData } from "../../../services/visulization/zone/getTemplate
import { useDroppedObjectsStore } from "../../../store/visualization/useDroppedObjectsStore"; import { useDroppedObjectsStore } from "../../../store/visualization/useDroppedObjectsStore";
import RenameInput from "../../../components/ui/inputs/RenameInput"; import RenameInput from "../../../components/ui/inputs/RenameInput";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
const Templates = () => { const Templates = () => {
@ -13,13 +14,12 @@ const Templates = () => {
const { setSelectedZone, selectedZone } = useSelectedZoneStore(); const { setSelectedZone, selectedZone } = useSelectedZoneStore();
const { visualizationSocket } = useSocketStore(); const { visualizationSocket } = useSocketStore();
const { projectId } = useParams(); const { projectId } = useParams();
const { userName, userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
async function templateData() { async function templateData() {
try { try {
const email = localStorage.getItem("email") ?? ""; let response = await getTemplateData(organization, projectId);
const organization = email?.split("@")[1]?.split(".")[0];
let response = await getTemplateData(organization,projectId);
setTemplates(response); setTemplates(response);
} catch (error) { } catch (error) {
echo.error("Failed to fetching template data"); echo.error("Failed to fetching template data");
@ -36,13 +36,11 @@ const Templates = () => {
) => { ) => {
try { try {
e.stopPropagation(); e.stopPropagation();
const email = localStorage.getItem("email") ?? ""; const { userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
let deleteTemplate = { let deleteTemplate = {
organization: organization, organization,
templateID: id, templateID: id,
userId,projectId userId, projectId
}; };
if (visualizationSocket) { if (visualizationSocket) {
visualizationSocket.emit( visualizationSocket.emit(
@ -60,15 +58,13 @@ const Templates = () => {
const handleLoadTemplate = async (template: any) => { const handleLoadTemplate = async (template: any) => {
try { try {
if (selectedZone.zoneName === "") return; if (selectedZone.zoneName === "") return;
const email = localStorage.getItem("email") ?? ""; const { userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
let loadingTemplate = { let loadingTemplate = {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
templateID: template.id, templateID: template.id,
projectId,userId projectId, userId
}; };
if (visualizationSocket) { if (visualizationSocket) {

View File

@ -19,6 +19,7 @@ import { usePlayButtonStore } from "../../../../store/usePlayButtonStore";
import OuterClick from "../../../../utils/outerClick"; import OuterClick from "../../../../utils/outerClick";
import useChartStore from "../../../../store/visualization/useChartStore"; import useChartStore from "../../../../store/visualization/useChartStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
type Side = "top" | "bottom" | "left" | "right"; type Side = "top" | "bottom" | "left" | "right";
@ -83,13 +84,13 @@ export const DraggableWidget = ({
}>({}); }>({});
const { measurements, duration, name } = useChartStore(); const { measurements, duration, name } = useChartStore();
const { isPlaying } = usePlayButtonStore(); const { isPlaying } = usePlayButtonStore();
const { userId, organization, email } = getUserData();
const [canvasDimensions, setCanvasDimensions] = useState({ const [canvasDimensions, setCanvasDimensions] = useState({
width: 0, width: 0,
height: 0, height: 0,
}); });
const { projectId } = useParams(); const { projectId } = useParams();
useEffect(() => {}, [measurements, duration, name]); useEffect(() => { }, [measurements, duration, name]);
const handlePointerDown = () => { const handlePointerDown = () => {
if (selectedChartId?.id !== widget.id) { if (selectedChartId?.id !== widget.id) {
setSelectedChartId(widget); setSelectedChartId(widget);
@ -100,14 +101,12 @@ export const DraggableWidget = ({
const deleteSelectedChart = async () => { const deleteSelectedChart = async () => {
try { try {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
let deleteWidget = { let deleteWidget = {
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widgetID: widget.id, widgetID: widget.id,
organization: organization, organization,
projectId,userId projectId, userId
}; };
if (visualizationSocket) { if (visualizationSocket) {
@ -173,9 +172,7 @@ export const DraggableWidget = ({
const duplicateWidget = async () => { const duplicateWidget = async () => {
try { try {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
const duplicatedWidget: Widget = { const duplicatedWidget: Widget = {
...widget, ...widget,
@ -188,10 +185,10 @@ export const DraggableWidget = ({
}; };
let duplicateWidget = { let duplicateWidget = {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: duplicatedWidget, widget: duplicatedWidget,
projectId,userId projectId, userId
}; };
if (visualizationSocket) { if (visualizationSocket) {
@ -297,9 +294,8 @@ export const DraggableWidget = ({
<div <div
draggable draggable
key={widget.id} key={widget.id}
className={`chart-container ${ className={`chart-container ${selectedChartId?.id === widget.id && !isPlaying && "activeChart"
selectedChartId?.id === widget.id && !isPlaying && "activeChart" }`}
}`}
onPointerDown={handlePointerDown} onPointerDown={handlePointerDown}
onDragStart={handleDragStart} onDragStart={handleDragStart}
onDragEnter={handleDragEnter} onDragEnter={handleDragEnter}
@ -327,9 +323,8 @@ export const DraggableWidget = ({
{openKebabId === widget.id && ( {openKebabId === widget.id && (
<div className="kebab-options" ref={widgetRef}> <div className="kebab-options" ref={widgetRef}>
<div <div
className={`edit btn ${ className={`edit btn ${isPanelFull(widget.panel) ? "btn-blur" : ""
isPanelFull(widget.panel) ? "btn-blur" : "" }`}
}`}
onClick={duplicateWidget} onClick={duplicateWidget}
> >
<div className="icon"> <div className="icon">

View File

@ -10,6 +10,7 @@ import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/visualization/useChartStore"; import useChartStore from "../../../../../store/visualization/useChartStore";
import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../../functions/getUserData";
interface ChartComponentProps { interface ChartComponentProps {
id: string; id: string;
@ -47,11 +48,10 @@ const BarGraphComponent = ({
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const { projectId } = useParams(); const { projectId } = useParams();
const { userName, userId, organization, email } = getUserData();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const defaultData = { const defaultData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [ datasets: [

View File

@ -8,6 +8,7 @@ import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/visualization/useChartStore"; import useChartStore from "../../../../../store/visualization/useChartStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore";
import { getUserData } from "../../../../../functions/getUserData";
interface ChartComponentProps { interface ChartComponentProps {
id: string; id: string;
@ -35,14 +36,13 @@ const DoughnutGraphComponent = ({
labels: [], labels: [],
datasets: [], datasets: [],
}); });
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const { selectedZone } = useSelectedZoneStore(); const { selectedZone } = useSelectedZoneStore();
const { projectId } = useParams(); const { projectId } = useParams();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0]
const defaultData = { const defaultData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [ datasets: [
@ -58,7 +58,7 @@ const DoughnutGraphComponent = ({
useEffect(() => { useEffect(() => {
},[]) }, [])
// Memoize Theme Colors // Memoize Theme Colors
const buttonActionColor = useMemo(() => themeColor[0] || "#5c87df", [themeColor]); const buttonActionColor = useMemo(() => themeColor[0] || "#5c87df", [themeColor]);
@ -86,34 +86,34 @@ const DoughnutGraphComponent = ({
[fontFamily, fontSizeValue, fontWeightValue] [fontFamily, fontSizeValue, fontWeightValue]
); );
// Memoize Chart Options // Memoize Chart Options
const options = useMemo( const options = useMemo(
() => ({ () => ({
responsive: true, responsive: true,
maintainAspectRatio: false, maintainAspectRatio: false,
plugins: { plugins: {
title: { title: {
display: true, display: true,
text: name, text: name,
font: chartFontStyle, font: chartFontStyle,
},
legend: {
display: false,
},
}, },
scales: { legend: {
// x: { display: false,
// ticks: {
// display: true, // This hides the x-axis labels
// },
// },
}, },
}), },
[title, chartFontStyle, name] scales: {
); // x: {
// ticks: {
// display: true, // This hides the x-axis labels
// },
// },
},
}),
[title, chartFontStyle, name]
);
// useEffect(() => {console.log(measurements); // useEffect(() => {console.log(measurements);
// },[measurements]) // },[measurements])
useEffect(() => { useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0) return; if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0) return;
@ -160,7 +160,7 @@ const DoughnutGraphComponent = ({
}; };
}, [measurements, duration, iotApiUrl]); }, [measurements, duration, iotApiUrl]);
const fetchSavedInputes = async() => { const fetchSavedInputes = async () => {
if (id !== "") { if (id !== "") {
try { try {
@ -198,7 +198,7 @@ const DoughnutGraphComponent = ({
fetchSavedInputes(); fetchSavedInputes();
} }
} }
,[chartMeasurements, chartDuration, widgetName]) , [chartMeasurements, chartDuration, widgetName])
return <Doughnut data={Object.keys(measurements).length > 0 ? chartData : defaultData} options={options} />; return <Doughnut data={Object.keys(measurements).length > 0 ? chartData : defaultData} options={options} />;
}; };

View File

@ -8,6 +8,7 @@ import useChartStore from "../../../../../store/visualization/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore";
import { getUserData } from "../../../../../functions/getUserData";
interface ChartComponentProps { interface ChartComponentProps {
id: string; id: string;
@ -48,8 +49,7 @@ const LineGraphComponent = ({
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const defaultData = { const defaultData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [ datasets: [
@ -63,7 +63,7 @@ const LineGraphComponent = ({
], ],
}; };
useEffect(() => {}, []); useEffect(() => { }, []);
// Memoize Theme Colors // Memoize Theme Colors
const buttonActionColor = useMemo( const buttonActionColor = useMemo(

View File

@ -8,6 +8,7 @@ import useChartStore from "../../../../../store/visualization/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../../functions/getUserData";
interface ChartComponentProps { interface ChartComponentProps {
id: string; id: string;
@ -47,8 +48,7 @@ const PieChartComponent = ({
const { projectId } = useParams(); const { projectId } = useParams();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const defaultData = { const defaultData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [ datasets: [
@ -62,7 +62,7 @@ const PieChartComponent = ({
], ],
}; };
useEffect(() => {}, []); useEffect(() => { }, []);
// Memoize Theme Colors // Memoize Theme Colors
const buttonActionColor = useMemo( const buttonActionColor = useMemo(

View File

@ -8,6 +8,7 @@ import useChartStore from "../../../../../store/visualization/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../../functions/getUserData";
interface ChartComponentProps { interface ChartComponentProps {
id: string; id: string;
@ -47,8 +48,7 @@ const PolarAreaGraphComponent = ({
const { projectId } = useParams(); const { projectId } = useParams();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const defaultData = { const defaultData = {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"], labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [ datasets: [
@ -62,7 +62,7 @@ const PolarAreaGraphComponent = ({
], ],
}; };
useEffect(() => {}, []); useEffect(() => { }, []);
// Memoize Theme Colors // Memoize Theme Colors
const buttonActionColor = useMemo( const buttonActionColor = useMemo(

View File

@ -8,6 +8,7 @@ import { useWidgetStore } from "../../../../../store/useWidgetStore";
import { StockIncreseIcon } from "../../../../../components/icons/RealTimeVisulationIcons"; import { StockIncreseIcon } from "../../../../../components/icons/RealTimeVisulationIcons";
import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../../functions/getUserData";
const ProgressCard1 = ({ id, title }: { id: string; title: string }) => { const ProgressCard1 = ({ id, title }: { id: string; title: string }) => {
const { const {
@ -24,8 +25,7 @@ const ProgressCard1 = ({ id, title }: { id: string; title: string }) => {
const { projectId } = useParams(); const { projectId } = useParams();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
useEffect(() => { useEffect(() => {
const socket = io(`http://${iotApiUrl}`); const socket = io(`http://${iotApiUrl}`);

View File

@ -8,6 +8,7 @@ import { useWidgetStore } from "../../../../../store/useWidgetStore";
import { StockIncreseIcon } from "../../../../../components/icons/RealTimeVisulationIcons"; import { StockIncreseIcon } from "../../../../../components/icons/RealTimeVisulationIcons";
import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore"; import { useSelectedZoneStore } from "../../../../../store/visualization/useZoneStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../../functions/getUserData";
const ProgressCard2 = ({ id, title }: { id: string; title: string }) => { const ProgressCard2 = ({ id, title }: { id: string; title: string }) => {
const { const {
@ -25,8 +26,7 @@ const ProgressCard2 = ({ id, title }: { id: string; title: string }) => {
const { projectId } = useParams(); const { projectId } = useParams();
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
useEffect(() => { useEffect(() => {
if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0) if (!iotApiUrl || !measurements || Object.keys(measurements).length === 0)

View File

@ -27,6 +27,7 @@ import Throughput from "./cards/Throughput";
import { useWidgetStore } from "../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../store/useWidgetStore";
import useChartStore from "../../../../store/visualization/useChartStore"; import useChartStore from "../../../../store/visualization/useChartStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
type WidgetData = { type WidgetData = {
id: string; id: string;
@ -78,13 +79,11 @@ export default function Dropped3dWidgets() {
const activeZoneWidgets = zoneWidgetData[selectedZone.zoneUuid] || []; const activeZoneWidgets = zoneWidgetData[selectedZone.zoneUuid] || [];
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
useEffect(() => { useEffect(() => {
if (activeModule !== "visualization") return; if (activeModule !== "visualization") return;
if (!selectedZone.zoneUuid) return; if (!selectedZone.zoneUuid) return;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
async function get3dWidgetData() { async function get3dWidgetData() {
const result = await get3dWidgetZoneData( const result = await get3dWidgetZoneData(
@ -208,9 +207,6 @@ export default function Dropped3dWidgets() {
hasEntered.current = false; hasEntered.current = false;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
const newWidget = createdWidgetRef.current; const newWidget = createdWidgetRef.current;
if (!newWidget || !widgetSelect.startsWith("ui")) return; if (!newWidget || !widgetSelect.startsWith("ui")) return;
@ -283,9 +279,7 @@ export default function Dropped3dWidgets() {
useEffect(() => { useEffect(() => {
if (!rightClickSelected) return; if (!rightClickSelected) return;
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
if (rightSelect === "Duplicate") { if (rightSelect === "Duplicate") {
async function duplicateWidget() { async function duplicateWidget() {
@ -310,7 +304,7 @@ export default function Dropped3dWidgets() {
}, },
}; };
const adding3dWidget = { const adding3dWidget = {
organization: organization, organization,
widget: newWidget, widget: newWidget,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
projectId, userId projectId, userId
@ -380,9 +374,6 @@ export default function Dropped3dWidgets() {
const [prevX, setPrevX] = useState(0); const [prevX, setPrevX] = useState(0);
useEffect(() => { useEffect(() => {
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
const handleMouseDown = (event: MouseEvent) => { const handleMouseDown = (event: MouseEvent) => {
if (!rightClickSelected || !rightSelect) return; if (!rightClickSelected || !rightSelect) return;
const selectedzoneUuid = Object.keys(zoneWidgetData).find( const selectedzoneUuid = Object.keys(zoneWidgetData).find(
@ -634,7 +625,7 @@ export default function Dropped3dWidgets() {
// } // }
// })(); // })();
let updatingPosition = { let updatingPosition = {
organization: organization, organization,
zoneUuid: selectedzoneUuid, zoneUuid: selectedzoneUuid,
id: rightClickSelected, id: rightClickSelected,
position: lastPosition, position: lastPosition,
@ -659,7 +650,7 @@ export default function Dropped3dWidgets() {
// } // }
// })(); // })();
let updatingRotation = { let updatingRotation = {
organization: organization, organization,
zoneUuid: selectedzoneUuid, zoneUuid: selectedzoneUuid,
id: rightClickSelected, id: rightClickSelected,
rotation: lastRotation, rotation: lastRotation,

View File

@ -16,6 +16,7 @@ import axios from "axios";
import io from "socket.io-client"; import io from "socket.io-client";
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/visualization/useChartStore"; import useChartStore from "../../../../../store/visualization/useChartStore";
import { getUserData } from "../../../../../functions/getUserData";
// Register ChartJS components // Register ChartJS components
ChartJS.register( ChartJS.register(
@ -67,8 +68,7 @@ const ProductionCapacity: React.FC<ProductionCapacityProps> = ({
datasets: [], datasets: [],
}); });
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
// Chart data for a week // Chart data for a week
const defaultChartData = { const defaultChartData = {
labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], // Days of the week labels: ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"], // Days of the week
@ -197,7 +197,7 @@ const ProductionCapacity: React.FC<ProductionCapacityProps> = ({
} }
}, [chartMeasurements, chartDuration, widgetName]); }, [chartMeasurements, chartDuration, widgetName]);
useEffect(() => {}, [rotation]); useEffect(() => { }, [rotation]);
return ( return (
<> <>

View File

@ -17,6 +17,7 @@ import io from "socket.io-client";
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/visualization/useChartStore"; import useChartStore from "../../../../../store/visualization/useChartStore";
import { WavyIcon } from "../../../../../components/icons/3dChartIcons"; import { WavyIcon } from "../../../../../components/icons/3dChartIcons";
import { getUserData } from "../../../../../functions/getUserData";
// Register Chart.js components // Register Chart.js components
ChartJS.register( ChartJS.register(
@ -77,8 +78,7 @@ const ReturnOfInvestment: React.FC<ReturnOfInvestmentProps> = ({
datasets: [], datasets: [],
}); });
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
// Improved sample data for the smooth curve graph (single day) // Improved sample data for the smooth curve graph (single day)
const graphData: ChartData<"line"> = { const graphData: ChartData<"line"> = {
labels: [ labels: [
@ -250,9 +250,8 @@ const ReturnOfInvestment: React.FC<ReturnOfInvestmentProps> = ({
> >
<div <div
className={`returnOfInvestment card ${ className={`returnOfInvestment card ${selectedChartId?.id === id ? "activeChart" : ""
selectedChartId?.id === id ? "activeChart" : "" }`}
}`}
onClick={() => setSelectedChartId({ id: id, type: type })} onClick={() => setSelectedChartId({ id: id, type: type })}
onContextMenu={onContextMenu} onContextMenu={onContextMenu}
> >

View File

@ -5,6 +5,7 @@ import axios from "axios";
import io from "socket.io-client"; import io from "socket.io-client";
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/visualization/useChartStore"; import useChartStore from "../../../../../store/visualization/useChartStore";
import { getUserData } from "../../../../../functions/getUserData";
// import image from "../../../../assets/image/temp/image.png"; // import image from "../../../../assets/image/temp/image.png";
interface StateWorkingProps { interface StateWorkingProps {
@ -38,8 +39,7 @@ const StateWorking: React.FC<StateWorkingProps> = ({
const [name, setName] = useState("Widget"); const [name, setName] = useState("Widget");
const [datas, setDatas] = useState<any>({}); const [datas, setDatas] = useState<any>({});
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
// const datas = [ // const datas = [
// { key: "Oil Tank:", value: "24/341" }, // { key: "Oil Tank:", value: "24/341" },
// { key: "Oil Refin:", value: 36.023 }, // { key: "Oil Refin:", value: 36.023 },
@ -124,16 +124,15 @@ const StateWorking: React.FC<StateWorkingProps> = ({
// sprite={true} // sprite={true}
prepend prepend
distanceFactor={20} distanceFactor={20}
// style={{ // style={{
// transform: transformStyle.transform, // transform: transformStyle.transform,
// transformStyle: "preserve-3d", // transformStyle: "preserve-3d",
// transition: "transform 0.1s ease-out", // transition: "transform 0.1s ease-out",
// }} // }}
> >
<div <div
className={`stateWorking-wrapper card ${ className={`stateWorking-wrapper card ${selectedChartId?.id === id ? "activeChart" : ""
selectedChartId?.id === id ? "activeChart" : "" }`}
}`}
onClick={() => setSelectedChartId({ id: id, type: type })} onClick={() => setSelectedChartId({ id: id, type: type })}
onContextMenu={onContextMenu} onContextMenu={onContextMenu}
> >

View File

@ -19,6 +19,7 @@ import io from "socket.io-client";
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import useChartStore from "../../../../../store/visualization/useChartStore"; import useChartStore from "../../../../../store/visualization/useChartStore";
import { ThroughputIcon } from "../../../../../components/icons/3dChartIcons"; import { ThroughputIcon } from "../../../../../components/icons/3dChartIcons";
import { getUserData } from "../../../../../functions/getUserData";
// Register Chart.js components // Register Chart.js components
ChartJS.register( ChartJS.register(
@ -80,8 +81,7 @@ const Throughput: React.FC<ThroughputProps> = ({
datasets: [], datasets: [],
}); });
const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL; const iotApiUrl = process.env.REACT_APP_IOT_SOCKET_SERVER_URL;
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
@ -225,7 +225,7 @@ const Throughput: React.FC<ThroughputProps> = ({
zIndexRange={[1, 0]} zIndexRange={[1, 0]}
prepend prepend
distanceFactor={20} distanceFactor={20}
// sprite={true} // sprite={true}
> >
<div <div
className={`throughput-wrapper card ${selectedChartId?.id === id ? "activeChart" : "" className={`throughput-wrapper card ${selectedChartId?.id === id ? "activeChart" : ""

View File

@ -19,6 +19,7 @@ import { useSocketStore } from "../../../../store/builder/store";
import { usePlayButtonStore } from "../../../../store/usePlayButtonStore"; import { usePlayButtonStore } from "../../../../store/usePlayButtonStore";
import { useSelectedZoneStore } from "../../../../store/visualization/useZoneStore"; import { useSelectedZoneStore } from "../../../../store/visualization/useZoneStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
interface DraggingState { interface DraggingState {
zone: string; zone: string;
index: number; index: number;
@ -78,7 +79,7 @@ const DroppedObjects: React.FC = () => {
const chartWidget = useRef<HTMLDivElement>(null); const chartWidget = useRef<HTMLDivElement>(null);
const kebabRef = useRef<HTMLDivElement>(null); const kebabRef = useRef<HTMLDivElement>(null);
const { userId, organization, email } = getUserData();
// Clean up animation frame on unmount // Clean up animation frame on unmount
useEffect(() => { useEffect(() => {
return () => { return () => {
@ -112,22 +113,19 @@ const DroppedObjects: React.FC = () => {
function handleDuplicate(zoneName: string, index: number) { function handleDuplicate(zoneName: string, index: number) {
setOpenKebabId(null); setOpenKebabId(null);
duplicateObject(zoneName, index,projectId); // Call the duplicateObject method from the store duplicateObject(zoneName, index, projectId); // Call the duplicateObject method from the store
setSelectedChartId(null); setSelectedChartId(null);
} }
async function handleDelete(zoneName: string, id: string) { async function handleDelete(zoneName: string, id: string) {
try { try {
setSelectedChartId(null); setSelectedChartId(null);
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
let deleteFloatingWidget = { let deleteFloatingWidget = {
floatWidgetID: id, floatWidgetID: id,
organization: organization, organization,
zoneUuid: zone.zoneUuid, zoneUuid: zone.zoneUuid,
userId,projectId userId, projectId
}; };
if (visualizationSocket) { if (visualizationSocket) {
@ -296,8 +294,6 @@ const DroppedObjects: React.FC = () => {
try { try {
// Save to backend // Save to backend
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const response = await addingFloatingWidgets( const response = await addingFloatingWidgets(
zone.zoneUuid, zone.zoneUuid,
organization, organization,
@ -432,10 +428,8 @@ const DroppedObjects: React.FC = () => {
}; };
// Save to backend // Save to backend
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
let updateFloatingWidget = { let updateFloatingWidget = {
organization: organization, organization,
widget: { widget: {
...zone.objects[draggingIndex.index], ...zone.objects[draggingIndex.index],
position: boundedPosition, position: boundedPosition,
@ -491,45 +485,40 @@ const DroppedObjects: React.FC = () => {
{zone?.objects?.map((obj, index) => { {zone?.objects?.map((obj, index) => {
const topPosition = const topPosition =
typeof obj?.position?.top === "number" typeof obj?.position?.top === "number"
? `calc(${obj?.position?.top}px + ${ ? `calc(${obj?.position?.top}px + ${isPlaying && selectedZone?.activeSides?.includes("top")
isPlaying && selectedZone?.activeSides?.includes("top") ? `${heightMultiplier - 55}px`
? `${heightMultiplier - 55}px` : "0px"
: "0px" })`
})`
: "auto"; : "auto";
const leftPosition = const leftPosition =
typeof obj?.position?.left === "number" typeof obj?.position?.left === "number"
? `calc(${obj?.position?.left}px + ${ ? `calc(${obj?.position?.left}px + ${isPlaying && selectedZone?.activeSides?.includes("left")
isPlaying && selectedZone?.activeSides?.includes("left") ? `${widthMultiplier - 150}px`
? `${widthMultiplier - 150}px` : "0px"
: "0px" })`
})`
: "auto"; : "auto";
const rightPosition = const rightPosition =
typeof obj?.position?.right === "number" typeof obj?.position?.right === "number"
? `calc(${obj?.position?.right}px + ${ ? `calc(${obj?.position?.right}px + ${isPlaying && selectedZone?.activeSides?.includes("right")
isPlaying && selectedZone?.activeSides?.includes("right") ? `${widthMultiplier - 150}px`
? `${widthMultiplier - 150}px` : "0px"
: "0px" })`
})`
: "auto"; : "auto";
const bottomPosition = const bottomPosition =
typeof obj?.position?.bottom === "number" typeof obj?.position?.bottom === "number"
? `calc(${obj?.position?.bottom}px + ${ ? `calc(${obj?.position?.bottom}px + ${isPlaying && selectedZone?.activeSides?.includes("bottom")
isPlaying && selectedZone?.activeSides?.includes("bottom") ? `${heightMultiplier - 55}px`
? `${heightMultiplier - 55}px` : "0px"
: "0px" })`
})`
: "auto"; : "auto";
return ( return (
<div <div
key={`${obj.id}-${index}`} key={`${obj.id}-${index}`}
className={`${obj.className} ${ className={`${obj.className} ${selectedChartId?.id === obj.id && "activeChart"
selectedChartId?.id === obj.id && "activeChart" } `}
} `}
ref={chartWidget} ref={chartWidget}
style={{ style={{
position: "absolute", position: "absolute",
@ -538,9 +527,8 @@ const DroppedObjects: React.FC = () => {
right: rightPosition, right: rightPosition,
bottom: bottomPosition, bottom: bottomPosition,
pointerEvents: isPlaying ? "none" : "auto", pointerEvents: isPlaying ? "none" : "auto",
minHeight: `${ minHeight: `${obj.className === "warehouseThroughput" && "150px !important"
obj.className === "warehouseThroughput" && "150px !important" } `,
} `,
}} }}
onPointerDown={(event) => { onPointerDown={(event) => {
setSelectedChartId(obj); setSelectedChartId(obj);

View File

@ -5,14 +5,14 @@ import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios"; import axios from "axios";
import io from "socket.io-client"; import io from "socket.io-client";
import { usePlayButtonStore } from "../../../../../store/usePlayButtonStore"; import { usePlayButtonStore } from "../../../../../store/usePlayButtonStore";
import { getUserData } from "../../../../../functions/getUserData";
const FleetEfficiencyComponent = ({ object }: any) => { const FleetEfficiencyComponent = ({ object }: any) => {
const [progress, setProgress] = useState<any>(0); const [progress, setProgress] = useState<any>(0);
const [measurements, setmeasurements] = useState<any>({}); const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h"); const [duration, setDuration] = useState("1h");
const [name, setName] = useState(object.header ? object.header : ""); const [name, setName] = useState(object.header ? object.header : "");
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const { header, flotingDuration, flotingMeasurements } = useChartStore(); const { header, flotingDuration, flotingMeasurements } = useChartStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
const { isPlaying } = usePlayButtonStore(); const { isPlaying } = usePlayButtonStore();

View File

@ -10,15 +10,14 @@ import {
GlobeIcon, GlobeIcon,
WalletIcon, WalletIcon,
} from "../../../../../components/icons/3dChartIcons"; } from "../../../../../components/icons/3dChartIcons";
import { getUserData } from "../../../../../functions/getUserData";
const TotalCardComponent = ({ object }: any) => { const TotalCardComponent = ({ object }: any) => {
const [progress, setProgress] = useState<any>(0); const [progress, setProgress] = useState<any>(0);
const [measurements, setmeasurements] = useState<any>({}); const [measurements, setmeasurements] = useState<any>({});
const [duration, setDuration] = useState("1h"); const [duration, setDuration] = useState("1h");
const [name, setName] = useState(object.header ? object.header : ""); const [name, setName] = useState(object.header ? object.header : "");
const { userName, userId, organization, email } = getUserData();
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const { header, flotingDuration, flotingMeasurements } = useChartStore(); const { header, flotingDuration, flotingMeasurements } = useChartStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();
@ -70,7 +69,7 @@ const TotalCardComponent = ({ object }: any) => {
} else { } else {
echo.error("Failed to fetch saved inputs"); echo.error("Failed to fetch saved inputs");
} }
} catch (error) {} } catch (error) { }
} }
}; };

View File

@ -4,6 +4,7 @@ import useChartStore from "../../../../../store/visualization/useChartStore";
import { useWidgetStore } from "../../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../../store/useWidgetStore";
import axios from "axios"; import axios from "axios";
import io from "socket.io-client"; import io from "socket.io-client";
import { getUserData } from "../../../../../functions/getUserData";
const WarehouseThroughputComponent = ({ object }: any) => { const WarehouseThroughputComponent = ({ object }: any) => {
const [measurements, setmeasurements] = useState<any>({}); const [measurements, setmeasurements] = useState<any>({});
@ -16,8 +17,7 @@ const WarehouseThroughputComponent = ({ object }: any) => {
labels: [], labels: [],
datasets: [], datasets: [],
}); });
const email = localStorage.getItem("email") || ""; const { userName, userId, organization, email } = getUserData();
const organization = email?.split("@")[1]?.split(".")[0];
const { header, flotingDuration, flotingMeasurements } = useChartStore(); const { header, flotingDuration, flotingMeasurements } = useChartStore();
const { selectedChartId } = useWidgetStore(); const { selectedChartId } = useWidgetStore();

View File

@ -7,6 +7,7 @@ import {
import { AddIcon } from "../../../../components/icons/ExportCommonIcons"; import { AddIcon } from "../../../../components/icons/ExportCommonIcons";
import { useSocketStore } from "../../../../store/builder/store"; import { useSocketStore } from "../../../../store/builder/store";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
// Define the type for `Side` // Define the type for `Side`
type Side = "top" | "bottom" | "left" | "right"; type Side = "top" | "bottom" | "left" | "right";
@ -70,6 +71,8 @@ const AddButtons: React.FC<ButtonsProps> = ({
}) => { }) => {
const { visualizationSocket } = useSocketStore(); const { visualizationSocket } = useSocketStore();
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
// Function to toggle visibility of a panel // Function to toggle visibility of a panel
const toggleVisibility = (side: Side) => { const toggleVisibility = (side: Side) => {
@ -97,9 +100,6 @@ const AddButtons: React.FC<ButtonsProps> = ({
// Function to toggle lock/unlock a panel // Function to toggle lock/unlock a panel
const toggleLockPanel = async (side: Side) => { const toggleLockPanel = async (side: Side) => {
const email = localStorage.getItem("email") ?? "";
const organization = email?.split("@")[1]?.split(".")[0]; // Fallback value
const userId = localStorage.getItem("userId");
//add api //add api
const newLockedPanels = selectedZone.lockedPanels.includes(side) const newLockedPanels = selectedZone.lockedPanels.includes(side)
? selectedZone.lockedPanels.filter((panel) => panel !== side) ? selectedZone.lockedPanels.filter((panel) => panel !== side)
@ -111,7 +111,7 @@ const AddButtons: React.FC<ButtonsProps> = ({
}; };
let lockedPanel = { let lockedPanel = {
organization: organization, organization,
lockedPanel: newLockedPanels, lockedPanel: newLockedPanels,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
userId, projectId userId, projectId
@ -133,12 +133,10 @@ const AddButtons: React.FC<ButtonsProps> = ({
) )
return; return;
const email = localStorage.getItem("email") ?? "";
const organization = email?.split("@")[1]?.split(".")[0]; // Fallback value
const userId = localStorage.getItem("userId");
let clearPanel = { let clearPanel = {
organization: organization, organization,
panelName: side, panelName: side,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
userId, projectId userId, projectId
@ -169,10 +167,6 @@ const AddButtons: React.FC<ButtonsProps> = ({
setTimeout(() => { setTimeout(() => {
console.log("Removing after wait..."); console.log("Removing after wait...");
const email = localStorage.getItem("email") ?? "";
const organization = email?.split("@")[1]?.split(".")[0] ?? "";
const userId = localStorage.getItem("userId");
// Remove widgets for that side // Remove widgets for that side
const cleanedWidgets = selectedZone.widgets.filter( const cleanedWidgets = selectedZone.widgets.filter(
(widget) => widget.panel !== side (widget) => widget.panel !== side
@ -215,10 +209,6 @@ const AddButtons: React.FC<ButtonsProps> = ({
} else { } else {
// Panel does not exist: Add it // Panel does not exist: Add it
try { try {
const email = localStorage.getItem("email") ?? "";
const organization = email?.split("@")[1]?.split(".")[0] ?? "";
const userId = localStorage.getItem("userId");
const newActiveSides = selectedZone.activeSides.includes(side) const newActiveSides = selectedZone.activeSides.includes(side)
? [...selectedZone.activeSides] ? [...selectedZone.activeSides]
: [...selectedZone.activeSides, side]; : [...selectedZone.activeSides, side];

View File

@ -6,6 +6,7 @@ import { usePlayButtonStore } from "../../../../store/usePlayButtonStore";
import { useWidgetStore } from "../../../../store/useWidgetStore"; import { useWidgetStore } from "../../../../store/useWidgetStore";
import { DraggableWidget } from "../2d/DraggableWidget"; import { DraggableWidget } from "../2d/DraggableWidget";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../../functions/getUserData";
type Side = "top" | "bottom" | "left" | "right"; type Side = "top" | "bottom" | "left" | "right";
@ -69,6 +70,8 @@ const Panel: React.FC<PanelProps> = ({
height: 0, height: 0,
}); });
const { projectId } = useParams(); const { projectId } = useParams();
const { userId, organization, email } = getUserData();
// Track canvas dimensions // Track canvas dimensions
useEffect(() => { useEffect(() => {
@ -182,9 +185,7 @@ const Panel: React.FC<PanelProps> = ({
// Add widget to panel // Add widget to panel
const addWidgetToPanel = async (asset: any, panel: Side) => { const addWidgetToPanel = async (asset: any, panel: Side) => {
const email = localStorage.getItem("email") ?? "";
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
const newWidget = { const newWidget = {
...asset, ...asset,
@ -193,7 +194,7 @@ const Panel: React.FC<PanelProps> = ({
}; };
let addWidget = { let addWidget = {
organization: organization, organization,
zoneUuid: selectedZone.zoneUuid, zoneUuid: selectedZone.zoneUuid,
widget: newWidget, widget: newWidget,
projectId, userId projectId, userId

View File

@ -15,6 +15,7 @@ import {
import { InfoIcon } from "../../../components/icons/ExportCommonIcons"; import { InfoIcon } from "../../../components/icons/ExportCommonIcons";
import { usePlayButtonStore } from "../../../store/usePlayButtonStore"; import { usePlayButtonStore } from "../../../store/usePlayButtonStore";
import { useParams } from "react-router-dom"; import { useParams } from "react-router-dom";
import { getUserData } from "../../../functions/getUserData";
// Define the type for `Side` // Define the type for `Side`
type Side = "top" | "bottom" | "left" | "right"; type Side = "top" | "bottom" | "left" | "right";
@ -91,7 +92,7 @@ const DisplayZone: React.FC<DisplayZoneProps> = ({
const [showRightArrow, setShowRightArrow] = useState(false); const [showRightArrow, setShowRightArrow] = useState(false);
const { floatingWidget, setFloatingWidget } = useFloatingWidget(); const { floatingWidget, setFloatingWidget } = useFloatingWidget();
const { isPlaying } = usePlayButtonStore(); const { isPlaying } = usePlayButtonStore();
const { userName, userId, organization, email } = getUserData();
const { setSelectedChartId } = useWidgetStore(); const { setSelectedChartId } = useWidgetStore();
const { projectId } = useParams(); const { projectId } = useParams();
// Function to calculate overflow state // Function to calculate overflow state
@ -174,8 +175,6 @@ const DisplayZone: React.FC<DisplayZoneProps> = ({
return; return;
} }
// setSelectedChartId(null); // setSelectedChartId(null);
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
let response = await getSelect2dZoneData(zoneUuid, organization, projectId); let response = await getSelect2dZoneData(zoneUuid, organization, projectId);
// console.log('response2d: ', response); // console.log('response2d: ', response);
@ -212,9 +211,9 @@ const DisplayZone: React.FC<DisplayZoneProps> = ({
ref={containerRef} ref={containerRef}
id="zone-container" id="zone-container"
className={`zone-container ${selectedZone?.activeSides?.includes("bottom") && className={`zone-container ${selectedZone?.activeSides?.includes("bottom") &&
!hiddenPanels[selectedZone.zoneUuid]?.includes("bottom") !hiddenPanels[selectedZone.zoneUuid]?.includes("bottom")
? "bottom" ? "bottom"
: "" : ""
} ${isPlaying ? "visualization-playing" : ""}`} } ${isPlaying ? "visualization-playing" : ""}`}
> >
{/* Left Arrow */} {/* Left Arrow */}

View File

@ -5,7 +5,7 @@ import {
import DashboardHome from "../components/Dashboard/DashboardHome"; import DashboardHome from "../components/Dashboard/DashboardHome";
import DashboardProjects from "../components/Dashboard/DashboardProjects"; import DashboardProjects from "../components/Dashboard/DashboardProjects";
import DashboardTrash from "../components/Dashboard/DashboardTrash"; import DashboardTrash from "../components/Dashboard/DashboardTrash";
import { getUserData } from "../components/Dashboard/functions/getUserData"; import { getUserData } from "../functions/getUserData";
import SidePannel from "../components/Dashboard/SidePannel"; import SidePannel from "../components/Dashboard/SidePannel";
import DashboardTutorial from "../components/Dashboard/DashboardTutorial"; import DashboardTutorial from "../components/Dashboard/DashboardTutorial";
import { useProductStore } from "../store/simulation/useProductStore"; import { useProductStore } from "../store/simulation/useProductStore";

View File

@ -34,6 +34,7 @@ import { setFloorItemApi } from "../services/factoryBuilder/assest/floorAsset/se
import { useAssetsStore } from "../store/builder/useAssetStore"; import { useAssetsStore } from "../store/builder/useAssetStore";
import ComparisonSceneProvider from "../components/layout/scenes/ComparisonSceneProvider"; import ComparisonSceneProvider from "../components/layout/scenes/ComparisonSceneProvider";
import MainSceneProvider from "../components/layout/scenes/MainSceneProvider"; import MainSceneProvider from "../components/layout/scenes/MainSceneProvider";
import { getUserData } from "../functions/getUserData";
const Project: React.FC = () => { const Project: React.FC = () => {
let navigate = useNavigate(); let navigate = useNavigate();
@ -49,31 +50,22 @@ const Project: React.FC = () => {
const { setProducts } = useProductStore(); const { setProducts } = useProductStore();
const { projectId } = useParams(); const { projectId } = useParams();
const { setProjectName } = useProjectName(); const { setProjectName } = useProjectName();
const { userId, email, organization, userName } = getUserData();
const generateThumbnail = async () => { const generateThumbnail = async () => {
const email = localStorage.getItem("email");
const userId = localStorage.getItem("userId");
try { try {
if (!email || !userId) { if (!email || !userId) {
console.error("User data not found in localStorage"); console.error("User data not found in localStorage");
return; return;
} }
const emailParts = email.split("@");
if (emailParts.length < 2) {
console.error("Invalid email format");
return;
}
const domainParts = emailParts[1].split(".");
const Organization = domainParts[0];
const projects = await getAllProjects( const projects = await getAllProjects(
userId, Organization userId, organization
); );
const filterProject = projects?.Projects.find((val: any) => val.projectUuid === projectId || val._id const filterProject = projects?.Projects.find((val: any) => val.projectUuid === projectId || val._id
=== projectId) === projectId)
const viewedProject = await viewProject( const viewedProject = await viewProject(
Organization, organization,
filterProject._id, filterProject._id,
userId, userId,
); );
@ -106,17 +98,14 @@ const Project: React.FC = () => {
setZones([]); setZones([]);
setProducts([]); setProducts([]);
setActiveModule("builder"); setActiveModule("builder");
const email = localStorage.getItem("email");
if (email) { if (email) {
const Organization = email.split("@")[1].split(".")[0];
const token = localStorage.getItem("token"); const token = localStorage.getItem("token");
if (token) { if (token) {
useSocketStore.getState().initializeSocket(email, Organization, token); useSocketStore.getState().initializeSocket(email, organization, token);
} }
const name = localStorage.getItem("userName"); if (organization && userName) {
if (Organization && name) { setOrganization(organization);
setOrganization(Organization); setUserName(userName);
setUserName(name);
} }
echo.success("Log in successful"); echo.success("Log in successful");
} else { } else {

View File

@ -11,7 +11,7 @@ import { signInApi } from "../services/factoryBuilder/signInSignUp/signInApi";
import { signUpApi } from "../services/factoryBuilder/signInSignUp/signUpApi"; import { signUpApi } from "../services/factoryBuilder/signInSignUp/signUpApi";
import FingerprintJS from "@fingerprintjs/fingerprintjs"; import FingerprintJS from "@fingerprintjs/fingerprintjs";
import { recentlyViewed } from "../services/dashboard/recentlyViewed"; import { recentlyViewed } from "../services/dashboard/recentlyViewed";
import { getUserData } from "../components/Dashboard/functions/getUserData"; import { getUserData } from "../functions/getUserData";
const UserAuth: React.FC = () => { const UserAuth: React.FC = () => {
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
@ -56,16 +56,16 @@ const UserAuth: React.FC = () => {
localStorage.setItem("refreshToken", res.message.refreshToken); localStorage.setItem("refreshToken", res.message.refreshToken);
try { try {
// console.log('res.message.userId: ', res.message.userId);
// console.log('organization: ', organization);
const projects = await recentlyViewed(organization, res.message.userId); const projects = await recentlyViewed(organization, res.message.userId);
// console.log('projects: ', projects);
if (res.message.isShare) { if (res.message.isShare) {
if (Object.values(projects.RecentlyViewed).length > 0) { if (Object.values(projects.RecentlyViewed).length > 0) {
const firstId = (Object.values(projects?.RecentlyViewed || {})[0] as any)?._id; const firstId = (Object.values(projects?.RecentlyViewed || {})[0] as any)?._id;
setLoadingProgress(1) if (Object.values(projects?.RecentlyViewed).filter((val: any) => val._id == firstId)) {
navigate(`/${firstId}`) setLoadingProgress(1)
navigate(`/${firstId}`)
} else {
navigate("/Dashboard")
}
} else { } else {
setLoadingProgress(1); setLoadingProgress(1);
navigate("/Dashboard"); navigate("/Dashboard");

View File

@ -1,6 +1,7 @@
import { create } from "zustand"; import { create } from "zustand";
import { useSocketStore } from "../builder/store"; import { useSocketStore } from "../builder/store";
import useChartStore from "./useChartStore"; import useChartStore from "./useChartStore";
import { getUserData } from "../../functions/getUserData";
type DroppedObject = { type DroppedObject = {
className: string; className: string;
@ -38,7 +39,11 @@ type DroppedObjectsState = {
} }
) => void; ) => void;
deleteObject: (zoneName: string, id: string) => void; // Add this line deleteObject: (zoneName: string, id: string) => void; // Add this line
duplicateObject: (zoneName: string, index: number, projectId?: string) => void; // Add this line duplicateObject: (
zoneName: string,
index: number,
projectId?: string
) => void; // Add this line
}; };
export const useDroppedObjectsStore = create<DroppedObjectsState>((set) => ({ export const useDroppedObjectsStore = create<DroppedObjectsState>((set) => ({
@ -47,7 +52,11 @@ export const useDroppedObjectsStore = create<DroppedObjectsState>((set) => ({
setZone: (zoneName: string, zoneUuid: string) => setZone: (zoneName: string, zoneUuid: string) =>
set((state) => ({ set((state) => ({
zones: { zones: {
[zoneName]: state.zones[zoneName] || { zoneName, zoneUuid, objects: [] }, // Keep existing zone if it exists [zoneName]: state.zones[zoneName] || {
zoneName,
zoneUuid,
objects: [],
}, // Keep existing zone if it exists
}, },
})), })),
@ -92,7 +101,11 @@ export const useDroppedObjectsStore = create<DroppedObjectsState>((set) => ({
}, },
}; };
}), }),
duplicateObject: async (zoneName: string, index: number, projectId?: string) => { duplicateObject: async (
zoneName: string,
index: number,
projectId?: string
) => {
const state = useDroppedObjectsStore.getState(); // Get the current state const state = useDroppedObjectsStore.getState(); // Get the current state
const zone = state.zones[zoneName]; const zone = state.zones[zoneName];
let socketState = useSocketStore.getState(); let socketState = useSocketStore.getState();
@ -100,16 +113,13 @@ export const useDroppedObjectsStore = create<DroppedObjectsState>((set) => ({
let visualizationSocket = socketState.visualizationSocket; let visualizationSocket = socketState.visualizationSocket;
let iotMeasurements = iotData.flotingMeasurements; let iotMeasurements = iotData.flotingMeasurements;
let iotDuration = iotData.flotingDuration; let iotDuration = iotData.flotingDuration;
let iotHeader = iotData.header let iotHeader = iotData.header;
if (!zone) return; if (!zone) return;
const originalObject = zone.objects[index]; const originalObject = zone.objects[index];
if (!originalObject) return; if (!originalObject) return;
const { userId, organization, email } = getUserData();
const email = localStorage.getItem("email") || "";
const organization = email?.split("@")[1]?.split(".")[0];
const userId = localStorage.getItem("userId");
// Create a shallow copy of the object with a unique ID and slightly adjusted position // Create a shallow copy of the object with a unique ID and slightly adjusted position
const duplicatedObject: DroppedObject = { const duplicatedObject: DroppedObject = {
@ -135,12 +145,12 @@ export const useDroppedObjectsStore = create<DroppedObjectsState>((set) => ({
console.log("duplicated object", duplicatedObject); console.log("duplicated object", duplicatedObject);
let duplicateFloatingWidget = { let duplicateFloatingWidget = {
organization: organization, organization,
widget: duplicatedObject, widget: duplicatedObject,
zoneUuid: zone.zoneUuid, zoneUuid: zone.zoneUuid,
index: index, index: index,
projectId, userId projectId,
userId,
}; };
if (visualizationSocket) { if (visualizationSocket) {