merged with main branch to clear the testing commits

This commit is contained in:
2025-06-02 11:22:06 +05:30
107 changed files with 1344 additions and 2364 deletions

View File

@@ -1,50 +1,56 @@
let url_Backend_dwinzoMajor = "http://192.168.0.110:3503";
//Login Api
export const createCamera = async (userId:string, position:Object) => {
try {
const response = await fetch(`${url_Backend_dwinzoMajor}/api/v1/createCamera`, {
export const createCamera = async (userId: string, position: Object) => {
try {
const response = await fetch(
`${url_Backend_dwinzoMajor}/api/v1/createCamera`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ userId, position }),
});
if (!response.ok) {
throw new Error("Failed to create Camera");
}
const result = await response.json();
return result;
} catch (error) {
if (error instanceof Error) {
throw new Error(error.message); // Now TypeScript knows `error` is an instance of `Error`
} else {
throw new Error("An unknown error occurred");
}
}
};
);
export const getCamera = async (userId:string) => {
try {
const response = await fetch(`${url_Backend_dwinzoMajor}/api/v1/getCamera/${userId}`, {
if (!response.ok) {
throw new Error("Failed to create Camera");
}
const result = await response.json();
return result;
} catch (error) {
if (error instanceof Error) {
throw new Error(error.message);
} else {
throw new Error("An unknown error occurred");
}
}
};
export const getCamera = async (userId: string) => {
try {
const response = await fetch(
`${url_Backend_dwinzoMajor}/api/v1/getCamera/${userId}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
},
});
if (!response.ok) {
throw new Error("Failed to get Camera");
}
const result = await response.json();
return result;
} catch (error) {
if (error instanceof Error) {
throw new Error(error.message); // Now TypeScript knows `error` is an instance of `Error`
} else {
throw new Error("An unknown error occurred");
}
);
if (!response.ok) {
throw new Error("Failed to get Camera");
}
};
const result = await response.json();
return result;
} catch (error) {
if (error instanceof Error) {
throw new Error(error.message);
} else {
throw new Error("An unknown error occurred");
}
}
};

View File

@@ -7,20 +7,19 @@ ENV NODE_ENV = development
WORKDIR /usr/src/app
RUN npm install -g tsx
RUN npm install -g tsx --ignore-scripts
COPY package.json /usr/src/app/package.json
COPY package.json ./
COPY package-lock.json ./
RUN npm install --ignore-scripts
# COPY package-lock.json /usr/src/app/package-lock.json
RUN addgroup -S appgroup && \
adduser -S appuser -G appgroup && \
chown -R appuser:appgroup /usr/src/app
RUN npm install
# Run the application as a non-root user.
USER root
# Copy the rest of the source files into the image.
# Switch to non-root user
USER appuser
COPY . .

View File

@@ -8,5 +8,4 @@ router.patch(
AssetsFloorService.updateAssetPositionRotation
);
router.patch("/eventDataUpdate", AssetsFloorService.replaceEventDatas);
// router.get("/pointData/:modelfileID/:organization", AssetsFloorService.gettypePoints);
export default router;

View File

@@ -1,11 +1,10 @@
import express from "express";
import { FloorItems } from "../controller/assets/flooritem-Services.ts";
import { AssetsFloorService } from "../controller/simulation/assetsFloorservice.ts";
import express from 'express';
import { FloorItems } from '../controller/assets/flooritem-Services.ts';
import { AssetsFloorService } from '../controller/simulation/assetsFloorservice.ts';
const router = express.Router();
router.post("/setfloorItems", FloorItems.setFloorItems);
router.get("/findfloorItems/:organization", FloorItems.getFloorItems);
// router.delete('/deletefloorItem',floorItems.deleteFloorItems)
router.delete("/deletefloorItem", AssetsFloorService.deleteFloorItems);
router.post('/setfloorItems',FloorItems.setFloorItems)
router.get('/findfloorItems/:organization',FloorItems.getFloorItems)
router.delete('/deletefloorItem',AssetsFloorService.deleteFloorItems)
export default router;

View File

@@ -1,12 +1,13 @@
import express from "express";
import { Lines } from "../controller/lines/line-Services.ts";
import express from 'express';
import { Lines } from '../controller/lines/line-Services.ts';
const router = express.Router();
router.post("/setLine", Lines.setLines);
router.post("/updatePoint", Lines.updateLines);
router.get("/findLines/:organization", Lines.getLines);
router.delete("/deleteLine", Lines.deleteLineItems);
router.delete("/deletePoint", Lines.deleteLinPoiteItems);
router.post("/deleteLayer", Lines.deleteLayer);
router.post('/setLine',Lines.setLines)
router.post('/updatePoint',Lines.updateLines)
router.get('/findLines/:organization',Lines.getLines)
router.delete('/deleteLine',Lines.deleteLineItems)
router.delete('/deletePoint',Lines.deleteLinPoiteItems)
router.post('/deleteLayer',Lines.deleteLayer)
export default router;

View File

@@ -138,5 +138,4 @@ router.post("/panel/save", PanelService.AddPanel);
router.patch("/panel/delete", PanelService.deletePanel);
router.patch("/clearpanel", PanelService.clearPanel);
// router.get("/zone/:sceneID", Zoneservice.allZones);
export default router;

View File

@@ -1,13 +1,10 @@
import * as express from "express";
import { ProductFlowservice } from "../controller/simulation/productService.ts";
import { ProductFlowService } from "../controller/simulation/productService.ts";
const productRouter = express.Router();
productRouter.post("/UpsertProductOrEvent", ProductFlowservice.productAdd);
productRouter.get("/productData", ProductFlowservice.getProductDatas);
productRouter.patch("/EventDataDelete", ProductFlowservice.EventDataDelete);
productRouter.patch("/productDataDelete", ProductFlowservice.productDataDelete);
productRouter.get(
"/AllProducts/:organization",
ProductFlowservice.AllProductDatas
);
productRouter.patch("/productRename", ProductFlowservice.productRename);
productRouter.post("/UpsertProductOrEvent", ProductFlowService.productAdd);
productRouter.get("/productData", ProductFlowService.getProductDatas);
productRouter.patch("/EventDataDelete", ProductFlowService.EventDataDelete);
productRouter.patch("/productDataDelete", ProductFlowService.productDataDelete);
productRouter.get("/AllProducts/:organization", ProductFlowService.AllProductDatas);
productRouter.patch("/productRename", ProductFlowService.productRename);
export default productRouter;

View File

@@ -7,6 +7,6 @@ router.post("/TemplatetoZone", TemplateService.AddToZone);
router.patch(
"/TemplateDelete/:templateID/:organization",
TemplateService.Deletezone
); //delete zone
);
export default router;

View File

@@ -1,9 +1,10 @@
import express from "express";
import { User } from "../controller/user-Controller.ts";
import express from 'express';
import { User } from '../controller/user-Controller.ts';
const router = express.Router();
router.post("/signup", User.signup);
router.post("/login", User.login);
router.post('/signup',User.signup)
router.post('/login',User.login)
export default router;

View File

@@ -1,9 +1,10 @@
import express from "express";
import { WallItems } from "../controller/assets/wallitem-Services.ts";
import express from 'express';
import { WallItems } from '../controller/assets/wallitem-Services.ts';
const router = express.Router();
router.post("/setWallItems", WallItems.setWallItems);
router.get("/findWallItems/:organization", WallItems.getWallItems);
router.delete("/deleteWallItem", WallItems.deleteWallItems);
router.post('/setWallItems',WallItems.setWallItems)
router.get('/findWallItems/:organization',WallItems.getWallItems)
router.delete('/deleteWallItem',WallItems.deleteWallItems)
export default router;

View File

@@ -1,7 +1,5 @@
import * as express from "express";
import { ZoneService } from "../controller/lines/zoneService.ts";
import { zone } from "../controller/lines/zone-Services.ts";
const router = express.Router();
/**
* @swagger
@@ -247,7 +245,7 @@ const router = express.Router();
* type: string
* example: "Internal server error"
*/
router.post("/zone/save", ZoneService.addandUpdateZone); //Zone create and update for the points
router.post("/zone/save", ZoneService.addandUpdateZone);
/**
* @swagger
@@ -538,8 +536,7 @@ router.get("/A_zone/:zoneId/:organization", ZoneService.ZoneData);
* type: string
* example: "Internal Server Error"
*/
router.patch("/zone/:zoneId", ZoneService.deleteAZone); //delete Zone
router.patch("/zones/lockedPanels", ZoneService.lockedPanel);
router.patch("/zone/:zoneId", ZoneService.deleteAZone);
router.get("/findZones/:organization", zone.getZones);
router.patch("/zones/lockedPanels", ZoneService.lockedPanel);
export default router;

View File

@@ -67,7 +67,6 @@ export const GetProjects = async (
): Promise<void> => {
try {
const { userId, organization, role } = req.user || {};
// const { userId, organization } = req.params;
if (!userId || !organization || !role) {
res.status(400).json({
message: "All fields are required",
@@ -106,7 +105,6 @@ export const RemoveProject = async (
): Promise<void> => {
try {
const { projectId } = req.params;
// const { organization, userId } = req.body;
const { organization, userId } = req.user || {};
if (!req.user || !req.user.userId || !req.user.organization) {
res.status(401).json({ message: "Unauthorized" });

View File

@@ -8,12 +8,7 @@ export const versioncontroller = async (
try {
console.log("req.body: ", req.body);
const { projectId, userId, description, db } = req.body;
// if (!userName || !Email || !description) {
// res.status(400).json({
// message: "All fields are required",
// });
// return;
// }
const result = await versionService.saveCurrentStateAsVersion(
db,
projectId,

View File

@@ -11,46 +11,36 @@ import {
const v1Zone = express.Router();
//Zone-Page
v1Zone.post(
"/zones",
tokenValidator,
// authorizedRoles("Admin", "User"),
CreateZoneController
);
v1Zone.patch(
"/zones/delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
DeleteZoneController
);
//viz
v1Zone.get(
"/zones/visualization/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
VizZoneController
);
//getzones
v1Zone.get(
"/zones/:projectId/:zoneId",
tokenValidator,
// authorizedRoles("Admin", "User"),
ZoneDataController
);
// viz
v1Zone.get(
"/zones/panel/:projectId/:zoneId",
tokenValidator,
// authorizedRoles("Admin", "User"),
SingleZonePanelController
);
v1Zone.get(
"/zones/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
GetZoneController
);
export default v1Zone;

View File

@@ -9,29 +9,24 @@ import {
const v1Asset = express.Router();
//Asset-Page
v1Asset.post(
"/setAsset",
tokenValidator,
// authorizedRoles("Admin", "User"),
CreateAssetController
);
v1Asset.patch(
"/updateFloorAssetPositions",
tokenValidator,
// authorizedRoles("Admin", "User"),
AssetUpdatePosRotController
);
v1Asset.get(
"/floorAssets/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
GetAssetController
);
v1Asset.patch(
"/updateEventData",
tokenValidator,
// authorizedRoles("Admin", "User"),
ReplaceEventDataController
);
export default v1Asset;

View File

@@ -8,23 +8,19 @@ import {
const v1Camera = express.Router();
//Camera-Page
v1Camera.post(
"/setCamera",
tokenValidator,
// authorizedRoles("Admin", "User"),
SetNewCamera
);
v1Camera.get(
"/activeCameras",
tokenValidator,
// authorizedRoles("Admin", "User"),
ActiveOnlineController
);
v1Camera.get(
"/cameras/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
CameraList
);

View File

@@ -11,41 +11,34 @@ import {
const v1Line = express.Router();
//Line-Page
v1Line.post(
"/lines",
tokenValidator,
// authorizedRoles("Admin", "User"),
NewLineController
);
v1Line.post(
"/points",
tokenValidator,
// authorizedRoles("Admin", "User"),
UpdateLineController
);
v1Line.patch(
"/layers/delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
DeleteLayerController
);
v1Line.patch(
"/lines/delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
DeleteLineController
);
v1Line.patch(
"/points/delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
DeleteLinePointsController
);
v1Line.get(
"/lines/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
GetLinesController
);
export default v1Line;

View File

@@ -8,23 +8,19 @@ import {
const v1Wall = express.Router();
//Wall-Page
v1Wall.post(
"/walls",
tokenValidator,
// authorizedRoles("Admin", "User"),
WallSetup
);
v1Wall.patch(
"/walls/delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
WallDelete
);
v1Wall.get(
"/walls/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
WallGet
);
export default v1Wall;

View File

@@ -9,23 +9,19 @@ import {
const v1homeRoutes = express.Router();
//home-Page
v1homeRoutes.get(
"/RecentlyViewed",
tokenValidator,
// authorizedRoles("Admin", "User"),
recentDataController
);
v1homeRoutes.get(
"/searchProjects",
tokenValidator,
// authorizedRoles("Admin", "User"),
searchProjectController
);
v1homeRoutes.get(
"/searchTrashProjects",
tokenValidator,
// authorizedRoles("Admin", "User"),
searchTrashProjectController
);

View File

@@ -8,11 +8,9 @@ import {
ViewData,
} from "../../V1/v1Controllers/projectController/v1projectController.ts";
import { tokenValidator } from "../../../shared/utils/token.ts";
import authorizedRoles from "../../../shared/middleware/rbacMiddleware.ts";
const v1projectRouter = express.Router();
// project
v1projectRouter.post("/NewProject", tokenValidator, createProjectController);
v1projectRouter.post(
"/project/Duplicate",
@@ -22,26 +20,22 @@ v1projectRouter.post(
v1projectRouter.get(
"/Projects",
tokenValidator,
// authorizedRoles("Admin", "User"),
GetProjects
);
v1projectRouter.patch(
"/Projects/Archive/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
RemoveProject
);
v1projectRouter.patch(
"/Projects/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
updateProjectController
);
v1projectRouter.get(
"/Project/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
ViewData
);

View File

@@ -8,24 +8,20 @@ import {
} from "../../V1/v1Controllers/trashController/v1trashController.ts";
const v1TrashRoutes = express.Router();
//trash
v1TrashRoutes.get(
"/TrashItems",
tokenValidator,
// authorizedRoles("Admin", "User"),
GetTrashList
);
v1TrashRoutes.patch(
"/Trash/restore",
tokenValidator,
// authorizedRoles("Admin", "User"),
RestoreTrash
);
v1TrashRoutes.patch(
"/Trash/Delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
DeleteTrashData
);
export default v1TrashRoutes;

View File

@@ -10,35 +10,29 @@ import {
const v1FloatWidget = express.Router();
//floatWidget-Page
v1FloatWidget.post(
"/floatWidget/save",
tokenValidator,
// authorizedRoles("Admin", "User"),
FloatAddController
);
v1FloatWidget.patch(
"/floatWidget/delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
DeleteFloatController
);
v1FloatWidget.get(
"/floatWidgets/:zoneId/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
GetFloatController
);
v1FloatWidget.get(
"/floatWidget/:floatWidgetId",
tokenValidator,
// authorizedRoles("Admin", "User"),
SingleFloatController
);
v1FloatWidget.post(
"/floatWidget/duplicate",
tokenValidator,
// authorizedRoles("Admin", "User"),
DuplicateFloatController
);
export default v1FloatWidget;

View File

@@ -9,29 +9,24 @@ import {
const v1Template = express.Router();
//template-Page
v1Template.post(
"/template/save",
tokenValidator,
// authorizedRoles("Admin", "User"),
AddTemplateController
);
v1Template.post(
"/template/toZone",
tokenValidator,
// authorizedRoles("Admin", "User"),
AddTemToZoneController
);
v1Template.get(
"/template/data/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
GetTemplateController
);
v1Template.patch(
"/template/delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
TemplateDeleteController
);
export default v1Template;

View File

@@ -8,23 +8,19 @@ import {
const v1PanelRoutes = express.Router();
//panel-Page
v1PanelRoutes.post(
"/panel/save",
tokenValidator,
// authorizedRoles("Admin", "User"),
AddPanelController
);
v1PanelRoutes.patch(
"/panel/delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
DeletePanelController
);
v1PanelRoutes.patch(
"/panel/clear",
tokenValidator,
// authorizedRoles("Admin", "User"),
ClearPanelController
);

View File

@@ -10,29 +10,26 @@ import {
const v1Widget3d = express.Router();
//widget3d-Page
v1Widget3d.post(
"/widget3d/save",
tokenValidator,
// authorizedRoles("Admin", "User"),
Add3dWidgetController
);
v1Widget3d.patch(
"/widget3d/update",
tokenValidator,
// authorizedRoles("Admin", "User"),
Update3DwidgetController
);
v1Widget3d.get(
"/widget3d/data/:zoneId/:projectId",
tokenValidator,
// authorizedRoles("Admin", "User"),
Get3DWidgetController
);
v1Widget3d.patch(
"/widget3d/delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
Delete3DwidgetController
);
export default v1Widget3d;

View File

@@ -9,29 +9,24 @@ import {
const v1Widget = express.Router();
//widget-Page
v1Widget.post(
"/widget/save",
tokenValidator,
// authorizedRoles("Admin", "User"),
AddWidgetController
);
v1Widget.patch(
"/widget/:widgetID",
tokenValidator,
// authorizedRoles("Admin", "User"),
WidgetUpdateController
);
v1Widget.get(
"/widget/data",
tokenValidator,
// authorizedRoles("Admin", "User"),
GetWidgetController
);
v1Widget.patch(
"/widget/delete",
tokenValidator,
// authorizedRoles("Admin", "User"),
WidgetDeleteController
);
export default v1Widget;

View File

@@ -8,7 +8,8 @@ import flooritemRoutes from "./Routes/flooritem-Routes.ts";
import WallitemRoutes from "./Routes/wallItems-Routes.ts";
import userRoutes from "./Routes/user-Routes.ts";
import shareRoutes from "./Routes/share-Routes.ts";
import zoneRoutes from "./Routes/zoneRoutes.ts"; //update
import zoneRoutes from "./Routes/zone-Routes.ts";
import zoneRoutes2 from "./Routes/zoneRoutes.ts";
import panelRouter from "./Routes/panelRoutes.ts";
import widgetRouter from "./Routes/widgetRoute.ts";
import assetpointRouter from "./Routes/assetpointRoutes.ts";
@@ -35,51 +36,20 @@ import v1PanelRoutes from "./V1/v1Routes/vizRoutes.ts/v1-panelRoutes.ts";
import v1Template from "./V1/v1Routes/vizRoutes.ts/v1-TemplateRoutes.ts";
import v1Widget from "./V1/v1Routes/vizRoutes.ts/v1-widgetRoutes.ts";
import v1Widget3d from "./V1/v1Routes/vizRoutes.ts/v1-widget3dRoutes.ts";
// import productFlowRoutes from "./Routes/productFlowRouts.ts";
redis;
const app = express();
app.use(cors());
// const allowedOriginsDev = [
// "http://localhost:3000",
// "http://192.168.0.183:8200",
// "http://192.168.0.101:8200",
// "http://192.168.0.105:8200",
// "http://192.168.0.134:8200"
// ];
// const allowedOrigin =
// process.env.NODE_ENV === "production"
// ? process.env.FRONTEND_ORIGIN_PROD
// : allowedOriginsDev;
// app.use(cors({
// origin: (origin, callback) => {
// if (!origin) return callback(null, true);
// if (
// Array.isArray(allowedOrigin) &&
// allowedOrigin.includes(origin)
// ) {
// return callback(null, true);
// }
// if (typeof allowedOrigin === "string" && origin === allowedOrigin) {
// return callback(null, true);
// }
// return callback(new Error("Not allowed by CORS"));
// },
// credentials: true
// }));
app.use(express.json({ limit: "50mb" }));
app.use(
express.urlencoded({ limit: "50mb", extended: true, parameterLimit: 50000 })
);
dotenv.config();
app.use(cors());
app.use(express.json());
app.get("/", (req, res) => {
res.send("Hello, I am Major-Dwinzo API!");
});
app.get("/health", (req, res) => {
res.status(200).json({ message: "Server is running" });
});
app.use("/api/v1", cameraRoutes);
app.use("/api/v1", environmentsRoutes);
@@ -88,8 +58,9 @@ app.use("/api/v1", flooritemRoutes);
app.use("/api/v1", WallitemRoutes);
app.use("/api/v1", userRoutes);
app.use("/api/v1", shareRoutes);
//update
app.use("/api/v2", zoneRoutes); //updates
app.use("/api/v2", zoneRoutes);
app.use("/api/v2", zoneRoutes2);
app.use("/api/v2", panelRouter);
app.use("/api/v2", widgetRouter);
app.use("/api/v2", assetpointRouter);
@@ -98,12 +69,10 @@ app.use("/api/v2", floadWidgetRoutes);
app.use("/api/v2", templateRoutes);
app.use("/api/v2", widget3dRoutes);
app.use("/api/v2", productRouter);
// app.use("/api/v2", productFlowRoutes);
app.use("/api/v1", projectRouter);
app.use("/api/v1", trashRouter);
app.use("/api/v1", homePageRouter);
//New versions--based on the token and role based
app.use("/api/V1", Authrouter);
app.use("/api/V1", v1projectRouter);
app.use("/api/V1", v1TrashRoutes);

View File

@@ -48,9 +48,7 @@ export class FloorItems {
res.status(201).json(newValue);
}
// Send response with the created document
} catch (error) {
console.error("Error creating flooritems:", error);
res.status(500).json({ message: "Failed to create flooritems" });
}
}
@@ -65,7 +63,6 @@ export class FloorItems {
res.status(201).json(findValue);
}
} catch (error) {
console.error("Error get flooritems:", error);
res.status(500).json({ error: "Failed to get flooritems" });
}
}
@@ -83,7 +80,6 @@ export class FloorItems {
res.status(201).json(findValue);
}
} catch (error) {
console.error("Error get flooritems:", error);
res.status(500).json({ error: "Failed to get flooritems" });
}
}

View File

@@ -77,8 +77,6 @@ interface IPointStaticMachine extends IPointBase {
export class PointService {
static async addPoints(req: Request, res: Response): Promise<any> {
const { type, modelfileID, organization } = req.body;
// Validate type
if (!["Conveyor", "Vehicle", "ArmBot", "StaticMachine"].includes(type)) {
return res.status(400).json({ message: "Invalid type requested" });
}
@@ -92,7 +90,6 @@ export class PointService {
if (type === "Conveyor") {
const baseData = {
// modelfileID: "672a090f80d91ac979f4d0bd",
modelfileID: "7dc04e36882e4debbc1a8e3d",
type: "Conveyor",
};
@@ -118,8 +115,6 @@ export class PointService {
name: "trigger 1",
type: "triggerType",
bufferTime: 0,
// delay: "Inherit",
// spawnInterval: "Inherit",
isUsed: false,
},
],
@@ -195,7 +190,6 @@ export class PointService {
} else if (type === "Vehicle") {
console.log("vehcile data");
const baseData = {
// modelfileID: "67e3da19c2e8f37134526e6a",
modelfileID: "a1ee92554935007b10b3eb05",
type: "Vehicle",
};
@@ -231,7 +225,6 @@ export class PointService {
} else if (type === "ArmBot") {
console.log("ArmBot data");
const baseData = {
// modelfileID: "67eb7904c2e8f37134527eae",
modelfileID: "52e6681fbb743a890d96c914",
type: "ArmBot",
};
@@ -269,7 +262,6 @@ export class PointService {
} else if (type === "StaticMachine") {
console.log("StaticMachine data");
const baseData = {
// modelfileID: "67e3db5ac2e8f37134526f40",
modelfileID: "ca164ffdfa74f6622536bb0f",
type: "StaticMachine",
};

View File

@@ -32,7 +32,7 @@ export class WallItems {
quaternion,
scale,
},
{ new: true } // Return the updated document
{ new: true }
);
res.status(201).json(updatevalue);
} else {
@@ -49,8 +49,6 @@ export class WallItems {
res.status(201).json(newValue);
}
// Send response with the created document
} catch (error) {
console.error("Error creating wallitems:", error);
res.status(500).json({ message: "Failed to create wallitems" });

View File

@@ -28,8 +28,6 @@ export class Camera {
res.status(201).json(newCamera);
}
// Send response with the created document
} catch (error) {
console.error("Error creating camera:", error);
res.status(500).json({ message: "Failed to create camera" });
@@ -38,7 +36,6 @@ export class Camera {
static async getCamera(req: Request, res: Response) {
try {
const { userId, organization } = req.params;
const findCamera = await cameraModel(organization).findOne({
userId: userId,
});
@@ -79,8 +76,6 @@ export class Camera {
},
};
}
// Return null if no camera data is found for the user
return null;
}
);

View File

@@ -46,7 +46,6 @@ export class Environment {
res.status(201).json(newValue);
}
// Send response with the created document
} catch (error) {
console.error("Error creating environments:", error);
res.status(500).json({ message: "Failed to create environments" });

View File

@@ -12,8 +12,6 @@ export class Lines {
});
res.status(201).json(newLine);
// Send response with the created document
} catch (error) {
console.error("Error creating Lines:", error);
res.status(500).json({ message: "Failed to create Lines" });
@@ -22,16 +20,12 @@ export class Lines {
static async updateLines(req: Request, res: Response) {
try {
const { organization, uuid, position } = req.body;
// const findLine = await lineModel(organization).find({ 'line.uuid': uuid });
// Update the position of the line matching the uuid
const updateResult = await lineModel(organization).updateMany(
{ "line.uuid": uuid }, // Filter: Find the line with the given uuid
{ $set: { "line.$.position": position } } // Update the position and type
{ "line.uuid": uuid },
{ $set: { "line.$.position": position } }
);
res.status(201).json(updateResult);
// Send response with the created document
} catch (error) {
console.error("Error creating Lines:", error);
res.status(500).json({ message: "Failed to create Lines" });
@@ -54,11 +48,12 @@ export class Lines {
}
static async deleteLineItems(req: Request, res: Response) {
try {
const { organization, layer, line, type } = req.body;
const { organization, line } = req.body;
const inputUuids = line.map((item: any) => item.uuid);
const findValue = await lineModel(organization).findOneAndDelete({
"line.uuid": { $all: inputUuids },
"line.uuid": { $all: inputUuids },
});
if (!findValue) {
@@ -73,7 +68,7 @@ export class Lines {
}
static async deleteLinPoiteItems(req: Request, res: Response) {
try {
const { organization, layer, uuid, type } = req.body;
const { organization, uuid } = req.body;
const findValue = await lineModel(organization).deleteMany({
"line.uuid": uuid,
@@ -103,7 +98,7 @@ export class Lines {
const updateResult = await lineModel(organization).updateMany(
{ layer: { $gt: layer } },
{ $inc: { layer: -1 } }
{ $inc: { layer: -1 } }
);
res.status(201).json(updateResult);

View File

@@ -1,10 +1,9 @@
import { Request, Response } from "express";
import zoneModel from "../../../shared/model/lines/zone-Model.ts";
export class zone {
export class Zone {
static async setZone(req: Request, res: Response) {
try {
const { organization, userId, zoneData } = req.body;
// console.log('req.body: ', req.body);
const zoneId = zoneData.zoneId;
const points = zoneData.points;
const zoneName = zoneData.zoneName;
@@ -26,11 +25,13 @@ export class zone {
{ new: true }
)
.select("-_id -__v");
res.status(201).json({
message: "zone updated",
data: updateZone,
organization: organization,
});
res
.status(201)
.json({
message: "zone updated",
data: updateZone,
organization: organization,
});
} else {
const zoneCreate = await zoneModel(organization).create({
zoneId,
@@ -45,11 +46,13 @@ export class zone {
.findById(zoneCreate._id)
.select("-_id -__v")
.lean();
res.status(201).json({
message: "zone created",
data: createdZone,
organization: organization,
});
res
.status(201)
.json({
message: "zone created",
data: createdZone,
organization: organization,
});
}
} catch (error) {
console.log("error: ", error);
@@ -67,11 +70,13 @@ export class zone {
const deleteZone = await zoneModel(organization)
.findOneAndDelete({ zoneId: zoneId, createBy: userId })
.select("-_id -__v");
res.status(201).json({
message: "zone deleted",
data: deleteZone,
organization: organization,
});
res
.status(201)
.json({
message: "zone deleted",
data: deleteZone,
organization: organization,
});
} else {
res.status(500).json({ message: "Invalid zone ID" });
}
@@ -82,7 +87,7 @@ export class zone {
}
static async getZones(req: Request, res: Response) {
try {
const { organization, userId } = req.params;
const { organization } = req.params;
const findZoneId = await zoneModel(organization)
.find()
@@ -93,7 +98,7 @@ export class zone {
if (!findZoneId) {
res.status(500).json({ message: "Invalid zone" });
}
res.status(200).json({ data: findZoneId, organization: organization });
res.status(201).json({ data: findZoneId, organization: organization });
} catch (error) {
console.log("error: ", error);
res.status(500).json({ message: "Zone not found", error });
@@ -107,7 +112,6 @@ export class zone {
const findZone = await zoneModel(organization).findOne({
zoneId: zoneId,
});
// .select("zoneName");
console.log("findZone: ", findZone);
if (findZone) return res.status(200).json(findZone);
} catch (error: any) {

View File

@@ -33,13 +33,6 @@ export class ZoneService {
},
});
} else {
// const existingZoneName = await zoneSchema(organization).find({
// zoneName: zoneDatas.zoneName,
// isArchive: false,
// });
// if (existingZoneName.length > 0) {
// return res.json({ message: "Zone name already exists" });
// }
const replaceZone = await zoneSchema(organization).findOneAndUpdate(
{ zoneId: zoneDatas.zoneId, isArchive: false },
{
@@ -96,7 +89,6 @@ export class ZoneService {
}
}
//single zode panel and widget data
static async singleZonePanelDatas(req: Request, res: Response): Promise<any> {
const organization = req.query.organization;
const zoneId = req.params.zoneId;
@@ -157,7 +149,6 @@ export class ZoneService {
}
}
//page full zone Datas with panel and widget
static async vizAllDatas(req: Request, res: Response): Promise<any> {
const organization = req.query.organization;
try {
@@ -173,13 +164,11 @@ export class ZoneService {
} else {
const response = await Promise.all(
existingZones.map(async (zone) => {
// Fetch all panels associated with the current zone
const panelData = await panelSchema(organization).find({
zoneId: zone._id,
isArchive: false,
});
// Fetch widgets for each panel
const widgets = await Promise.all(
panelData.map(async (panel) => {
const widgetDataArray = await widgetSchema(organization).find({
@@ -218,7 +207,6 @@ export class ZoneService {
}
}
//only for the name and zoneID
static async allZones(req: Request, res: Response): Promise<any> {
const organization = req.query.organization;
const sceneID = req.params.sceneID || "scene123";
@@ -244,7 +232,7 @@ export class ZoneService {
const findZone = await zoneSchema(organization).findOne({
zoneId: zoneId,
});
// .select("zoneName");
if (findZone) return res.status(200).json(findZone);
} catch (error: any) {
return res.status(500).send(error.message);
@@ -284,21 +272,4 @@ export class ZoneService {
return res.status(500).send(error.message);
}
}
// static async zoneIdgenerate(req: Request, res: Response): Promise<any> {
// const organization = req.query.organization;
// const sceneID = req.params.sceneID;
// try {
// const Allzones = await zoneSchema(organization)
// .find({ sceneID: sceneID, isArchive: false })
// .select("zoneName sceneID zoneId");
// if (!Allzones || Allzones.length === 0) {
// return res.send({ message: "Zone not found for the UUID" });
// }
// return res.send(Allzones);
// } catch (error: any) {
// return res.status(500).send(error.message);
// }
// }
}

View File

@@ -18,7 +18,6 @@ export class Share {
if (!findValue) {
res.status(404).json({ message: "Not found" });
}
// Send response with the created document
} catch (error) {
console.error("Error creating Share:", error);
res.status(500).json({ message: "Failed to create Share" });
@@ -37,7 +36,6 @@ export class Share {
if (!findValue) {
res.status(404).json({ message: "Not found" });
}
// Send response with the created document
} catch (error) {
console.error("Error Share:", error);
res.status(500).json({ message: "Failed to Share datas " });

View File

@@ -17,8 +17,6 @@ export class AssetsFloorService {
isLocked,
isVisible,
organization,
// modelfileID, //optional
// eventData, // Optional
} = req.body;
const existingAsset = await assetModel(organization).findOne({
@@ -84,11 +82,9 @@ export class AssetsFloorService {
organization,
eventData,
} = req.body;
console.log("req.body: ", req.body);
const findvalue = await assetModel(organization).findOne({
modelUuid,
// modelName,
isArchive: false,
});
await pointModel(organization).findOne({
@@ -207,14 +203,11 @@ export class AssetsFloorService {
return res.status(500).json({ message: "Failed to archive asset" });
}
const updatedEvents = await EventsDataModel(organization).updateMany(
await EventsDataModel(organization).updateMany(
{ modelUuid },
{ $set: { isArchive: true } }
);
console.log("Archived asset:", archivedAsset);
console.log("Updated events:", updatedEvents.modifiedCount);
return res.status(200).json({ message: "delete Asset successfully" });
} catch (error) {
console.error("Error deleting floor items:", error);

View File

@@ -2,10 +2,10 @@ import { Request, Response } from "express";
import ProductModel from "../../../shared/model/simulation/productModel.ts";
import EventsDataModel from "../../../shared/model/simulation/eventsDataModel.ts";
export class ProductFlowservice {
export class ProductFlowService {
static async productAdd(req: Request, res: Response): Promise<any> {
try {
const { productName, productId,eventDatas, organization } = req.body;
const { productName, productId, eventDatas, organization } = req.body;
if (!organization) {
return res.json({ message: "organization not found" });
}
@@ -136,12 +136,10 @@ export class ProductFlowservice {
productId: productId,
});
if (existingEventDatas) {
// for (const event of existingEventDatas) {
await EventsDataModel(organization).updateMany(
{ productId },
{ $set: { isArchive: true } }
);
// }
await EventsDataModel(organization).updateMany(
{ productId },
{ $set: { isArchive: true } }
);
}
return res.status(201).json({ message: "product deleted successfully" });
} catch (error) {
@@ -197,11 +195,9 @@ export class ProductFlowservice {
.select("-productId -isArchive -createdAt -updatedAt -__v -_id");
result.push({
// product: {
productName: product.productName,
productId: product.productId,
eventDatas,
// },
});
}

View File

@@ -28,7 +28,6 @@ export const GetTrashList = async (
case "Success":
res.status(200).json({
// message: "Project created Successfully",
TrashDatas: result.ListDatas,
});
break;

View File

@@ -1,76 +1,72 @@
import { Request, Response } from "express";
import userModel from "../../shared/model/user-Model.ts";
import {hashGenerate,hashValidator} from "../../shared/utils/Hasing.ts"
import { hashGenerate, hashValidator } from "../../shared/security/Hasing.ts";
let serverAlive = true;
export class User {
static async signup(req: Request, res: Response) {
try {
let role;
const { userName, email, password,organization,profilePicture } = req.body;
const caseChange = email.toLowerCase();
const emailcheck = await userModel(organization).findOne({ email: caseChange });
if (emailcheck!==null) {
res.json({
message:"User already exists"
});
} else {
const hashpassword=await hashGenerate(password)
const userCount = await userModel(organization).countDocuments({});
role = userCount === 0 ? "Admin" : "User";
const isShare = "true";
const newuser = await userModel(organization).create({
userName: userName,
email: caseChange,
isShare:isShare,
password: hashpassword,
role:role,
profilePicture:profilePicture
});
newuser.save();
res.status(200).json({
message:"New User created"
});
}
} catch (error:any) {
res.status(500).send(error);
}
static async signup(req: Request, res: Response) {
try {
let role;
const { userName, email, password, organization, profilePicture } =
req.body;
const caseChange = email.toLowerCase();
const emailcheck = await userModel(organization).findOne({
email: caseChange,
});
if (emailcheck !== null) {
res.json({
message: "User already exists",
});
} else {
const hashpassword = await hashGenerate(password);
const userCount = await userModel(organization).countDocuments({});
role = userCount === 0 ? "Admin" : "User";
const isShare = "true";
const newuser = await userModel(organization).create({
userName: userName,
email: caseChange,
isShare: isShare,
password: hashpassword,
role: role,
profilePicture: profilePicture,
});
newuser.save();
res.status(200).json({
message: "New User created",
});
}
} catch (error: any) {
res.status(500).send(error);
}
static async login(req: Request, res: Response) {
try {
let role;
const { email, password,organization } = req.body;
const existingMail = await userModel(organization).findOne({
email:email
});
if (existingMail === null || !existingMail) {
res.status(401).json({ message: "User Not Found!!! Kindly signup..." });
} else {
const hashedpassword= existingMail.password
const checkpassword = await hashValidator(
password,
hashedpassword
)
if (checkpassword) {
// const tokenValidation=await tokenGenerator(existingMail.email)
res.status(200).send({
message: "login successfull",
email: existingMail.email,
name: existingMail.userName,
userId: existingMail._id,
isShare:existingMail.isShare,
// token:tokenValidation
});
} else {
res.status(404).json({message:"email & password is invalid...Check the credentials"})
}
}
} catch (error:any) {
res.status(500).send(error);
}
}
}
}
static async login(req: Request, res: Response) {
try {
let role;
const { email, password, organization } = req.body;
const existingMail = await userModel(organization).findOne({
email: email,
});
if (existingMail === null || !existingMail) {
res.status(401).json({ message: "User Not Found!!! Kindly signup..." });
} else {
const hashedpassword = existingMail.password;
const checkpassword = await hashValidator(password, hashedpassword);
if (checkpassword) {
res.status(200).send({
message: "login successfull",
email: existingMail.email,
name: existingMail.userName,
userId: existingMail._id,
isShare: existingMail.isShare,
});
} else {
res.status(404).json({
message: "email & password is invalid...Check the credentials",
});
}
}
} catch (error: any) {
res.status(500).send(error);
}
}
}

View File

@@ -8,7 +8,6 @@ export class PanelService {
try {
const organization = req.body.organization;
const zoneId = req.body.zoneId;
// const panelName = req.body.panelName;
const panelOrder = req.body.panelOrder;
const findZone = await zoneSchema(organization).findOne({
zoneId: zoneId,

View File

@@ -8,16 +8,7 @@ import floatWidgetModel from "../../../shared/model/vizualization/floatWidget.ts
export class TemplateService {
static async AddTemplate(req: Request, res: Response): Promise<any> {
try {
const {
organization,
template,
// id,
// name,
// panelOrder,
// widgets,
// snapshot,
// floatWidgets,
} = req.body;
const { organization, template } = req.body;
const existingTemplate = await templateModel(organization).findOne({
templateID: template.id,
isArchive: false,
@@ -83,7 +74,6 @@ export class TemplateService {
if (existingZone.panelOrder.length > 0) {
existingZone.panelOrder = existingTemplate.panelOrder;
await existingZone.save();
// Clear existing data before adding new data
const archivePanelDatas = await panelSchema(organization).find({
zoneId,
isArchive: false,

View File

@@ -5,12 +5,7 @@ import widgetSchema from "../../../shared/model/vizualization/widgemodel.ts";
export class WidgetService {
static async addWidget(req: Request, res: Response): Promise<any> {
try {
const {
organization,
// panel,
zoneId,
widget,
} = req.body;
const { organization, zoneId, widget } = req.body;
const existingZone = await zoneSchema(organization).findOne({
zoneId: zoneId,
isArchive: false,
@@ -30,7 +25,6 @@ export class WidgetService {
panelID: existingPanel._id,
widgetID: widget.id,
isArchive: false,
// widgetOrder: widget.widgetOrder,
});
if (existingWidget) {
const updateWidget = await widgetSchema(
@@ -43,8 +37,6 @@ export class WidgetService {
},
{
$set: {
// panelID: existingPanel._id,
// widgetID: widget.id,
widgetName: widget?.widgetName,
Data: {
measurements: widget?.Data?.measurements || {},
@@ -53,7 +45,7 @@ export class WidgetService {
isArchive: false,
},
},
{ upsert: true, new: true } // Upsert: create if not exists, new: return updated document
{ upsert: true, new: true }
);
if (!updateWidget) {
return res.json({ message: "Widget update unsuccessful" });
@@ -65,7 +57,6 @@ export class WidgetService {
const newWidget = await widgetSchema(organization).create({
widgetID: widget.id,
elementType: widget.type,
// widgetOrder: widgetOrder,
zoneId,
widgetName: widget.title,
panelID: existingPanel._id,
@@ -80,7 +71,6 @@ export class WidgetService {
await existingPanel.save();
return res.status(201).json({
message: "Widget created successfully",
// widgetID: newWidget._id,
});
}
}
@@ -106,19 +96,11 @@ export class WidgetService {
);
if (widgetData) {
// Find all widgets in the same panel and sort them by widgetOrder
await widgetSchema(organization).find({
panelID: findWidget.panelID,
zoneId: zoneId,
isArchive: false,
});
// .sort({ widgetOrder: 1 });
// Reassign widgetOrder values
// for (let i = 0; i < widgets.length; i++) {
// widgets[i].widgetOrder = (i + 1).toString(); // Convert to string
// await widgets[i].save();
// }
const panelData = await panelSchema(organization).findOne({
_id: findWidget.panelID,
zoneId: zoneId,
@@ -147,7 +129,7 @@ export class WidgetService {
return res.status(404).send({ message: "Data not found" });
const updateData = {
widgetName: values.widgetName,
widgetSide: values.widgetSide, // Fixed typo from widgetside to widgetSide
widgetSide: values.widgetSide,
elementType: values.type,
Data: {
measurement: values.Data.measurement,

View File

@@ -1,36 +1,25 @@
import app from './app.ts';
import http from 'http';
// import { startHealthCheck } from './controller/user-Controller';
import swaggerUi from 'swagger-ui-express';
import fs from 'fs';
import app from "./app.ts";
import http from "http";
import swaggerUi from "swagger-ui-express";
import fs from "fs";
const server = http.createServer(app);
let swaggerDocument = {};
// try {
// swaggerDocument = require('../../swagger-output.json');
// } catch (error) {
// console.error('Error loading Swagger JSON:', error);
// swaggerDocument = {}; // Fallback: empty object or some default
// }
try {
swaggerDocument = JSON.parse(fs.readFileSync('swagger-output.json', 'utf-8'));
swaggerDocument = JSON.parse(fs.readFileSync("swagger-output.json", "utf-8"));
} catch (error) {
console.error('Error loading Swagger JSON:', error);
console.error("Error loading Swagger JSON:", error);
}
app.use('/api-docs', swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const organization = process.env.ORGANIZATION_NAME || 'defaultOrganization'; // Replace with your logic
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerDocument));
const organization = process.env.ORGANIZATION_NAME || "defaultOrganization";
// mongoAdminCreation()
if (!organization) {
throw new Error('ORGANIZATION_NAME is not defined in the environment');
throw new Error("ORGANIZATION_NAME is not defined in the environment");
}
const PORT = process.env.API_PORT
const PORT = process.env.API_PORT;
server.listen(PORT, () => {
console.log(`API-Server running on http://localhost:${PORT}`);
console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
console.log(`API-Server running on http://localhost:${PORT}`);
console.log(`Swagger UI available at http://localhost:${PORT}/api-docs`);
});

View File

@@ -39,7 +39,6 @@ const UserDataSchema: Schema = new Schema({
},
profilePicture: {
type: String,
// default: "default-profile-picture.jpg"
},
});

View File

@@ -21,7 +21,6 @@ const AuthSchema: Schema = new Schema({
Password: {
type: String,
min: 8,
// required: true,
},
isArchive: { type: Boolean, default: false },
lastPasswordReset: { type: Number },

View File

@@ -31,7 +31,7 @@ export interface AssetData extends Document {
type: string;
isVisible: boolean;
isArchive: false;
// points: [] | {};
position: [];
rotation: {
x: number;

View File

@@ -1,26 +1,24 @@
import mongoose, { Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
import { User } from "../Auth/userAuthModel.ts";
import { Project } from "../Project/project-model.ts";
import { Version } from "../Version/versionModel.ts";
import { User } rom "../Version/versionModel.ts";
const positionSchema = new mongoose.Schema({
x: { type: Number }, // Optional position fields
x: { type: Number },
y: { type: Number },
z: { type: Number },
});
const Vector3 = new mongoose.Schema({
position: { type: positionSchema, required: false }, // Optional position
uuid: { type: String, required: false }, // Optional uuid
position: { type: positionSchema, required: false },
uuid: { type: String, required: false },
});
const LineSchema = new mongoose.Schema({
userId: { type: Schema.Types.ObjectId, ref: "User" },
projectId: { type: Schema.Types.ObjectId, ref: "Project" },
versionId: { type: Schema.Types.ObjectId, ref: "Version" },
layer: { type: Number, required: true }, // Layer is mandatory
line: { type: [Vector3], required: true }, // Array of line objects
type: { type: String, required: false }, // Optional type
layer: { type: Number, required: true },
line: { type: [Vector3], required: true },
type: { type: String, required: false },
});
const lineModel = (db: string) => {

View File

@@ -38,8 +38,6 @@ const zoneSchema: Schema = new Schema(
default: [],
enum: ["left", "right", "top", "bottom"],
},
// createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
// sceneID: { type: mongoose.Schema.Types.ObjectId, ref: "Scene" },
},
{ timestamps: true }
);

View File

@@ -1,4 +1,3 @@
// models/Product.ts
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
@@ -118,13 +117,11 @@ interface RoboticArmEventSchema extends AssetEventSchema {
interface MachineEventSchema extends AssetEventSchema {
type: "machine";
// speed: number;
point: MachinePointSchema;
}
interface StorageEventSchema extends AssetEventSchema {
type: "storageUnit";
// speed: number;
point: StoragePointSchema;
}
interface IPointModel extends Document {
@@ -144,7 +141,6 @@ interface IPointModel extends Document {
| StorageEventSchema;
points: ConveyorEventSchema[];
}
// type EventsSchema = ConveyorEventSchema | VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema;
const BaseEventSchema = new Schema<IPointModel>(
{

View File

@@ -5,9 +5,7 @@ import { Version } from "../Version/versionModel.ts";
import MainModel from "../../connect/mongoose.ts";
interface IComment {
userId: User["_id"];
// createdAt: string;
comment: string;
// lastUpdatedAt: string;
timestamp:Number
}
export interface IThread extends Document {
@@ -26,14 +24,11 @@ export interface IThread extends Document {
const CommentSchema = new Schema<IComment>(
{
userId: { type: Schema.Types.ObjectId, ref: 'User', required: true },
// createdAt: { type: String, },
comment: { type: String,},
// lastUpdatedAt: { type: String, },
timestamp:{
type: Number,
default:Date.now()}
},
// { _id: false } // Prevent automatic _id for each reply object
);
const threadSchema = new Schema<IThread>({
projectId: { type: Schema.Types.ObjectId, ref: 'Project', required: true },

View File

@@ -14,13 +14,12 @@ const MainModel = <T>(
): Model<T> => {
const db1_url = `${process.env.MONGO_URI}${db}`;
const authOptions = {
user: process.env.MONGO_USER, // Correct username environment variable
pass: process.env.MONGO_PASSWORD, // Correct password environment variable
authSource: process.env.MONGO_AUTH_DB || "admin", // Default to 'admin' if not provided
user: process.env.MONGO_USER,
pass: process.env.MONGO_PASSWORD,
authSource: process.env.MONGO_AUTH_DB || "admin",
maxPoolSize: 50,
};
// Check if the connection already exists
if (connections[db]) {
return connections[db].model<T>(modelName, schema, collectionName);
}
@@ -28,10 +27,8 @@ const MainModel = <T>(
try {
const db1 = mongoose.createConnection(db1_url, authOptions);
// Cache the connection
connections[db] = db1;
// Log connection success or handle errors
db1.on("connected", () => {
console.log(`Connected to MongoDB database: ${db}`);
});

View File

@@ -1,7 +1,7 @@
import { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface FloorItems extends Document {
export interface FloorItenms extends Document {
modelUuid: string;
modelfileID: string;
modelName: string;

View File

@@ -26,7 +26,6 @@ export interface AssetData extends Document {
type: string;
isVisible: boolean;
isArchive: false;
// points: [] | {};
position: [];
rotation: {
x: number;

View File

@@ -1,4 +1,4 @@
import { Document, Schema } from "mongoose";
import { Document, Schema } from "mongoose";
import MainModel from "../../../connect/mongoose.ts";
export interface Camera extends Document {

View File

@@ -1,20 +1,20 @@
import mongoose from "mongoose";
import MainModel from "../../../connect/mongoose.ts";
const positionSchema = new mongoose.Schema({
x: { type: Number }, // Optional position fields
x: { type: Number },
y: { type: Number },
z: { type: Number },
});
const Vector3 = new mongoose.Schema({
position: { type: positionSchema, required: false }, // Optional position
uuid: { type: String, required: false }, // Optional uuid
position: { type: positionSchema, required: false },
uuid: { type: String, required: false },
});
const LineSchema = new mongoose.Schema({
layer: { type: Number, required: true }, // Layer is mandatory
line: { type: [Vector3], required: true }, // Array of line objects
type: { type: String, required: false }, // Optional type
layer: { type: Number, required: true },
line: { type: [Vector3], required: true },
type: { type: String, required: false },
});
const lineModel = (db: string) => {

View File

@@ -1,5 +1,4 @@
import { Schema, Document } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../../connect/mongoose.ts";
export interface Zone extends Document {
@@ -13,8 +12,6 @@ export interface Zone extends Document {
sceneID: string;
panelOrder: string[];
lockedPanel: string[];
// createdBy: mongoose.Types.ObjectId;
// sceneID: mongoose.Types.ObjectId;
layer: number;
}
const zoneSchema: Schema = new Schema(
@@ -37,8 +34,6 @@ const zoneSchema: Schema = new Schema(
default: [],
enum: ["left", "right", "top", "bottom"],
},
// createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" },
// sceneID: { type: mongoose.Schema.Types.ObjectId, ref: "Scene" },
},
{ timestamps: true }
);

View File

@@ -9,14 +9,14 @@ export interface Camera extends Document {
z: number;
};
target: {
x: { type: Number; required: true };
y: { type: Number; required: true };
z: { type: Number; required: true };
x: { type: number; required: true };
y: { type: number; required: true };
z: { type: number; required: true };
};
rotation: {
x: { type: Number; required: true };
y: { type: Number; required: true };
z: { type: Number; required: true };
x: { type: number; required: true };
y: { type: number; required: true };
z: { type: number; required: true };
};
}

View File

@@ -1,43 +1,23 @@
import mongoose, { Document, Schema } from "mongoose";
import mongoose from "mongoose";
import MainModel from "../../connect/mongoose.ts";
const positionSchema = new mongoose.Schema({
x: { type: Number, }, // Optional position fields
y: { type: Number, },
z: { type: Number},
});
// Define a schema for the individual line
const Vector3 = new mongoose.Schema({
position: { type: positionSchema, required: false }, // Optional position
uuid: { type: String, required: false }, // Optional uuid
});
// Define the main schema
const LineSchema = new mongoose.Schema({
layer: { type: Number, required: true }, // Layer is mandatory
line: { type: [Vector3], required: true }, // Array of line objects
type: { type: String, required: false }, // Optional type
});
x: { type: Number },
y: { type: Number },
z: { type: Number },
});
// Database connection and model creation
// const lineModel = (db: string) => {
// const mongoUrl = process.env.MONGO_URI || "";
// if (!mongoUrl) {
// throw new Error("MONGO_URI environment variable is not set");
// }
const Vector3 = new mongoose.Schema({
position: { type: positionSchema, required: false },
uuid: { type: String, required: false },
});
// // Connect to the database
// const dbConnection = mongoose.createConnection(mongoUrl, {
// dbName: db, // Specify the database name here
// serverSelectionTimeoutMS: 30000,
// });
const LineSchema = new mongoose.Schema({
layer: { type: Number, required: true },
line: { type: [Vector3], required: true },
type: { type: String, required: false },
});
// // Return the model
// return dbConnection.model("lines", LineSchema, "lines");
// };
// export default lineModel;
const lineModel = (db:string) => {
return MainModel(db, "lines", LineSchema, "lines")
const lineModel = (db: string) => {
return MainModel(db, "lines", LineSchema, "lines");
};
export default lineModel;
export default lineModel;

View File

@@ -1,32 +1,28 @@
import mongoose, { Document, ObjectId, Schema } from "mongoose";
import mongoose, { Document, Schema } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface zoneSchema extends Document {
zoneId: string;//UUID
zoneName: string
createBy: mongoose.Types.ObjectId
points: []
layer: Number
viewPortCenter: []
viewPortposition: []
isArchive:boolean
export interface ZoneSchema extends Document {
zoneId: string;
zoneName: string;
createBy: mongoose.Types.ObjectId;
points: [];
layer: number;
viewPortCenter: [];
viewPortposition: [];
isArchive: boolean;
}
// Define the Mongoose Schema
const zoneSchema: Schema = new Schema({
zoneId: { type: String },//UUID
zoneName: { type: String },
createBy: { type: Schema.Types.ObjectId, ref: "Users", },
points: { type: Array },
layer: { type: Number, required: true },
viewPortCenter: { type: Array, required: true },
viewPortposition: { type: Array, required: true },
isArchive:{type:Boolean,default:false}
zoneId: { type: String },
zoneName: { type: String },
createBy: { type: Schema.Types.ObjectId, ref: "Users" },
points: { type: Array },
layer: { type: Number, required: true },
viewPortCenter: { type: Array, required: true },
viewPortposition: { type: Array, required: true },
isArchive: { type: Boolean, default: false },
});
// export default zoneModel;
const zoneModel = (db: string) => {
return MainModel(db, "zones", zoneSchema, "zones")
return MainModel(db, "zones", zoneSchema, "zones");
};
export default zoneModel;
export default zoneModel;

View File

@@ -7,27 +7,17 @@ export interface Project extends Document {
projectName: string;
createdBy: User["_id"];
isArchive: boolean;
isDeleted: boolean;
thumbnail: string;
sharedUsers: [];
DeletedAt: Date;
isViewed: number;
total_versions: string;
Present_version: string;
}
const projectSchema: Schema = new Schema(
{
projectUuid: { type: String },
projectName: { type: String },
projectUuid: { type: String, required: true },
projectName: { type: String },
thumbnail: { type: String },
isArchive: { type: Boolean, default: false },
createdBy: { type: Schema.Types.ObjectId, ref: "user" },
sharedUsers: [{ type: Schema.Types.ObjectId, ref: "user" }],
DeletedAt: { type: Date, default: null },
isDeleted: { type: Boolean, default: false },
isViewed: { type: Number },
total_versions: { type: String },
Present_version: { type: String },
},
{ timestamps: true }
);

View File

@@ -1,4 +1,3 @@
// models/Product.ts
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
@@ -118,22 +117,20 @@ interface RoboticArmEventSchema extends AssetEventSchema {
interface MachineEventSchema extends AssetEventSchema {
type: "machine";
// speed: number;
point: MachinePointSchema;
}
interface StorageEventSchema extends AssetEventSchema {
type: "storageUnit";
// speed: number;
point: StoragePointSchema;
}
interface IPointModel extends Document {
modelUuid: String;
modelName: String;
position: String;
rotation: String;
state: String;
productId: String;
modelUuid: string;
modelName: string;
position: [number];
rotation: [number];
state: string;
productId: string;
isArchive: boolean;
type: "transfer" | "vehicle" | "roboticArm" | "machine" | "storageUnit";
speed: number;
@@ -144,7 +141,6 @@ interface IPointModel extends Document {
| StorageEventSchema;
points: ConveyorEventSchema[];
}
// type EventsSchema = ConveyorEventSchema | VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema;
const BaseEventSchema = new Schema<IPointModel>(
{

View File

@@ -3,9 +3,7 @@ import MainModel from "../../connect/mongoose.ts";
export interface Trigger extends Document {
pointsUUID: string;
// triggerUUID: string;
isArchive: string;
// sceneID: string;
uuid: string;
name: string;
type: string;
@@ -16,7 +14,6 @@ const triggerSchema: Schema = new Schema(
{
pointsUUID: { type: String },
isArchive: { type: Boolean, default: false },
// triggerUUID: { type: String },
uuid: { type: String, default: "" },
name: { type: String },
type: { type: String },

View File

@@ -32,7 +32,6 @@ const signupschema: Schema = new Schema({
},
profilePicture: {
type: String,
// default: "default-profile-picture.jpg"
},
isShare: {
type: Boolean,
@@ -43,14 +42,9 @@ const signupschema: Schema = new Schema({
enum: ["online", "offline"],
default: "offline",
},
recentlyViewed: {
type: [String],
default: [],
},
});
const userModel = (db: string) => {
return MainModel(db, "Users", signupschema, "Users")
// return MainModel(db, "UserAuth", signupschema, "UserAuth");
return MainModel(db, "Users", signupschema, "Users");
};
export default userModel;

View File

@@ -1,4 +1,4 @@
import { Schema, Document, model } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface Widget3d extends Document {

View File

@@ -1,4 +1,4 @@
import { Schema, Document, model } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface FloatingWidget extends Document {

View File

@@ -9,7 +9,7 @@ export interface Panel extends Document {
}
const panelSchema: Schema = new Schema(
{
zoneId: { type: String },
zoneId: { type: String },
panelName: { type: String },
widgets: [{ type: mongoose.Schema.Types.ObjectId, ref: "Widget" }],
isArchive: { type: Boolean, default: false },

View File

@@ -1,4 +1,4 @@
import { Schema, Document } from "mongoose";
import { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface Template extends Document {

View File

@@ -1,7 +1,7 @@
import mongoose, { Schema, Document } from "mongoose";
import MainModel from "../../connect/mongoose.ts";
export interface widget extends Document {
export interface Widget extends Document {
widgetName: string;
widgetside: string;
widgetID: string;
@@ -17,7 +17,7 @@ export interface widget extends Document {
measurements: {};
duration: string;
};
zoneId:string
zoneId: string;
}
const widgetSchema: Schema = new Schema(
{
@@ -36,7 +36,7 @@ const widgetSchema: Schema = new Schema(
fontWeight: { type: String },
isArchive: { type: Boolean, default: false },
panelID: { type: mongoose.Schema.Types.ObjectId, ref: "Panel" },
zoneId:{ type: String }
zoneId: { type: String },
},
{ timestamps: true }
);

View File

@@ -194,7 +194,6 @@ export const AuthLogin = async (
name: existingMail.userName,
userId: existingMail._id,
isShare: UserData.isShare,
// updatedUser: updatedUser as IUser,
token: tokenValidation,
refreshToken: refreshTokenvalidation,
};

View File

@@ -11,7 +11,6 @@ type MulterFile = {
const bucketName = "assets-public-bucket";
// Define public read policy
const publicReadPolicy = {
Version: "2012-10-17",
Statement: [
@@ -35,7 +34,7 @@ async function ensureBucketExists() {
async function ensureFolderExists(folderName: string) {
const folderPrefix = folderName.endsWith("/") ? folderName : `${folderName}/`;
const objects = minioClient.listObjects(bucketName, folderPrefix, true);
for await (const _ of objects) return; // Folder exists
for await (const _ of objects) return;
await minioClient.putObject(bucketName, folderPrefix, Buffer.from(""));
}

View File

@@ -9,7 +9,7 @@ import {
interface setAssetInput {
modelUuid: string;
modelName: string;
position: []; // user ID
position: [];
rotation: object;
eventData: Mixed;
modelfileID: string;
@@ -22,7 +22,7 @@ interface setAssetInput {
interface AssetUpdate {
modelUuid: string;
modelName: string;
position: []; // user ID
position: [];
rotation: object;
isLocked: boolean;
isVisible: boolean;
@@ -98,12 +98,7 @@ export const setAssetModel = async (
},
{ new: true }
);
// return {
// success: true,
// message: "Model updated successfully",
// data: updatevalue,
// organization: organization,
// };
return {
status: "Updated successfully",
data: updatevalue,
@@ -121,21 +116,6 @@ export const setAssetModel = async (
isVisible,
};
// if (eventData) {
// if (eventData?.type === "Conveyor") {
// assetData.eventData = {
// type: eventData.type,
// // point:undefined,
// points: eventData.points,
// };
// } else {
// assetData.eventData = {
// type: eventData.type,
// point: eventData.point,
// // points: undefined
// };
// }
// }
if (eventData) {
const typedEventData = eventData as unknown as {
type: string;
@@ -254,12 +234,7 @@ export const setAssetModel = async (
isVisible: assetDoc.isVisible,
};
}
// return {
// success: true,
// message: "Model created successfully",
// data: assetDatas,
// organization: organization,
// };
return {
status: "Success",
data: assetDatas,
@@ -307,11 +282,6 @@ export const deleteAssetModel = async (
{ new: true }
);
if (!archivedAsset) {
// return {
// success: false,
// status: "Failed to archive asset",
// organization: organization,
// };
return {
status: "Failed to archive asset",
};
@@ -321,13 +291,6 @@ export const deleteAssetModel = async (
{ $set: { isArchive: true } }
);
// return {
// success: true,
// message: "Model deleted successfully",
// data: archivedAsset,
// organization: organization,
// };
return {
status: "Success",
data: archivedAsset,
@@ -364,11 +327,6 @@ export const replaceEventDatas = async (
});
if (!existingModel) {
return { status: "Model not for this UUID" };
// return {
// success: false,
// message: "Model not for this UUID",
// organization: organization,
// };
} else {
const typedEventData = eventData as unknown as {
speed: number;
@@ -384,23 +342,11 @@ export const replaceEventDatas = async (
{ modelUuid, projectId, isArchive: false },
{
points: typedEventData?.points,
// speed: speed,
type: typedEventData?.type || existingModel?.type,
},
{ new: true }
);
// if (updatedModel)
// // return {
// // success: true,
// // message: "Data updated successfully",
// // data: updatedModel,
// // organization: organization,
// // };
// return {
// status: "Success",
// data: updatedModel,
// };
return {
status: "Success",
data: updatedModel,
@@ -448,7 +394,6 @@ export const updateAssetPositionRotation = async (
});
if (!existingAsset) {
return { status: "Asset not found" };
// return res.send("Asset not found");
}
const updateAsset = await assetModel(organization).updateMany(
{
@@ -464,12 +409,10 @@ export const updateAssetPositionRotation = async (
isLocked: isLocked,
}
);
// if (updateAsset)
return {
status: "Success",
data: updateAsset,
};
// return res.status(200).json({ message: "Asset updated successfully" });
} catch (error: unknown) {
if (error instanceof Error) {
return {
@@ -501,7 +444,6 @@ export const getFloorItems = async (
if (!findValues || findValues.length === 0) {
return { status: "floorItems not found" };
// return res.status(200).json({ message: "floorItems not found" });
}
const response = findValues.map((item) => {
@@ -519,8 +461,6 @@ export const getFloorItems = async (
return responseItem;
});
// return res.status(200).json(response);
return {
status: "Success",
data: response,

View File

@@ -68,13 +68,12 @@ export const setWallItems = async (data: IWallSetupData): Promise<IWallItemResul
quaternion,
scale,
},
{ new: true } // Return the updated document
{ new: true }
);
return {
status: "Updated successfully",
data: updatevalue,
};
// res.status(201).json(updatevalue);
} else {
const newValue = await wallItemModel(organization).create({
modelUuid,
@@ -91,7 +90,6 @@ export const setWallItems = async (data: IWallSetupData): Promise<IWallItemResul
status: "wall Item created successfully",
data: newValue,
};
// res.status(201).json(newValue);
}
} catch (error: unknown) {
if (error instanceof Error) {

View File

@@ -42,7 +42,7 @@ export const previousVersion = async (
projectId: projectId,
isArchive: false,
});
// .sort({ version: -1 });
return result;
};
export const generateUntitledProjectName = async (

View File

@@ -45,7 +45,7 @@ export const previousVersion = async (
projectId: projectId,
isArchive: false,
});
// .sort({ version: -1 });
return result;
};
export const generateUntitledProjectName = async (

View File

@@ -56,7 +56,7 @@ export const searchProject = async (data: searchProjectInterface) => {
const userExisting = await existingUser(userId, organization);
if (!userExisting) return { status: "User not found" };
const findprojectName = await projectModel(organization).find({
projectName: { $regex: `${searchName}`, $options: "i" }, // 'i' makes it case-insensitive
projectName: { $regex: `${searchName}`, $options: "i" },
isArchive: false,
});
if (!findprojectName || findprojectName.length === 0)

View File

@@ -11,7 +11,7 @@ import {
interface CreateProjectInput {
projectName: string;
projectUuid: string;
userId: string; // user ID
userId: string;
thumbnail?: string;
sharedUsers?: string[];
organization: string;
@@ -19,7 +19,7 @@ interface CreateProjectInput {
interface updateProjectInput {
projectName: string;
projectId: string;
userId: string; // user ID
userId: string;
thumbnail?: string;
sharedUsers?: string[];
organization: string;

View File

@@ -1,375 +1,364 @@
import { Mixed } from "mongoose";
import EventsDataModel from "../../V1Models/Simulation/eventsDataModel.ts";
import ProductModel from "../../V1Models/Simulation/productModel.ts";
import { existingProjectById, existingUser } from "../helpers/v1projecthelperFns.ts";
import {
existingProjectById,
existingUser,
} from "../helpers/v1projecthelperFns.ts";
interface Iproduct {
productName: string;
productId: string;
eventDatas: {
modelUuid: string
modelName: string
position: [Number]
rotation: [Number]
type: string
speed: string
point: Mixed
points: Mixed
};
userId: string;
organization: string;
projectId: string;
productName: string;
productId: string;
eventDatas: {
modelUuid: string;
modelName: string;
position: [Number];
rotation: [Number];
type: string;
speed: string;
point: Mixed;
points: Mixed;
};
userId: string;
organization: string;
projectId: string;
}
interface IResult {
status: string;
data?: object;
status: string;
data?: object;
}
interface IEventDataDelete {
productId: string;
modelUuid: string
userId: string;
organization: string;
projectId: string;
productId: string;
modelUuid: string;
userId: string;
organization: string;
projectId: string;
}
export const productAdd = async (data: Iproduct): Promise<IResult> => {
try {
const { productName, productId, eventDatas, projectId, userId, organization } = data
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).findOne({
productId: productId, projectId: projectId,
isArchive: false,
});
if (existingProduct) {
const existingEventData = await EventsDataModel(organization).findOne({
productId: productId,
projectId: projectId,
modelUuid: eventDatas.modelUuid,
isArchive: false,
});
if (existingEventData) {
await EventsDataModel(organization).findOneAndUpdate(
{
modelUuid: eventDatas.modelUuid,
productId: productId,
isArchive: false,
},
{
modelUuid: eventDatas?.modelUuid,
modelName: eventDatas?.modelName,
position: eventDatas?.position,
rotation: eventDatas?.rotation,
type: eventDatas?.type,
speed: eventDatas?.speed,
point: eventDatas?.point,
points: eventDatas?.points,
}
);
return {
status: "EventData updated successfully"
}
// return res
// .status(200)
// .json({ message: "EventData updated successfully" });
} else {
await EventsDataModel(organization).create({
productId: productId,
modelUuid: eventDatas?.modelUuid,
modelName: eventDatas?.modelName,
position: eventDatas?.position,
rotation: eventDatas?.rotation,
type: eventDatas?.type,
speed: eventDatas?.speed,
point: eventDatas?.point,
points: eventDatas?.points,
});
return {
status: "EventData add successfully"
}
// return res
// .status(201)
// .json({ message: "EventData add successfully" });
}
} else {
const newProduct = await ProductModel(organization).create({
productId: productId,
productName: productName,
});
if (newProduct) {
if (eventDatas) {
await EventsDataModel(organization).create({
productId: productId,
modelUuid: eventDatas?.modelUuid,
modelName: eventDatas?.modelName,
position: eventDatas?.position,
rotation: eventDatas?.rotation,
type: eventDatas?.type,
speed: eventDatas?.speed,
point: eventDatas?.point,
points: eventDatas?.points,
});
}
}
return {
status: "Success"
}
// return res
// .status(201)
// .json({ message: "Product created successfully" });
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
}
export const getProductDatas = async (data: Iproduct): Promise<IResult> => {
try {
const { productId, projectId, userId, organization } = data
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).findOne({
productId: productId, projectId: projectId,
isArchive: false,
});
if (!existingProduct)
return { status: "Product not found" };
// return res.status(404).json({ message: "Product not found" });
const existingEventDatas = await EventsDataModel(organization)
.find({ productId: productId, projectId: projectId })
.select("-productId");
return { status: "Success", data: existingEventDatas };
// return res.status(200).json(existingEventDatas);
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
}
export const productDataDelete = async (data: Iproduct): Promise<IResult> => {
try {
const { productId, projectId, userId, organization } = data
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).findOne({
productId: productId,
isArchive: false,
});
if (!existingProduct)
return { status: "Product not found" };
// return res.status(404).json({ message: "Product not found" });
await ProductModel(organization).findOneAndUpdate(
{ productId: productId, projectId: projectId },
{
isArchive: true,
},
{ new: true }
);
const existingEventDatas = await EventsDataModel(organization).find({
productId: productId,
});
if (existingEventDatas) {
await EventsDataModel(organization).updateMany(
{ productId, projectId },
{ $set: { isArchive: true } }
);
}
return {
status: "Success",
// data: assetDatas,
};
// return res.status(201).json({ message: "product deleted successfully" });
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
}
export const EventDataDelete = async (data: IEventDataDelete): Promise<IResult> => {
try {
const { modelUuid, productId, projectId, userId, organization } = data
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).findOne({
productId: productId, projectId: projectId,
isArchive: false,
});
if (!existingProduct)
return { status: "Product not found" };
// return res.status(404).json({ message: "Product not found" });
try {
const {
productName,
productId,
eventDatas,
projectId,
userId,
organization,
} = data;
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).findOne({
productId: productId,
projectId: projectId,
isArchive: false,
});
if (existingProduct) {
const existingEventData = await EventsDataModel(organization).findOne({
productId: productId,
projectId: projectId,
modelUuid: eventDatas.modelUuid,
isArchive: false,
});
if (existingEventData) {
await EventsDataModel(organization).findOneAndUpdate(
{ productId: productId, projectId: projectId, modelUuid: modelUuid },
{
isArchive: true,
},
{ new: true }
);
// return res
// .status(201)
// .json({ message: "EventData deleted successfully" });
return {
status: "Success",
// data: assetDatas,
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
}
export const AllProductDatas = async (data: IEventDataDelete): Promise<IResult> => {
try {
const { projectId, userId, organization } = data
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).find({
{
modelUuid: eventDatas.modelUuid,
productId: productId,
isArchive: false,
});
if (!existingProduct) {
// return res.status(404).json({ message: "No products found" });
return {
status: "No products found",
// data: result,
};
}
const result = [];
for (const product of existingProduct) {
const eventDatas = await EventsDataModel(organization)
.find({ projectId: product.projectId, productId: product.productId, isArchive: false })
.select("-productId -isArchive -createdAt -updatedAt -__v -_id");
result.push({
// product: {
projectId: product.projectId,
productName: product.productName,
productId: product.productId,
eventDatas,
// },
});
}
// return res.status(200).json(result);
},
{
modelUuid: eventDatas?.modelUuid,
modelName: eventDatas?.modelName,
position: eventDatas?.position,
rotation: eventDatas?.rotation,
type: eventDatas?.type,
speed: eventDatas?.speed,
point: eventDatas?.point,
points: eventDatas?.points,
}
);
return {
status: "Success",
data: result,
status: "EventData updated successfully",
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
} else {
await EventsDataModel(organization).create({
productId: productId,
modelUuid: eventDatas?.modelUuid,
modelName: eventDatas?.modelName,
position: eventDatas?.position,
rotation: eventDatas?.rotation,
type: eventDatas?.type,
speed: eventDatas?.speed,
point: eventDatas?.point,
points: eventDatas?.points,
});
return {
status: "EventData add successfully",
};
}
} else {
const newProduct = await ProductModel(organization).create({
productId: productId,
productName: productName,
});
if (newProduct) {
if (eventDatas) {
await EventsDataModel(organization).create({
productId: productId,
modelUuid: eventDatas?.modelUuid,
modelName: eventDatas?.modelName,
position: eventDatas?.position,
rotation: eventDatas?.rotation,
type: eventDatas?.type,
speed: eventDatas?.speed,
point: eventDatas?.point,
points: eventDatas?.points,
});
}
}
return {
status: "Success",
};
}
}
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const getProductDatas = async (data: Iproduct): Promise<IResult> => {
try {
const { productId, projectId, userId, organization } = data;
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).findOne({
productId: productId,
projectId: projectId,
isArchive: false,
});
if (!existingProduct) return { status: "Product not found" };
const existingEventDatas = await EventsDataModel(organization)
.find({ productId: productId, projectId: projectId })
.select("-productId");
return { status: "Success", data: existingEventDatas };
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const productDataDelete = async (data: Iproduct): Promise<IResult> => {
try {
const { productId, projectId, userId, organization } = data;
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).findOne({
productId: productId,
isArchive: false,
});
if (!existingProduct) return { status: "Product not found" };
await ProductModel(organization).findOneAndUpdate(
{ productId: productId, projectId: projectId },
{
isArchive: true,
},
{ new: true }
);
const existingEventDatas = await EventsDataModel(organization).find({
productId: productId,
});
if (existingEventDatas) {
await EventsDataModel(organization).updateMany(
{ productId, projectId },
{ $set: { isArchive: true } }
);
}
return {
status: "Success",
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const EventDataDelete = async (
data: IEventDataDelete
): Promise<IResult> => {
try {
const { modelUuid, productId, projectId, userId, organization } = data;
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).findOne({
productId: productId,
projectId: projectId,
isArchive: false,
});
if (!existingProduct) return { status: "Product not found" };
await EventsDataModel(organization).findOneAndUpdate(
{ productId: productId, projectId: projectId, modelUuid: modelUuid },
{
isArchive: true,
},
{ new: true }
);
return {
status: "Success",
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const AllProductDatas = async (
data: IEventDataDelete
): Promise<IResult> => {
try {
const { projectId, userId, organization } = data;
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).find({
isArchive: false,
});
if (!existingProduct) {
return {
status: "No products found",
};
}
const result = [];
for (const product of existingProduct) {
const eventDatas = await EventsDataModel(organization)
.find({
projectId: product.projectId,
productId: product.productId,
isArchive: false,
})
.select("-productId -isArchive -createdAt -updatedAt -__v -_id");
result.push({
projectId: product.projectId,
productName: product.productName,
productId: product.productId,
eventDatas,
});
}
return {
status: "Success",
data: result,
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
};
export const productRename = async (data: Iproduct): Promise<IResult> => {
try {
const { productName, productId, projectId, userId, organization } = data
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).findOne({
productId: productId, projectId: projectId,
isArchive: false,
});
try {
const { productName, productId, projectId, userId, organization } = data;
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const LivingProject = await existingProjectById(
projectId,
organization,
userId
);
if (!LivingProject) return { status: "Project not found" };
const existingProduct = await ProductModel(organization).findOne({
productId: productId,
projectId: projectId,
isArchive: false,
});
if (!existingProduct)
return { status: "Product not found" };
if (!existingProduct) return { status: "Product not found" };
await ProductModel(organization).findOneAndUpdate(
{ productId: productId },
{
productName: productName,
},
{ new: true }
);
await ProductModel(organization).findOneAndUpdate(
{ productId: productId },
{
productName: productName,
},
{ new: true }
);
// return res.status(201).json({ message: "product Rename successfully" });
return {
status: "Success",
// data: assetDatas,
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
return {
status: "Success",
};
} catch (error: unknown) {
if (error instanceof Error) {
return {
status: error.message,
};
} else {
return {
status: "An unexpected error occurred",
};
}
}
}
};

View File

@@ -11,7 +11,7 @@ import UsersDataModel from "../../V1Models/Auth/user.ts";
interface CreateProjectInput {
projectName: string;
projectUuid: string;
userId: string; // user ID
userId: string;
thumbnail?: string;
sharedUsers?: string[];
organization: string;
@@ -19,7 +19,7 @@ interface CreateProjectInput {
interface IProjectDuplicate {
projectName: string;
projectUuid: string;
userId: string; // user ID
userId: string;
thumbnail?: string;
sharedUsers?: string[];
organization: string;
@@ -27,7 +27,7 @@ interface IProjectDuplicate {
interface updateProjectInput {
projectName: string;
projectId: string;
userId: string; // user ID
userId: string;
thumbnail?: string;
sharedUsers?: string[];
organization: string;
@@ -116,9 +116,7 @@ export const GetAllProjects = async (data: GetProjectsInterface) => {
await existingUser(userId, organization);
if (!existingUser) return { status: "User not found" };
let filter = { isArchive: false } as RoleFilter;
// if (role === "User") {
// filter.createdBy = userId;
// }
const projectDatas = await projectModel(organization)
.find(filter)
.select("_id projectName createdBy thumbnail createdAt projectUuid");
@@ -135,9 +133,7 @@ export const DeleteProject = async (data: ProjectDelInterface) => {
if (!ExistingUser) return { status: "User not found" };
let filter = { _id: projectId, isArchive: false } as RoleFilter;
// if (role === "User") {
// filter.createdBy = userId;
// }
const existingProject = await projectModel(organization).findOne(filter);
console.log("existingProject: ", existingProject);
if (!existingProject) return { status: "Project not found" };
@@ -158,9 +154,7 @@ export const updateProject = async (data: updateProjectInput) => {
const ExistingUser = await existingUser(userId, organization);
if (!ExistingUser) return { status: "User not found" };
let filter = { _id: projectId, isArchive: false } as RoleFilter;
// if (role === "User") {
// filter.createdBy = userId;
// }
const existingProject = await projectModel(organization).findOne(filter);
if (!existingProject) return { status: "Project not found" };
if (projectName !== undefined) projectName;
@@ -245,9 +239,7 @@ export const viewProject = async (data: ProjectInterface) => {
isArchive: false,
});
let filter = { _id: projectId, isArchive: false } as RoleFilter;
// if (role === "User") {
// filter.createdBy = userId;
// }
const existingProject = await projectModel(organization).findOne(filter);
if (!existingProject) return { status: "Project not found" };
const newArr = RecentUserDoc?.recentlyViewed || [];

View File

@@ -36,12 +36,8 @@ export const RecentlyAdded = async (data: IRecentData) => {
model: projectModel(organization),
select: "_id",
});
let filter = { isArchive: false } as RoleFilter;
// if (role === "User") {
// filter.createdBy = userId;
// }
const populatedProjects = userRecentData.recentlyViewed as IProject[];
console.log("populatedProjects: ", populatedProjects);
const RecentDatas = await Promise.all(
populatedProjects.map(async (project) => {
const projectExisting = await projectModel(organization)
@@ -50,7 +46,6 @@ export const RecentlyAdded = async (data: IRecentData) => {
return projectExisting;
})
);
console.log("RecentDatas: ", RecentDatas);
const filteredProjects = RecentDatas.filter(Boolean);
console.log("filteredProjects: ", filteredProjects);
@@ -65,7 +60,7 @@ export const searchProject = async (data: searchProjectInterface) => {
const userExisting = await existingUser(userId, organization);
if (!userExisting) return { status: "User not found" };
const findprojectName = await projectModel(organization).find({
projectName: { $regex: `${searchName}`, $options: "i" }, // 'i' makes it case-insensitive
projectName: { $regex: `${searchName}`, $options: "i" },
isArchive: false,
});
if (!findprojectName || findprojectName.length === 0)

View File

@@ -19,9 +19,7 @@ export const TrashDatas = async (data: IOrg) => {
try {
const { organization, role, userId } = data;
let filter = { isArchive: true, isDeleted: false } as RoleFilter;
// if (role === "User") {
// filter.createdBy = userId;
// }
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
const TrashLists = await projectModel(organization).find(filter);
@@ -62,9 +60,7 @@ export const RestoreTrashData = async (data: IRestore) => {
const UserExists = await existingUser(userId, organization);
if (!UserExists) return { status: "User not found" };
let filter = { isArchive: true, _id: projectId } as RoleFilter;
// if (role === "User") {
// filter.createdBy = userId;
// }
const findProject = await projectModel(organization).findOne(filter);
if (!findProject) return { status: "Project not found" };
const restoreData = await projectModel(organization).findOneAndUpdate(

View File

@@ -48,7 +48,6 @@ class VersionService {
userId: string,
description?: string
) {
// Create new version
const newVersion = await this.createNewVersion(
db,
projectId,
@@ -56,7 +55,6 @@ class VersionService {
description
);
// Get all assets from previous version
const previousVersion = parseFloat((newVersion.version - 0.1).toFixed(1));
const previousVersionDoc = await versionModel(db).findOne({
projectId,
@@ -73,7 +71,6 @@ class VersionService {
});
}
// Copy assets to new version
const newAssets = await Promise.all(
previousAssets.map(async (asset) => {
console.log("previousAssets: ", previousAssets);

View File

@@ -45,13 +45,12 @@ export class WallItems {
quaternion,
scale,
},
{ new: true } // Return the updated document
{ new: true }
);
return {
state: "Updated successfully",
data: updatevalue,
};
// res.status(201).json(updatevalue);
} else {
const newValue = await wallItemModel(organization).create({
modelUuid,
@@ -67,16 +66,12 @@ export class WallItems {
state: "wall Item created successfully",
data: newValue,
};
// res.status(201).json(newValue);
}
// Send response with the created document
} catch (error:unknown) {
const err = error as Error;
console.error("Error creating wallitems:", error);
return { state: "Failed to create wallitems", data: { message: err.message } };
// return { state: "Failed to create wallitems", data: error } };
// res.status(500).json({ message: "Failed to create wallitems" });
}
}
static async getWallItems(req: Request, res: Response) {

View File

@@ -15,8 +15,6 @@ const doc = {
description: "Description",
},
host: "185.100.212.76:5000",
// host: "192.168.0.102:5000",
// basePath: "/api/v1",
schemes: ["http"],
};

View File

@@ -1,34 +1,34 @@
import { MongoClient } from 'mongodb'
import { MongoClient } from "mongodb";
export default async function mongoAdminCreation() {
const uri = process.env.MONGO_URI!; // Replace with your MongoDB URI
const client = new MongoClient(uri);
const user = {
user:"admin",
pwd: process.env.MONGO_PASSWORD!,
roles: [{ role: "root", db: process.env.MONGO_AUTH_DB || "admin" }],
};
try {
await client.connect();
const db = client.db('admin'); // Specify the actual database where the user should be created
// Check if the user already exists
const userExists = await db.collection('system.users').findOne({ user: user.user});
if (userExists) {
console.log(`User ${user} already exists`);
return; // Exit if the user already exists
}
// Create the user
await db.command({ createUser: user.user, pwd: user.pwd, roles: user.roles });
console.log("User created successfully!")
} catch (error) {
console.error("Error creating user:",error);
} finally {
await client.close();
const uri = process.env.MONGO_URI!;
const client = new MongoClient(uri);
const user = {
user: "admin",
pwd: process.env.MONGO_PASSWORD!,
roles: [{ role: "root", db: process.env.MONGO_AUTH_DB || "admin" }],
};
try {
await client.connect();
const db = client.db("admin");
const userExists = await db
.collection("system.users")
.findOne({ user: user.user });
if (userExists) {
console.log(`User ${user} already exists`);
return;
}
await db.command({
createUser: user.user,
pwd: user.pwd,
roles: user.roles,
});
console.log("User created successfully!");
} catch (error) {
console.error("Error creating user:", error);
} finally {
await client.close();
}
// mongoAdminCreation
}

View File

@@ -77,9 +77,7 @@ const tokenValidator = async (
req.user = decoded;
next();
} catch (err) {
// res.status(401).json({
// msg: "Invalid Token",
// });
if (!refresh_token) {
res.status(403).json({
success: false,

View File

@@ -3,11 +3,11 @@ ARG NODE_VERSION=lts
FROM node:${NODE_VERSION}-alpine AS development
# Use production node environment by default.
ENV NODE_ENV development
ENV NODE_ENV=development
WORKDIR /usr/src/app
RUN npm install -g tsx
RUN npm install -g tsx --ignore-scripts
COPY package.json /usr/src/app/package.json
@@ -15,7 +15,7 @@ COPY package.json /usr/src/app/package.json
# COPY package-lock.json /usr/src/app/package-lock.json
RUN npm install
RUN npm install --ignore-scripts
# Run the application as a non-root user.
USER root

View File

@@ -1,21 +1,17 @@
import express from "express"
import { Response, Request } from "express";
import express,{ Response, Request } from "express";
import http from "http";
import dotenv from "dotenv"; // Import dotenv
import dotenv from "dotenv";
dotenv.config();
import { initSocketServer } from "./socket/socketManager.ts";
import { SocketServer } from "./manager/manager.ts";
const app = express();
const PORT = process.env.SOCKET_PORT;
const server = http.createServer(app);
app.get('/', (req: Request, res: Response) => {
res.send('Hello, I am Major-Dwinzo RealTime!');
app.get("/", (req: Request, res: Response) => {
res.send("Hello, I am Major-Dwinzo RealTime!");
});
// initSocketServer(server);
SocketServer(server)
server.listen(PORT, () => {
console.log(`socket-Server is running on http://localhost:${PORT}`);

View File

@@ -21,14 +21,14 @@ import { getUserRole } from '../utils/getUsers.ts';
interface UserSocketInfo {
socketId: string;
userId: string;
role: string; // e.g., "admin" or "user"
role: string;
}
const connectedUsersByOrg: { [organization: string]: UserSocketInfo[] } = {};
export const SocketServer = (httpServer: any) => {
const io = new Server(httpServer, {
cors: {
origin: '*', // Allow CORS for all origins (adjust in production)
origin: '*',
methods: ['GET', 'POST'],
},
});
@@ -43,15 +43,15 @@ export const SocketServer = (httpServer: any) => {
visualization: io.of("/Visualization"),
};
// const onlineUsers = new Map<string, Set<string>>();
const onlineUsers: { [organization: string]: Set<string> } = {};
const handleNamespace = (namespace: any, ...eventHandlers: Function[]) => {
namespace.use(async (socket: Socket, next: any) => {
// console.log(`🔌 Connecting to namespace: ${namespace.name}`);
const token = socket.handshake.auth.token;
// const token = socket.handshake.query.token as string;
const jwt_secret = process.env.JWT_SECRET as string;
if (!token) {
@@ -63,13 +63,13 @@ export const SocketServer = (httpServer: any) => {
return next(new Error("Server configuration error: Missing secret"));
}
try {
// 1. Verify token
const decoded = jwt.verify(token, jwt_secret) as {
userId: string;
Email: string;
organization: string
};
// 2. Find user in DB
const user = await AuthModel(decoded.organization).findOne({ _id: decoded.userId, Email: decoded.Email, });
if (!user) {
@@ -77,12 +77,12 @@ export const SocketServer = (httpServer: any) => {
return next(new Error("Authentication error: User not found"));
}
// 3. Attach to socket for later use
(socket as any).user = {
// ...user.toObject(), // convert Mongoose doc to plain object
organization: decoded.organization, // manually add org
Email: decoded.Email, // manually add org
userId: decoded.userId, // manually add org
organization: decoded.organization,
Email: decoded.Email,
userId: decoded.userId,
};
next();
@@ -93,38 +93,21 @@ export const SocketServer = (httpServer: any) => {
}
});
namespace.on("connection",async (socket: Socket) => {
// Extract organization from query parameters
const user = (socket as any).user;
const organization = user.organization;
const Email = user.Email;
const userId = user.userId;
// namespace.on("connection", (socket: Socket) => {
// console.log(`✅ Client connected to ${namespace.name}: ${socket.id}`);
// // Extract organization from query parameters
// const organization = socket.handshake.query.organization as string;
// const email = socket.handshake.query.email as string;
// // const {organization,email} = socket.handshake.auth
// console.log(`🔍 Received organization: ${organization}`);
if (organization) {
socket.join(organization);
// console.log(`🔹 Socket ${socket.id} joined room: ${organization}`);
}
// // Handle all events
// if (organization && email) {
// if (!onlineUsers[organization]) {
// onlineUsers[organization] = new Set();
// }
// onlineUsers[organization].add(socket.id);
// }
const role = await getUserRole(userId, organization);
if (role === "Admin") {
socket.join(`${organization}_admins`);
}
// Save user info somewhere
if (organization && userId && role) {
if (!connectedUsersByOrg[organization]) {
connectedUsersByOrg[organization] = [];
@@ -136,30 +119,22 @@ export const SocketServer = (httpServer: any) => {
role,
});
// console.log(`🔗 User connected: ${userId} with role ${role} in ${organization}`);
// console.log("🧩 connectedUsersByOrg: ", connectedUsersByOrg);
} else {
console.warn(`❌ Cannot store user. Missing data:`,);
}
// userStatus(EVENTS.connection, socket, socket.handshake.auth, socket);
socket.onAny((event: string, data: any, callback: any) => {
eventHandlers.forEach(handler =>
handler(event, socket, io, data, connectedUsersByOrg, callback) // ✅ fixed
handler(event, socket, io, data, connectedUsersByOrg, callback)
);
// eventHandlers.forEach(handler =>
// handler(event, socket,io,namespace, data, connectedUsersByOrg, callback));
});
// Handle disconnection
socket.on("disconnect", () => {
onlineUsers[organization]?.delete(socket.id);
if (onlineUsers[organization]?.size === 0) delete onlineUsers[organization];
// userStatus(EVENTS.disconnect, socket, socket.handshake.auth, socket);
});
// Handle reconnection (Auto rejoin)
socket.on("reconnect", (attempt: number) => {
if (organization) {

View File

@@ -1,208 +1,6 @@
import assetModel from "../../../shared/model/builder/assets/asset-Model.ts";
import actionModel from "../../../shared/model/simulation/actionmodel.ts";
import EventsDataModel from "../../../shared/model/simulation/eventsDataModel.ts";
import triggerModel from "../../../shared/model/simulation/triggersmodel.ts";
// export const setAssetModel = async (data: any) => {
// const {
// modelUuid,
// modelName,
// position,
// rotation,
// eventData,
// modelfileID,
// isLocked,
// isVisible,
// organization,
// } = data;
// try {
// const findvalue = await assetModel(organization).findOne({
// modelUuid: modelUuid,
// // modelName: modelName,
// isArchive: false,
// });
// if (findvalue) {
// const updatevalue = await assetModel(organization).findOneAndUpdate(
// { modelUuid: modelUuid, isArchive: false },
// {
// modelName: modelName,
// position: position,
// rotation: rotation,
// isVisible: isVisible,
// isLocked: isLocked,
// },
// { new: true }
// );
// return {
// success: true,
// message: "Model updated successfully",
// data: updatevalue,
// organization: organization,
// };
// } else {
// let assetData: any = {
// modelUuid,
// modelName,
// position,
// modelfileID,
// rotation,
// isLocked,
// isVisible,
// };
// if (eventData) {
// if (eventData.type === "Conveyor") {
// assetData.speed = eventData.speed;
// } else if (eventData.type === "Vehicle") {
// assetData.speed = eventData.points.speed;
// if (!eventData.points) {
// return {
// success: false,
// message: "Vehicle points must be a single object",
// organization: organization,
// };
// }
// // if (eventData.points.rotation) {
// // return {
// // success: false,
// // message: "Rotation is not allowed for Vehicle points",
// // organization: organization,
// // };
// // }
// if (eventData.points.triggers) {
// return {
// success: false,
// message: "triggers is not allowed for Vehicle points",
// organization: organization,
// };
// }
// }
// assetData.points = eventData.points;
// assetData.type = eventData.type;
// }
// const assetDoc = await assetModel(organization).create(assetData);
// await assetDoc.save();
// let assetDatas;
// if (assetDoc.type === "Conveyor") {
// assetDatas = {
// modelUuid: assetDoc.modelUuid,
// modelName: assetDoc.modelName,
// modelfileID: assetDoc.modelfileID,
// position: assetDoc.position,
// rotation: assetDoc.rotation,
// isLocked: assetDoc.isLocked,
// isVisible: assetDoc.isVisible,
// eventData: {
// points: assetDoc.points,
// type: assetDoc.type,
// speed: assetDoc.speed,
// },
// };
// } else if (assetDoc.type === "Vehicle") {
// assetDatas = {
// modelUuid: assetDoc.modelUuid,
// modelName: assetDoc.modelName,
// modelfileID: assetDoc.modelfileID,
// position: assetDoc.position,
// rotation: assetDoc.rotation,
// isLocked: assetDoc.isLocked,
// isVisible: assetDoc.isVisible,
// eventData: {
// points: assetDoc.points,
// type: assetDoc.type,
// },
// };
// } else if (assetDoc.type === "ArmBot") {
// assetDatas = {
// modelUuid: assetDoc.modelUuid,
// modelName: assetDoc.modelName,
// modelfileID: assetDoc.modelfileID,
// position: assetDoc.position,
// rotation: assetDoc.rotation,
// isLocked: assetDoc.isLocked,
// isVisible: assetDoc.isVisible,
// eventData: {
// points: assetDoc.points,
// type: assetDoc.type,
// },
// };
// } else if (assetDoc.type === "StaticMachine") {
// assetDatas = {
// modelUuid: assetDoc.modelUuid,
// modelName: assetDoc.modelName,
// modelfileID: assetDoc.modelfileID,
// position: assetDoc.position,
// rotation: assetDoc.rotation,
// isLocked: assetDoc.isLocked,
// isVisible: assetDoc.isVisible,
// eventData: {
// points: assetDoc.points,
// type: assetDoc.type,
// },
// };
// } else {
// assetDatas = {
// modelUuid: assetDoc.modelUuid,
// modelName: assetDoc.modelName,
// modelfileID: assetDoc.modelfileID,
// position: assetDoc.position,
// rotation: assetDoc.rotation,
// isLocked: assetDoc.isLocked,
// isVisible: assetDoc.isVisible,
// };
// }
// return {
// success: true,
// message: "Model created successfully",
// data: assetDatas,
// organization: organization,
// };
// }
// } catch (error: any) {
// // console.error("Error creating flooritems:", error);
// return {
// success: false,
// message: error?.message || "Error occurred while ModelAsset",
// error,
// organization: organization,
// };
// }
// };
// export const deleteAssetModel = async (data: any) => {
// const { modelUuid, modelName, organization } = data;
// try {
// const findValue = await assetModel(organization).findOneAndDelete({
// modelUuid: modelUuid,
// modelName: modelName,
// isArchive: false,
// });
// if (!findValue) {
// return {
// success: false,
// message: "model not found",
// organization: organization,
// };
// } else {
// return {
// success: true,
// message: "Model deleted successfully",
// data: findValue,
// organization: organization,
// };
// }
// } catch (error) {
// // console.error('Error get flooritems:', error);
// return {
// success: false,
// message: "Failed to delete asset",
// error,
// organization: organization,
// };
// }
// };
//update 30/4..//setAssetModel//deleteAssetModel...........
export const setAssetModel = async (data: any) => {
const {
modelUuid,
@@ -218,7 +16,6 @@ export const setAssetModel = async (data: any) => {
try {
const findvalue = await assetModel(organization).findOne({
modelUuid: modelUuid,
// modelName: modelName,
isArchive: false,
});
@@ -256,49 +53,16 @@ export const setAssetModel = async (data: any) => {
if (eventData?.type === "Conveyor") {
assetData.eventData = {
type: eventData.type,
// point:undefined,
points: eventData.points,
};
} else {
assetData.eventData = {
type: eventData.type,
point: eventData.point,
// points: undefined
};
}
}
// if (eventData) {
// if (eventData.type === "Conveyor") {
// assetData.speed = eventData.speed;
// } else if (eventData.type === "Vehicle") {
// assetData.speed = eventData.points.speed;
// if (!eventData.points) {
// return {
// success: false,
// message: "Vehicle points must be a single object",
// organization: organization,
// };
// }
// // if (eventData.points.rotation) {
// // return {
// // success: false,
// // message: "Rotation is not allowed for Vehicle points",
// // organization: organization,
// // };
// // }
// if (eventData.points.triggers) {
// return {
// success: false,
// message: "triggers is not allowed for Vehicle points",
// organization: organization,
// };
// }
// }
// assetData.points = eventData.points;
// assetData.type = eventData.type;
// }
const assetDoc = await assetModel(organization).create(assetData);
await assetDoc.save();
let assetDatas;
@@ -374,7 +138,6 @@ export const setAssetModel = async (data: any) => {
};
}
} catch (error: any) {
// console.error("Error creating flooritems:", error);
return {
success: false,
message: error?.message || "Error occurred while ModelAsset",
@@ -392,11 +155,7 @@ export const deleteAssetModel = async (data: any) => {
modelName,
isArchive: false,
});
// const findmodelValue = await assetModel(organization).findOne({
// modelUuid: modelUuid,
// modelName: modelName,
// isArchive: false,
// });
if (!asset) {
return {
success: false,
@@ -416,22 +175,11 @@ export const deleteAssetModel = async (data: any) => {
organization: organization,
};
}
const updatedEvents = await EventsDataModel(organization).updateMany(
await EventsDataModel(organization).updateMany(
{ modelUuid },
{ $set: { isArchive: true } }
);
// const findProductEventData = await EventsDataModel(organization).find(modelUuid)
// console.log('findProductEventData: ', findProductEventData);
// if (findProductEventData) {
// for (const event of findProductEventData) {
// console.log("Event ID:", event);
// await EventsDataModel(organization).updateMany(
// { modelUuid },
// { $set: { isArchive: true } }
// );
// }
// }
return {
success: true,
message: "Model deleted successfully",
@@ -439,7 +187,6 @@ export const deleteAssetModel = async (data: any) => {
organization: organization,
};
} catch (error) {
// console.error('Error get flooritems:', error);
return {
success: false,
message: "Failed to delete asset",
@@ -466,14 +213,11 @@ export const replaceEventDatas = async (data: any) => {
if (existingModel.type === "Conveyor") {
speed = eventData?.speed;
}
// if (existingModel.type === "Vehicle") {
// speed = eventData?.points?.speed;
// }
const updatedModel = await assetModel(organization).findOneAndUpdate(
{ modelUuid, isArchive: false },
{
points: eventData?.points,
// speed: speed,
type: eventData?.type || existingModel?.type,
},
{ new: true }

View File

@@ -1,53 +1,94 @@
import { Request, Response } from "express";
import floorItemsModel from "../../../shared/model/assets/flooritems-Model.ts";
export const setFloorItems = async (data: any) => {
try {
const { modelfileID,modelUuid, modelName, position, rotation,isLocked,isVisible, organization } = data
try {
const {
modelfileID,
modelUuid,
modelName,
position,
rotation,
isLocked,
isVisible,
organization,
} = data;
const findvalue = await floorItemsModel(organization).findOne({
modelUuid: modelUuid,
modelName: modelName,
});
const findvalue = await floorItemsModel(organization).findOne({ modelUuid: modelUuid, modelName: modelName })
if (findvalue) {
if (findvalue) {
const updatevalue = await floorItemsModel(organization).findOneAndUpdate(
{ modelUuid: modelUuid, modelName: modelName },
{
position: position,
rotation: rotation,
isVisible: isVisible,
isLocked: isLocked,
},
{ new: true }
);
return {
success: true,
message: "flooritems updated",
data: updatevalue,
organization: organization,
};
} else {
const newValue = await floorItemsModel(organization).create({
modelUuid,
modelName,
modelfileID,
position,
rotation,
isLocked,
isVisible,
});
const updatevalue = await floorItemsModel(organization).findOneAndUpdate(
{ modelUuid: modelUuid, modelName: modelName }, { position: position, rotation: rotation ,isVisible:isVisible,isLocked:isLocked}, { new: true });
return { success: true, message: 'flooritems updated', data: updatevalue,organization:organization }
} else {
const newValue = await floorItemsModel(organization).create({ modelUuid, modelName, modelfileID,position, rotation,isLocked,isVisible });
return { success: true, message: 'flooritem created', data: newValue,organization:organization }
}
// Send response with the created document
} catch (error) {
console.error('Error creating flooritems:', error);
return { success: false, message: 'Error creating or updating camera', error }
}
}
export const deleteFloorItems = async (data: any)=>{
try {
const { modelUuid,modelName,organization } = data;
const findValue = await floorItemsModel(organization).findOneAndDelete({modelUuid:modelUuid,modelName:modelName})
if (!findValue) {
return { success: false, message: 'model not found',organization:organization }
} else {
return { success: true, message: 'flooritem deleted', data: findValue,organization:organization }
}
} catch (error) {
console.error('Error get flooritems:', error);
return { success: false, message: 'Failed to delete flooritems', error }
}
return {
success: true,
message: "flooritem created",
data: newValue,
organization: organization,
};
}
} catch (error) {
console.error("Error creating flooritems:", error);
return {
success: false,
message: "Error creating or updating camera",
error,
};
}
};
export const deleteFloorItems = async (data: any) => {
try {
const { modelUuid, modelName, organization } = data;
const findValue = await floorItemsModel(organization).findOneAndDelete({
modelUuid: modelUuid,
modelName: modelName,
});
if (!findValue) {
return {
success: false,
message: "model not found",
organization: organization,
};
} else {
return {
success: true,
message: "flooritem deleted",
data: findValue,
organization: organization,
};
}
} catch (error) {
console.error("Error get flooritems:", error);
return { success: false, message: "Failed to delete flooritems", error };
}
};

View File

@@ -31,7 +31,7 @@ export const setWallItems = async (data: any) => {
quaternion,
scale,
},
{ new: true } // Return the updated document
{ new: true }
);
return {
success: true,
@@ -58,8 +58,6 @@ export const setWallItems = async (data: any) => {
organization: organization,
};
}
// Send response with the created document
} catch (error) {
console.error("Error creating wallIitem:", error);
return {

View File

@@ -1,31 +1,45 @@
import { Request, Response } from "express";
import { Socket } from "socket.io";
import cameraModel from "../../../shared/model/camera/camera-Model.ts";
export const createCamera = async (data: any,) => {
const { userId, position, target, organization,rotation } = data
try {
export const createCamera = async (data: any) => {
const { userId, position, target, organization, rotation } = data;
try {
const findCamera = await cameraModel(organization).findOne({
userId: userId,
});
if (findCamera) {
const updateCamera = await cameraModel(organization).findOneAndUpdate(
{ userId: userId },
{ position: position, target: target, rotation: rotation },
{ new: true }
);
return {
success: true,
message: "Camera updated",
data: updateCamera,
organization: organization,
};
} else {
const newCamera = await cameraModel(organization).create({
userId,
position,
target,
rotation,
});
const findCamera = await cameraModel(organization).findOne({ userId: userId })
if (findCamera) {
const updateCamera = await cameraModel(organization).findOneAndUpdate(
{ userId: userId }, { position: position, target: target,rotation:rotation }, { new: true });
// io.emit('cameraUpdateResponse', { success: true, message: 'Camera updated', data: updateCamera });
return { success: true, message: 'Camera updated', data: updateCamera,organization:organization}
}
else {
const newCamera = await cameraModel(organization).create({ userId, position, target,rotation })
return { success: true, message: 'Camera created' ,data:newCamera,organization:organization}
}
// Send response with the created document
} catch (error) {
console.error('Error creating camera:', error);
return { success: false, message: 'Error creating or updating camera', error, organization:organization}
return {
success: true,
message: "Camera created",
data: newCamera,
organization: organization,
};
}
}
} catch (error) {
console.error("Error creating camera:", error);
return {
success: false,
message: "Error creating or updating camera",
error,
organization: organization,
};
}
};

View File

@@ -1,33 +1,55 @@
import { Request, Response } from "express";
import environmentModel from "../../../shared/model/environments/environments-Model.ts";
export const setEnvironment = async (data: any) => {
const {
userId,
roofVisibility,
wallVisibility,
shadowVisibility,
organization,
} = data;
try {
const findvalue = await environmentModel(organization).findOne({
userId: userId,
});
if (findvalue) {
const updatevalue = await environmentModel(organization).findOneAndUpdate(
{ userId: userId },
{
roofVisibility: roofVisibility,
wallVisibility: wallVisibility,
shadowVisibility: shadowVisibility,
},
{ new: true }
);
return {
success: true,
message: "evironments updated",
data: updatevalue,
organization: organization,
};
} else {
const newValue = await environmentModel(organization).create({
userId,
roofVisibility,
wallVisibility,
shadowVisibility,
});
export const setEnvironment = async (data: any,) => {
const { userId,roofVisibility,wallVisibility,shadowVisibility, organization } = data
try {
const findvalue = await environmentModel(organization).findOne({ userId: userId })
if (findvalue) {
const updatevalue = await environmentModel(organization).findOneAndUpdate(
{ userId: userId }, { roofVisibility:roofVisibility,wallVisibility:wallVisibility,shadowVisibility:shadowVisibility }, { new: true });
// res.status(201).json(updatevalue);
return { success: true, message: 'evironments updated', data: updatevalue,organization:organization }
} else {
const newValue = await environmentModel(organization).create({ userId, roofVisibility, wallVisibility,shadowVisibility });
return { success: true, message: 'evironments created', data: newValue,organization:organization }
// res.status(201).json(newValue);
}
// Send response with the created document
} catch (error) {
console.error('Error creating evironments:', error);
return { success: false, message: 'Error creating or updating evironments', error ,organization:organization}
return {
success: true,
message: "evironments created",
data: newValue,
organization: organization,
};
}
}
} catch (error) {
console.error("Error creating evironments:", error);
return {
success: false,
message: "Error creating or updating evironments",
error,
organization: organization,
};
}
};

View File

@@ -1,4 +1,3 @@
import { Request, Response } from "express";
import lineModel from "../../../shared/model/lines/lines-Model.ts";
export const createLineItems = async (data: any) => {
@@ -11,8 +10,6 @@ export const createLineItems = async (data: any) => {
data: newLine,
organization: organization,
};
// Send response with the created document
} catch (error) {
return {
success: false,
@@ -25,11 +22,9 @@ export const createLineItems = async (data: any) => {
export const updateLineItems = async (data: any) => {
const { organization, uuid, position } = data;
try {
// const findLine = await lineModel(organization).find({ 'line.uuid': uuid });
// Update the position of the line matching the uuid
const updateResult = await lineModel(organization).updateMany(
{ "line.uuid": uuid }, // Filter: Find the line with the given uuid
{ $set: { "line.$.position": position } } // Update the position and type
await lineModel(organization).updateMany(
{ "line.uuid": uuid },
{ $set: { "line.$.position": position } }
);
return {
success: true,
@@ -37,8 +32,6 @@ export const updateLineItems = async (data: any) => {
data: { uuid: uuid, position: position },
organization: organization,
};
// Send response with the created document
} catch (error) {
console.error("Error creating Lines:", error);
return {
@@ -55,12 +48,8 @@ export const deleteLineItems = async (data: any) => {
try {
const inputUuids = line.map((item: any) => item.uuid);
// const findValue = await lineModel(organization).findOneAndDelete({
// line: { $elemMatch: { uuid: { $in: inputUuids } } },
// });
const findValue = await lineModel(organization).findOneAndDelete({
"line.uuid": { $all: inputUuids }, // Ensure all UUIDs are present in the `line` key
"line.uuid": { $all: inputUuids },
});
if (!findValue) {
@@ -97,10 +86,9 @@ export const deleteLayer = async (data: any) => {
} else {
await lineModel(organization).deleteMany({ layer: layer });
// Update documents with layer greater than -1
const updateResult = await lineModel(organization).updateMany(
await lineModel(organization).updateMany(
{ layer: { $gt: layer } },
{ $inc: { layer: -1 } } // Example operation: decrementing layer by 1
{ $inc: { layer: -1 } }
);
return {
success: true,

View File

@@ -1,79 +0,0 @@
import zoneModel from "../../../shared/model/builder/lines/zone-Model.ts";
// export const setZone = async (data: any) => {
// const { organization, userId, zoneData } = data
// try {
// console.log('data: ', data);
// const zoneId = zoneData.zoneId
// const points = zoneData.points
// const zoneName = zoneData.zoneName
// const layer = zoneData.layer
// const viewPortCenter = zoneData.viewPortCenter
// const viewPortposition = zoneData.viewPortposition
// const sceneID = zoneData.sceneID
// const existingZone = await zoneModel(organization).findOne({
// zoneId: zoneId,
// isArchive: false,
// });
// if (!existingZone) {
// const newZone = await zoneModel(organization).create({
// zoneName: zoneName,
// zoneId: zoneId,
// zonePoints: points,
// viewPortposition: viewPortposition,
// viewPortCenter: viewPortCenter,
// createdBy: userId,
// layer: layer,
// sceneID: sceneID,
// });
// if (newZone)
// return { success: true, message: 'zone created', data: newZone, organization: organization }
// } else {
// const replaceZone = await zoneModel(organization).findOneAndUpdate(
// { zoneId: zoneId, isArchive: false },
// {
// zonePoints: points,
// viewPortposition: viewPortposition,
// viewPortCenter: viewPortCenter,
// },
// { new: true }
// );
// if (!replaceZone)
// return { success: false, message: 'Zone not updated',organization: organization }
// else
// return { success: true, message: 'zone updated', data: replaceZone, organization: organization }
// }
// } catch (error: any) {
// return { success: false, message: 'Zone not found', error,organization: organization }
// }
// }
// export const deleteZone = async (data: any) => {
// const { organization, userId, zoneId } = data
// try {
// const existingZone = await zoneModel(organization).findOne({
// zoneId: zoneId,
// isArchive: false,
// });
// if (!existingZone) {
// return { success: true, message: 'Invalid zone ID', organization: organization }
// } else {
// const deleteZone = await zoneModel(organization).findOneAndUpdate(
// { zoneId: zoneId, isArchive: false },
// {
// isArchive: true,
// },
// { new: true }
// );
// if (deleteZone) {
// return { success: true, message: 'zone deleted', data: deleteZone, organization: organization }
// }
// }
// } catch (error: any) {
// return { success: false, message: 'Zone not found', error,organization: organization }
// }
// }

View File

@@ -5,137 +5,131 @@ import panelModel from "../../../shared/model/vizualization/panelmodel.ts";
import templateModel from "../../../shared/model/vizualization/templatemodel.ts";
import widgetModel from "../../../shared/model/vizualization/widgemodel.ts";
export const setZone = async (data: any) => {
const { organization, userId, zoneData } = data
try {
const zoneId = zoneData.zoneId
const points = zoneData.points
const zoneName = zoneData.zoneName
const layer = zoneData.layer
const viewPortCenter = zoneData.viewPortCenter
const viewPortposition = zoneData.viewPortposition
const findZoneId = await zoneModel(organization).findOne({ zoneId: zoneId })
if (findZoneId) {
const updateZone = await zoneModel(organization).findOneAndUpdate(
{ zoneId: zoneId }, { points: points, viewPortposition: viewPortposition, viewPortCenter: viewPortCenter }, { new: true }
).select("-_id -__v")
return { success: true, message: 'zone updated', data: updateZone, organization: organization }
} else {
const zoneCreate = await zoneModel(organization).create({
zoneId, createdBy: userId, zoneName: zoneName, points, layer, viewPortCenter, viewPortposition
})
const createdZone = await zoneModel(organization)
.findById(zoneCreate._id)
.select('-_id -__v')
.lean();
return { success: true, message: 'zone created', data: createdZone, organization: organization }
}
} catch (error) {
console.log('error: ', error);
return { success: false, message: 'Zone not found', error , organization: organization}
const { organization, userId, zoneData } = data;
try {
const zoneId = zoneData.zoneId;
const points = zoneData.points;
const zoneName = zoneData.zoneName;
const layer = zoneData.layer;
const viewPortCenter = zoneData.viewPortCenter;
const viewPortposition = zoneData.viewPortposition;
const findZoneId = await zoneModel(organization).findOne({
zoneId: zoneId,
});
if (findZoneId) {
const updateZone = await zoneModel(organization)
.findOneAndUpdate(
{ zoneId: zoneId },
{
points: points,
viewPortposition: viewPortposition,
viewPortCenter: viewPortCenter,
},
{ new: true }
)
.select("-_id -__v");
return {
success: true,
message: "zone updated",
data: updateZone,
organization: organization,
};
} else {
const zoneCreate = await zoneModel(organization).create({
zoneId,
createdBy: userId,
zoneName: zoneName,
points,
layer,
viewPortCenter,
viewPortposition,
});
const createdZone = await zoneModel(organization)
.findById(zoneCreate._id)
.select("-_id -__v")
.lean();
return {
success: true,
message: "zone created",
data: createdZone,
organization: organization,
};
}
}
} catch (error) {
console.log("error: ", error);
return {
success: false,
message: "Zone not found",
error,
organization: organization,
};
}
};
export const deleteZone = async (data: any) => {
const { organization, userId, zoneId } = data
try {
const { organization, userId, zoneId } = data;
try {
const findZoneId = await zoneModel(organization).findOne({
zoneId: zoneId,
});
if (findZoneId) {
const deleteZone = await zoneModel(organization)
.findOneAndDelete({ zoneId: zoneId, createdBy: userId })
.select("-_id -__v");
if (deleteZone) {
const panels = await panelModel(organization).find({ zoneId });
console.log("panels: ", panels);
const findZoneId = await zoneModel(organization).findOne({ zoneId: zoneId })
if (findZoneId) {
const deleteZone = await zoneModel(organization).findOneAndDelete(
{ zoneId: zoneId, createdBy: userId }
).select("-_id -__v")
if (deleteZone) {
const panels = await panelModel(organization).find({ zoneId });
console.log('panels: ', panels);
const allWidgetIds = panels.reduce((ids: string[], panel: any) => {
return ids.concat(panel.widgets || []);
}, []);
// Collect all widget IDs from all panels
const allWidgetIds = panels.reduce((ids: string[], panel: any) => {
return ids.concat(panel.widgets || []);
}, []);
await widgetModel(organization).updateMany(
{ _id: { $in: allWidgetIds } },
{ $set: { isArchive: true } }
);
// Soft delete all widgets
await widgetModel(organization).updateMany(
{ _id: { $in: allWidgetIds } },
{ $set: { isArchive: true } }
);
await panelModel(organization).updateMany(
{ zoneId },
{ $set: { isArchive: true } }
);
// Soft delete all panels for the zone
await panelModel(organization).updateMany(
{ zoneId },
{ $set: { isArchive: true } }
);
await Promise.all([
widget3dModel(organization).updateMany(
{ zoneId },
{ $set: { isArchive: true } }
),
templateModel(organization).updateMany(
{ zoneId },
{ $set: { isArchive: true } }
),
floatWidgetModel(organization).updateMany(
{ zoneId },
{ $set: { isArchive: true } }
),
]);
}
// Soft delete from other models
await Promise.all([
widget3dModel(organization).updateMany({ zoneId }, { $set: { isArchive: true } }),
templateModel(organization).updateMany({ zoneId }, { $set: { isArchive: true } }),
floatWidgetModel(organization).updateMany({ zoneId }, { $set: { isArchive: true } }),
]);
}
return { success: true, message: 'zone deleted', data: deleteZone, organization: organization }
} else {
return { success: true, message: 'Invalid zone ID', organization: organization }
}
} catch (error) {
console.log('error: ', error);
return { success: false, message: 'Zone not found', error, organization: organization }
return {
success: true,
message: "zone deleted",
data: deleteZone,
organization: organization,
};
} else {
return {
success: true,
message: "Invalid zone ID",
organization: organization,
};
}
}
// export const zoneDatasDeleted = async (data: { organization: string; userId: string; zoneId: string }) => {
// const { organization, userId, zoneId } = data;
// console.log('data: ', data);
// try {
// const findZone = await zoneModel(organization).findOne({ zoneId });
// if (!findZone) {
// return { success: false, message: 'Invalid zone ID', organization };
// }
// // Soft delete the zone
// const deleteZone = await zoneModel(organization).findOneAndDelete(
// { zoneId, createdBy: userId },
// );
// if (deleteZone) {
// const panels = await panelModel(organization).find({ zoneId });
// console.log('panels: ', panels);
// // Collect all widget IDs from all panels
// const allWidgetIds = panels.reduce((ids: string[], panel: any) => {
// return ids.concat(panel.widgets || []);
// }, []);
// console.log('allWidgetIds: ', allWidgetIds);
// // Soft delete all widgets
// await widgetModel(organization).updateMany(
// { _id: { $in: allWidgetIds } },
// { $set: { isArchive: true } }
// );
// // Soft delete all panels for the zone
// await panelModel(organization).updateMany(
// { zoneId },
// { $set: { isArchive: true } }
// );
// // Soft delete from other models
// await Promise.all([
// widget3dModel(organization).updateMany({ zoneId }, { $set: { isArchive: true } }),
// templateModel(organization).updateMany({ zoneId }, { $set: { isArchive: true } }),
// floatWidgetModel(organization).updateMany({ zoneId }, { $set: { isArchive: true } }),
// ]);
// }
// console.log("Zone and associated data archived");
// return { success: true, message: 'Zone and associated data archived', data: deleteZone, organization };
// return { success: true, message: 'Zone and associated data deleted', data: deleteZone, organization };
// } catch (error) {
// console.error('Zone deletion error:', error);
// return { success: false, message: 'An error occurred while deleting the zone', error, organization };
// }
// };
} catch (error) {
console.log("error: ", error);
return {
success: false,
message: "Zone not found",
error,
organization: organization,
};
}
};

View File

@@ -1,137 +1,109 @@
import cameraModel from "../../../shared/model/camera/camera-Model.ts"
import userModel from "../../../shared/model/user-Model.ts"
import cameraModel from "../../../shared/model/camera/camera-Model.ts";
import userModel from "../../../shared/model/user-Model.ts";
export const activeUsers = async (data: any) => {
const {organization}=data
// console.log('data: ', data);
try {
if (data && data.email) {
const email = data.email
const organization = email.split("@")[1].split(".")[0]
const findUser = await userModel(organization).findOne({email})
if (findUser) {
const updateActiveStatus = await userModel(organization).findOneAndUpdate({email:findUser.email},{activeStatus:"online"},{new:true})
if (updateActiveStatus) {
const cameraDatas=await cameraModel(organization).findOne({userId:updateActiveStatus._id})
.select("position target rotation -_id");
if (cameraDatas) {
const result = {
position: cameraDatas.position,
target: cameraDatas.target,
rotation: cameraDatas.rotation,
userData: {
_id: updateActiveStatus._id,
userName: updateActiveStatus.userName,
email: updateActiveStatus.email,
},
};
return { success: true, message: 'user connect ', data: result,organization:organization }
// return result;
}
}
}
}else {
// console.error('Invalid data or missing email:', data);
// Handle the error or return a default value
// Example: Return an error response if the email is invalid
return { success: false, message: 'Email is missing or invalid', organization:organization }
// return res.status(400).send({ message: 'Email is missing or invalid' });
}
// // return [];
} catch (error:any) {
return { success: false, message: error?.message || "Error occurred while activeUser", error, organization: organization }
const { organization } = data;
try {
if (data && data.email) {
const email = data.email;
const organization = email.split("@")[1].split(".")[0];
// return { success: false, message:error}
const findUser = await userModel(organization).findOne({ email });
if (findUser) {
const updateActiveStatus = await userModel(
organization
).findOneAndUpdate(
{ email: findUser.email },
{ activeStatus: "online" },
{ new: true }
);
if (updateActiveStatus) {
const cameraDatas = await cameraModel(organization)
.findOne({ userId: updateActiveStatus._id })
.select("position target rotation -_id");
if (cameraDatas) {
const result = {
position: cameraDatas.position,
target: cameraDatas.target,
rotation: cameraDatas.rotation,
userData: {
_id: updateActiveStatus._id,
userName: updateActiveStatus.userName,
email: updateActiveStatus.email,
},
};
return {
success: true,
message: "user connect ",
data: result,
organization: organization,
};
}
}
}
} else {
return {
success: false,
message: "Email is missing or invalid",
organization: organization,
};
}
}
} catch (error: any) {
return {
success: false,
message: error?.message || "Error occurred while activeUser",
error,
organization: organization,
};
}
};
export const activeUserOffline = async (data: any) => {
const email = data.email
const organization = email.split("@")[1].split(".")[0]
try {
const findUsers = await userModel(organization).findOne({email})
// console.log('findUsers: ', findUsers);
if (findUsers) {
const updateActiveStatus = await userModel(organization).findOneAndUpdate({email:email},{activeStatus:"offline"},{new:true})
// console.log('updateActiveStatus: ',updateActiveStatus);
if (updateActiveStatus) {
const cameraDatas=await cameraModel(organization).findOne({userId:updateActiveStatus._id})
.select("position target rotation -_id");
// console.log('cameraDatas: ', cameraDatas);
if (cameraDatas) {
const result = {
position: cameraDatas.position,
target: cameraDatas.target,
rotation: cameraDatas.rotation,
userData: {
_id: updateActiveStatus._id,
userName: updateActiveStatus.userName,
email: updateActiveStatus.email,
},
};
// console.log("Formatted Result:", result);
// return result;
return { success: true, message: 'user disconnect', data: result,organization:organization }
}
}
const email = data.email;
const organization = email.split("@")[1].split(".")[0];
try {
const findUsers = await userModel(organization).findOne({ email });
if (findUsers) {
const updateActiveStatus = await userModel(organization).findOneAndUpdate(
{ email: email },
{ activeStatus: "offline" },
{ new: true }
);
if (updateActiveStatus) {
const cameraDatas = await cameraModel(organization)
.findOne({ userId: updateActiveStatus._id })
.select("position target rotation -_id");
if (cameraDatas) {
const result = {
position: cameraDatas.position,
target: cameraDatas.target,
rotation: cameraDatas.rotation,
userData: {
_id: updateActiveStatus._id,
userName: updateActiveStatus.userName,
email: updateActiveStatus.email,
},
};
return {
success: true,
message: "user disconnect",
data: result,
organization: organization,
};
}
// // return [];
} catch (error:any) {
return { success: false, message: error?.message || "Error occurred while activeUser", error, organization: organization }
// return { success: false, message: error}
}
}
}
type OnlineUsersMap = Map<string, Set<string>>;
// export const addUserToOnlineList = async (
// organization: string,
// email: string,
// onlineUsers: OnlineUsersMap,
// socket: any,
// namespace: string
// ) => {
// if (!organization || !email) return;
// console.log('organization: ', organization);
// // Ensure the organization entry exists
// if (!onlineUsers.has(organization)) {
// onlineUsers.set(organization, new Set());
// }
// const findUser = await userModel(organization).findOne({email})
// if (!findUser) {
// return { success: false, message: "User not found", organization };
// }
// const userId = findUser._id;
// console.log(`🔍 Found user with ID: ${userId}`);
// // Add user to the online set
// onlineUsers.get(organization)!.add(userId);
// console.log(`✅ User ${userId} is online (Org: ${organization})`);
// // Emit updated online users list
// socket.emit("users:online", {
// organization,
// users: [...onlineUsers.get(organization)!],
// });
// };
} catch (error: any) {
return {
success: false,
message: error?.message || "Error occurred while activeUser",
error,
organization: organization,
};
}
};

View File

@@ -2,7 +2,6 @@ import zoneSchema from "../../../shared/model/builder/lines/zone-Model.ts";
import widget3dModel from "../../../shared/model/vizualization/3dwidget.ts";
export const add3Dwidget = async (data: any,callback:any) => {
const { organization, widget, zoneId } = data;
// console.log("data: ", data);
try {
const existingZone = await zoneSchema(organization).findOne({

View File

@@ -143,12 +143,11 @@ export const duplicatefloat = async (data: any, callback: any) => {
callback({
success: false,
message: "FloatWidget update unsuccessfull",
})
});
}
return {
success: false,
message: "FloatWidget update unsuccessfull",
// data: updateWidget,
organization: organization,
};
}
@@ -162,7 +161,7 @@ export const duplicatefloat = async (data: any, callback: any) => {
callback({
success: true,
message: "Widget updated successfully",
})
});
}
return {
success: true,
@@ -203,7 +202,7 @@ export const duplicatefloat = async (data: any, callback: any) => {
callback({
success: true,
message: "duplicate FloatWidget created successfully",
})
});
}
return {
success: true,
@@ -217,7 +216,7 @@ export const duplicatefloat = async (data: any, callback: any) => {
callback({
success: false,
message: error?.message || "Error occurred while float",
})
});
}
return {
success: false,
@@ -256,9 +255,7 @@ export const deletefloat = async (data: any) => {
{ isArchive: true },
{ new: true }
);
// if(!widgetData) {
// return
// }
if (widgetData) {
const floatDeleteData = {
floatWidgetID: findfloatWidget.floatWidgetID,

Some files were not shown because too many files have changed in this diff Show More