From 0b30a8aeaad09e2790ea54926cabb3aadfb6091c Mon Sep 17 00:00:00 2001 From: Nivetharamesh Date: Sat, 17 May 2025 10:12:18 +0530 Subject: [PATCH 1/6] Latest Project, Trash and setting API and sockets along with the Model clearance --- src/api-server/Dockerfile | 2 +- src/api-server/Routes/assetfloorRoutes.ts | 12 +- src/api-server/Routes/assetpointRoutes.ts | 6 +- src/api-server/Routes/camera-Routes.ts | 8 +- src/api-server/Routes/environments-Routes.ts | 6 +- src/api-server/Routes/floadWidgetRoute.ts | 10 +- src/api-server/Routes/flooritem-Routes.ts | 15 +- src/api-server/Routes/lines-Routes.ts | 20 +- src/api-server/Routes/panelRoutes.ts | 8 +- src/api-server/Routes/productFlowRouts.ts | 6 - src/api-server/Routes/productRoutes.ts | 18 +- src/api-server/Routes/share-Routes.ts | 6 +- src/api-server/Routes/templateRoutes.ts | 10 +- src/api-server/Routes/user-Routes.ts | 9 +- src/api-server/Routes/wallItems-Routes.ts | 14 +- src/api-server/Routes/widget3dRoutes.ts | 12 +- src/api-server/Routes/widgetRoute.ts | 10 +- src/api-server/Routes/zone-Routes.ts | 14 - src/api-server/Routes/zoneRoutes.ts | 18 +- src/api-server/app.ts | 8 +- .../controller/assets/flooritem-Services.ts | 3 +- .../controller/assets/pointService.ts | 2 +- .../controller/assets/wallitem-Services.ts | 148 +++--- .../controller/camera/camera-Services.ts | 164 +++---- .../environments/environments-Services.ts | 2 +- .../controller/lines/line-Services.ts | 225 +++++---- .../controller/lines/zone-Services.ts | 88 ---- .../controller/lines/zoneService.ts | 2 +- .../controller/newassets/wallcontroller.ts | 59 +++ .../controller/share/share-Controller.ts | 75 +-- .../simulation/assetsFloorservice.ts | 241 +--------- .../simulation/productFlowservice.ts | 249 ---------- .../controller/simulation/productService.ts | 441 +++++++++--------- src/api-server/controller/user-Controller.ts | 31 +- .../visualization/3dWidgetService.ts | 2 +- .../visualization/floatWidgetService.ts | 67 +-- .../controller/visualization/panelService.ts | 17 +- .../visualization/templateService.ts | 4 +- .../controller/visualization/widgetService.ts | 16 +- src/api-server/main.ts | 3 - src/shared/model/assets/flooritems-Model.ts | 52 +-- src/shared/model/assets/wallitems-Model.ts | 48 -- .../model/builder/assets/asset-Model.ts | 99 +--- .../model/builder/assets/assetPoint-Model.ts | 341 +------------- .../model/builder/assets/wallitems-Model.ts | 11 +- .../model/builder/camera/camera-Model.ts | 5 +- .../environments/environments-Model.ts | 24 - src/shared/model/builder/lines/lines-Model.ts | 5 +- src/shared/model/builder/lines/zone-Model.ts | 37 +- src/shared/model/camera/camera-Model.ts | 78 +--- .../model/environments/environments-Model.ts | 25 +- src/shared/model/project/project-model.ts | 2 +- src/shared/model/simulation/actionmodel.ts | 7 +- .../model/simulation/eventsDataModel.ts | 273 +++++------ .../model/simulation/productFlowmodel.ts | 97 ---- src/shared/model/simulation/productModel.ts | 10 +- src/shared/model/simulation/triggersmodel.ts | 2 +- src/shared/model/user-Model.ts | 22 +- src/shared/model/vizualization/3dwidget.ts | 2 +- src/shared/model/vizualization/floatWidget.ts | 4 +- src/shared/model/vizualization/panelmodel.ts | 4 +- .../model/vizualization/templatemodel.ts | 2 +- src/shared/model/vizualization/widgemodel.ts | 2 +- .../services/project/project-Services.ts | 1 - src/shared/services/wall/wallItemservice.ts | 115 +++++ .../services/assets/wallitem-Controller.ts | 141 ++++-- 66 files changed, 1109 insertions(+), 2351 deletions(-) delete mode 100644 src/api-server/Routes/productFlowRouts.ts delete mode 100644 src/api-server/Routes/zone-Routes.ts delete mode 100644 src/api-server/controller/lines/zone-Services.ts create mode 100644 src/api-server/controller/newassets/wallcontroller.ts delete mode 100644 src/api-server/controller/simulation/productFlowservice.ts delete mode 100644 src/shared/model/assets/wallitems-Model.ts delete mode 100644 src/shared/model/builder/environments/environments-Model.ts delete mode 100644 src/shared/model/simulation/productFlowmodel.ts create mode 100644 src/shared/services/wall/wallItemservice.ts diff --git a/src/api-server/Dockerfile b/src/api-server/Dockerfile index 942e1bd..7e5f70a 100644 --- a/src/api-server/Dockerfile +++ b/src/api-server/Dockerfile @@ -3,7 +3,7 @@ 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 diff --git a/src/api-server/Routes/assetfloorRoutes.ts b/src/api-server/Routes/assetfloorRoutes.ts index 725fa79..66653a1 100644 --- a/src/api-server/Routes/assetfloorRoutes.ts +++ b/src/api-server/Routes/assetfloorRoutes.ts @@ -1,12 +1,12 @@ import * as express from "express"; -import { assetsFloorservice } from "../controller/simulation/assetsFloorservice.ts"; +import { AssetsFloorService } from "../controller/simulation/assetsFloorservice.ts"; const router = express.Router(); -router.post("/setasset", assetsFloorservice.setFloorassets); -router.get("/floorAssets/:organization", assetsFloorservice.getFloorItems); +router.post("/setasset", AssetsFloorService.setFloorassets); +router.get("/floorAssets/:organization", AssetsFloorService.getFloorItems); router.patch( "/updateFloorAssets", - assetsFloorservice.updateAssetPositionRotation + AssetsFloorService.updateAssetPositionRotation ); -router.patch("/eventDataUpdate", assetsFloorservice.replaceEventDatas); -// router.get("/pointData/:modelfileID/:organization", assetsFloorservice.gettypePoints); +router.patch("/eventDataUpdate", AssetsFloorService.replaceEventDatas); +// router.get("/pointData/:modelfileID/:organization", AssetsFloorService.gettypePoints); export default router; diff --git a/src/api-server/Routes/assetpointRoutes.ts b/src/api-server/Routes/assetpointRoutes.ts index 533eabd..8b0209f 100644 --- a/src/api-server/Routes/assetpointRoutes.ts +++ b/src/api-server/Routes/assetpointRoutes.ts @@ -1,6 +1,6 @@ import * as express from "express"; -import { pointService } from "../controller/assets/pointService.ts"; +import { PointService } from "../controller/assets/pointService.ts"; const router = express.Router(); -router.post("/pointSchema", pointService.addPoints); -router.get("/pointData/:modelfileID/:organization", pointService.gettypePoints); +router.post("/pointSchema", PointService.addPoints); +router.get("/pointData/:modelfileID/:organization", PointService.gettypePoints); export default router; diff --git a/src/api-server/Routes/camera-Routes.ts b/src/api-server/Routes/camera-Routes.ts index 9f2bc5f..0845394 100644 --- a/src/api-server/Routes/camera-Routes.ts +++ b/src/api-server/Routes/camera-Routes.ts @@ -1,11 +1,11 @@ import express from 'express'; -import { camera } from '../controller/camera/camera-Services.ts'; +import { Camera } from '../controller/camera/camera-Services.ts'; const router = express.Router(); -router.post('/setCamera',camera.createCamera) -router.get('/getCamera/:organization/:userId',camera.getCamera) -router.get('/activeCameras/:organization',camera.onlineActiveDatas) +router.post('/setCamera',Camera.createCamera) +router.get('/getCamera/:organization/:userId',Camera.getCamera) +router.get('/activeCameras/:organization',Camera.onlineActiveDatas) export default router; diff --git a/src/api-server/Routes/environments-Routes.ts b/src/api-server/Routes/environments-Routes.ts index d70035d..19f00c2 100644 --- a/src/api-server/Routes/environments-Routes.ts +++ b/src/api-server/Routes/environments-Routes.ts @@ -1,9 +1,9 @@ import express from 'express'; -import { environment } from '../controller/environments/environments-Services.ts'; +import { Environment } from '../controller/environments/environments-Services.ts'; const router = express.Router(); -router.post('/setEvironments',environment.setEnvironment) -router.get('/findEnvironments/:organization/:userId',environment.getEnvironment) +router.post('/setEvironments',Environment.setEnvironment) +router.get('/findEnvironments/:organization/:userId',Environment.getEnvironment) export default router; \ No newline at end of file diff --git a/src/api-server/Routes/floadWidgetRoute.ts b/src/api-server/Routes/floadWidgetRoute.ts index 0e2183d..fe7f307 100644 --- a/src/api-server/Routes/floadWidgetRoute.ts +++ b/src/api-server/Routes/floadWidgetRoute.ts @@ -1,14 +1,14 @@ import * as express from "express"; -import { floatWidgetService } from "../controller/visualization/floatWidgetService.ts"; +import { FloatWidgetService } from "../controller/visualization/FloatWidgetService.ts"; const router = express.Router(); -router.post("/floatwidget/save", floatWidgetService.addfloatWidget); -router.patch("/floatwidget/delete", floatWidgetService.deletefloatWidget); +router.post("/floatwidget/save", FloatWidgetService.addfloatWidget); +router.patch("/floatwidget/delete", FloatWidgetService.deletefloatWidget); router.get( "/floadData/:zoneId/:organization", - floatWidgetService.getfloatWidget + FloatWidgetService.getfloatWidget ); router.get( "/A_floatWidget/:floatWidgetID/:organization", - floatWidgetService.getsinglefloatWidget + FloatWidgetService.getsinglefloatWidget ); export default router; diff --git a/src/api-server/Routes/flooritem-Routes.ts b/src/api-server/Routes/flooritem-Routes.ts index a2963d8..645c612 100644 --- a/src/api-server/Routes/flooritem-Routes.ts +++ b/src/api-server/Routes/flooritem-Routes.ts @@ -1,12 +1,11 @@ -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.post("/setfloorItems", FloorItems.setFloorItems); +router.get("/findfloorItems/:organization", FloorItems.getFloorItems); // router.delete('/deletefloorItem',floorItems.deleteFloorItems) -router.delete('/deletefloorItem',assetsFloorservice.deleteFloorItems) +router.delete("/deletefloorItem", AssetsFloorService.deleteFloorItems); - -export default router; \ No newline at end of file +export default router; diff --git a/src/api-server/Routes/lines-Routes.ts b/src/api-server/Routes/lines-Routes.ts index 24f72dc..b4b7708 100644 --- a/src/api-server/Routes/lines-Routes.ts +++ b/src/api-server/Routes/lines-Routes.ts @@ -1,14 +1,12 @@ -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; \ No newline at end of file +export default router; diff --git a/src/api-server/Routes/panelRoutes.ts b/src/api-server/Routes/panelRoutes.ts index 5695232..cc391f1 100644 --- a/src/api-server/Routes/panelRoutes.ts +++ b/src/api-server/Routes/panelRoutes.ts @@ -1,5 +1,5 @@ import * as express from "express"; -import { panelService } from "../controller/visualization/panelService.ts"; +import { PanelService } from "../controller/visualization/PanelService.ts"; const router = express.Router(); /** * @swagger @@ -101,7 +101,7 @@ const router = express.Router(); * 500: * description: Server error */ -router.post("/panel/save", panelService.AddPanel); +router.post("/panel/save", PanelService.AddPanel); /** * @swagger @@ -135,8 +135,8 @@ router.post("/panel/save", panelService.AddPanel); * 500: * description: Server error */ -router.patch("/panel/delete", panelService.deletePanel); -router.patch("/clearpanel", panelService.clearPanel); +router.patch("/panel/delete", PanelService.deletePanel); +router.patch("/clearpanel", PanelService.clearPanel); // router.get("/zone/:sceneID", Zoneservice.allZones); export default router; diff --git a/src/api-server/Routes/productFlowRouts.ts b/src/api-server/Routes/productFlowRouts.ts deleted file mode 100644 index 102baed..0000000 --- a/src/api-server/Routes/productFlowRouts.ts +++ /dev/null @@ -1,6 +0,0 @@ -// import * as express from "express"; -// import { productFlowservice } from "../controller/simulation/productFlowservice.ts"; -// const router = express.Router(); -// router.post("/createProduct", productFlowservice.setproductFlow); -// router.get("/productFlowList/:organization", productFlowservice.productpathsList); -// export default router; diff --git a/src/api-server/Routes/productRoutes.ts b/src/api-server/Routes/productRoutes.ts index b4a3801..ffa68d6 100644 --- a/src/api-server/Routes/productRoutes.ts +++ b/src/api-server/Routes/productRoutes.ts @@ -1,11 +1,13 @@ 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; - diff --git a/src/api-server/Routes/share-Routes.ts b/src/api-server/Routes/share-Routes.ts index 57c4b7f..51aa04e 100644 --- a/src/api-server/Routes/share-Routes.ts +++ b/src/api-server/Routes/share-Routes.ts @@ -1,11 +1,11 @@ import express from 'express'; -import { share } from '../controller/share/share-Controller.ts'; +import { Share } from '../controller/share/share-Controller.ts'; const router = express.Router(); -router.post('/shareUser',share.shareUser) -router.get('/findshareUsers',share.findshareUser) +router.post('/shareUser',Share.shareUser) +router.get('/findshareUsers',Share.findshareUser) export default router; \ No newline at end of file diff --git a/src/api-server/Routes/templateRoutes.ts b/src/api-server/Routes/templateRoutes.ts index 26410ac..7882a7c 100644 --- a/src/api-server/Routes/templateRoutes.ts +++ b/src/api-server/Routes/templateRoutes.ts @@ -1,12 +1,12 @@ import * as express from "express"; -import { templateService } from "../controller/visualization/templateService.ts"; +import { TemplateService } from "../controller/visualization/templateService.ts"; const router = express.Router(); -router.post("/template/save", templateService.AddTemplate); -router.get("/templateData/:organization", templateService.GetAllTemplates); -router.post("/TemplatetoZone", templateService.AddToZone); +router.post("/template/save", TemplateService.AddTemplate); +router.get("/templateData/:organization", TemplateService.GetAllTemplates); +router.post("/TemplatetoZone", TemplateService.AddToZone); router.patch( "/TemplateDelete/:templateID/:organization", - templateService.Deletezone + TemplateService.Deletezone ); //delete zone export default router; diff --git a/src/api-server/Routes/user-Routes.ts b/src/api-server/Routes/user-Routes.ts index 4f5815a..37c23d6 100644 --- a/src/api-server/Routes/user-Routes.ts +++ b/src/api-server/Routes/user-Routes.ts @@ -1,10 +1,9 @@ -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; diff --git a/src/api-server/Routes/wallItems-Routes.ts b/src/api-server/Routes/wallItems-Routes.ts index 6b7c52a..8b16a5d 100644 --- a/src/api-server/Routes/wallItems-Routes.ts +++ b/src/api-server/Routes/wallItems-Routes.ts @@ -1,11 +1,9 @@ -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; \ No newline at end of file +export default router; diff --git a/src/api-server/Routes/widget3dRoutes.ts b/src/api-server/Routes/widget3dRoutes.ts index bd76d2d..4a5075f 100644 --- a/src/api-server/Routes/widget3dRoutes.ts +++ b/src/api-server/Routes/widget3dRoutes.ts @@ -1,9 +1,9 @@ import * as express from "express"; -import { widget3dService } from "../controller/visualization/3dWidgetService.ts"; +import { Widget3dService } from "../controller/visualization/3dWidgetService.ts"; const router = express.Router(); -router.post("/3dwidget/save", widget3dService.add3Dwidget); -router.get("/3dwidgetData/:zoneId/:organization", widget3dService.get3Dwiget); -router.get("/widget3D/:id/:organization", widget3dService.getSingle3Dwidget); -router.patch("/widget3D/delete", widget3dService.delete3Dwidget); -router.patch("/modifyPR/widget3D", widget3dService.update3DpositionRotation); +router.post("/3dwidget/save", Widget3dService.add3Dwidget); +router.get("/3dwidgetData/:zoneId/:organization", Widget3dService.get3Dwiget); +router.get("/widget3D/:id/:organization", Widget3dService.getSingle3Dwidget); +router.patch("/widget3D/delete", Widget3dService.delete3Dwidget); +router.patch("/modifyPR/widget3D", Widget3dService.update3DpositionRotation); export default router; diff --git a/src/api-server/Routes/widgetRoute.ts b/src/api-server/Routes/widgetRoute.ts index df5f7c3..fae382b 100644 --- a/src/api-server/Routes/widgetRoute.ts +++ b/src/api-server/Routes/widgetRoute.ts @@ -1,5 +1,5 @@ import * as express from "express"; -import { widgetService } from "../controller/visualization/widgetService.ts"; +import { WidgetService } from "../controller/visualization/widgetService.ts"; const router = express.Router(); /** * @swagger @@ -134,11 +134,11 @@ const router = express.Router(); * 500: * description: Server error */ -router.post("/widget/save", widgetService.addWidget); -router.patch("/widget/:widgetID", widgetService.updatewidget); -router.patch("/delete/widget", widgetService.deleteWidget); +router.post("/widget/save", WidgetService.addWidget); +router.patch("/widget/:widgetID", WidgetService.updatewidget); +router.patch("/delete/widget", WidgetService.deleteWidget); router.get( "/WidgetData/:widgetID/:organization", - widgetService.getDatafromWidget + WidgetService.getDatafromWidget ); export default router; diff --git a/src/api-server/Routes/zone-Routes.ts b/src/api-server/Routes/zone-Routes.ts deleted file mode 100644 index 4293328..0000000 --- a/src/api-server/Routes/zone-Routes.ts +++ /dev/null @@ -1,14 +0,0 @@ -import express from 'express'; - -import { zone } from '../controller/lines/zone-Services.ts'; - - -const router = express.Router(); -router.post('/setZone',zone.setZone) -router.delete('/deleteZone',zone.deleteZone) -router.get('/findZones/:organization',zone.getZones) -// router.get('/A_zone/:zoneId/:organization',zone.ZoneData) - - - -export default router; \ No newline at end of file diff --git a/src/api-server/Routes/zoneRoutes.ts b/src/api-server/Routes/zoneRoutes.ts index 0371ab8..79e6354 100644 --- a/src/api-server/Routes/zoneRoutes.ts +++ b/src/api-server/Routes/zoneRoutes.ts @@ -1,5 +1,6 @@ import * as express from "express"; -import { Zoneservice } from "../controller/lines/zoneService.ts"; +import { ZoneService } from "../controller/lines/zoneService.ts"; + const router = express.Router(); /** * @swagger @@ -245,7 +246,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); //Zone create and update for the points /** * @swagger @@ -318,9 +319,9 @@ router.post("/zone/save", Zoneservice.addandUpdateZone); //Zone create and updat * value: * message: "Zone not found for the UUID" */ -router.get("/zones/:sceneID", Zoneservice.allZones); +router.get("/zones/:sceneID", ZoneService.allZones); -router.get("/pageZodeData", Zoneservice.vizAllDatas); +router.get("/pageZodeData", ZoneService.vizAllDatas); /** * @swagger @@ -414,7 +415,7 @@ router.get("/pageZodeData", Zoneservice.vizAllDatas); * example: * error: "Internal Server Error" */ -router.get("/ZoneVisualization/:zoneId", Zoneservice.singleZonePanelDatas); +router.get("/ZoneVisualization/:zoneId", ZoneService.singleZonePanelDatas); /** * @swagger @@ -483,7 +484,7 @@ router.get("/ZoneVisualization/:zoneId", Zoneservice.singleZonePanelDatas); * value: * message: "Zone not found" */ -router.get("/A_zone/:zoneId/:organization", Zoneservice.ZoneData); +router.get("/A_zone/:zoneId/:organization", ZoneService.ZoneData); /** * @swagger @@ -536,7 +537,6 @@ router.get("/A_zone/:zoneId/:organization", Zoneservice.ZoneData); * type: string * example: "Internal Server Error" */ -router.patch("/zone/:zoneId", Zoneservice.deleteAZone); //delete Zone -// router.get("/zone/:sceneID", Zoneservice.allZones); -router.patch("/zones/lockedPanels", Zoneservice.lockedPanel); +router.patch("/zone/:zoneId", ZoneService.deleteAZone); //delete Zone +router.patch("/zones/lockedPanels", ZoneService.lockedPanel); export default router; diff --git a/src/api-server/app.ts b/src/api-server/app.ts index c4cf874..a4e996e 100644 --- a/src/api-server/app.ts +++ b/src/api-server/app.ts @@ -1,6 +1,5 @@ import express from "express"; import cors from "cors"; -import connectDB from "../shared/connect/mongoose.ts"; import dotenv from "dotenv"; import cameraRoutes from "./Routes/camera-Routes.ts"; import environmentsRoutes from "./Routes/environments-Routes.ts"; @@ -9,8 +8,7 @@ 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/zone-Routes.ts"; -import zoneRoutes2 from "./Routes/zoneRoutes.ts"; //update +import zoneRoutes from "./Routes/zoneRoutes.ts"; //update import panelRouter from "./Routes/panelRoutes.ts"; import widgetRouter from "./Routes/widgetRoute.ts"; import assetpointRouter from "./Routes/assetpointRoutes.ts"; @@ -64,7 +62,6 @@ dotenv.config(); app.get("/", (req, res) => { res.send("Hello, I am Major-Dwinzo API!"); }); -// connectDB(); app.get("/health", (req, res) => { res.status(200).json({ message: "Server is running" }); }); @@ -76,9 +73,8 @@ app.use("/api/v1", flooritemRoutes); app.use("/api/v1", WallitemRoutes); app.use("/api/v1", userRoutes); app.use("/api/v1", shareRoutes); -app.use("/api/v2", zoneRoutes); //update -app.use("/api/v2", zoneRoutes2); //updates +app.use("/api/v2", zoneRoutes); //updates app.use("/api/v2", panelRouter); app.use("/api/v2", widgetRouter); app.use("/api/v2", assetpointRouter); diff --git a/src/api-server/controller/assets/flooritem-Services.ts b/src/api-server/controller/assets/flooritem-Services.ts index b6d3447..8a44358 100644 --- a/src/api-server/controller/assets/flooritem-Services.ts +++ b/src/api-server/controller/assets/flooritem-Services.ts @@ -1,7 +1,7 @@ import { Request, Response } from "express"; import floorItemsModel from "../../../shared/model/assets/flooritems-Model.ts"; -export class floorItems { +export class FloorItems { static async setFloorItems(req: Request, res: Response) { try { const { @@ -57,7 +57,6 @@ export class floorItems { static async getFloorItems(req: Request, res: Response) { try { const { organization } = req.params; - // console.log('req.params: ', req.params); const findValue = await floorItemsModel(organization).find(); if (!findValue) { diff --git a/src/api-server/controller/assets/pointService.ts b/src/api-server/controller/assets/pointService.ts index 6e6c04e..f94d687 100644 --- a/src/api-server/controller/assets/pointService.ts +++ b/src/api-server/controller/assets/pointService.ts @@ -74,7 +74,7 @@ interface IPointStaticMachine extends IPointBase { targets: { modelUUID: string; pointUUID: string }[]; }; } -export class pointService { +export class PointService { static async addPoints(req: Request, res: Response): Promise { const { type, modelfileID, organization } = req.body; diff --git a/src/api-server/controller/assets/wallitem-Services.ts b/src/api-server/controller/assets/wallitem-Services.ts index 5791d86..79ab308 100644 --- a/src/api-server/controller/assets/wallitem-Services.ts +++ b/src/api-server/controller/assets/wallitem-Services.ts @@ -1,80 +1,92 @@ import { Request, Response } from "express"; -import wallItenmModel from "../../../shared/model/assets/wallitems-Model.ts"; +import wallItemModel from "../../../shared/model/builder/assets/wallitems-Model.ts"; +export class WallItems { + static async setWallItems(req: Request, res: Response) { + try { + const { + modelUuid, + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + organization, + } = req.body; -export class wallItems { - static async setWallItems(req: Request, res: Response) { - try { - const { modelUuid, modelName, position, type, csgposition,csgscale,quaternion,scale,organization } = req.body - + const findvalue = await wallItemModel(organization).findOne({ + modelUuid: modelUuid, + }); - const findvalue = await wallItenmModel(organization).findOne({ modelUuid: modelUuid}) - - if (findvalue) { - const updatevalue = await wallItenmModel(organization).findOneAndUpdate( - { modelUuid: modelUuid }, - { - modelName, - position, - type, - csgposition, - csgscale, - quaternion, - scale, - }, - { new: true } // Return the updated document - ); - res.status(201).json(updatevalue); - + if (findvalue) { + const updatevalue = await wallItemModel(organization).findOneAndUpdate( + { modelUuid: modelUuid }, + { + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + }, + { new: true } // Return the updated document + ); + res.status(201).json(updatevalue); + } else { + const newValue = await wallItemModel(organization).create({ + modelUuid, + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + }); - } else { - const newValue = await wallItenmModel(organization).create({ modelUuid,modelName, position, type, csgposition,csgscale,quaternion,scale }); + res.status(201).json(newValue); + } - - 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" }); - } + // Send response with the created document + } catch (error) { + console.error("Error creating wallitems:", error); + res.status(500).json({ message: "Failed to create wallitems" }); } - static async getWallItems(req: Request, res: Response) { - try { - const { organization } = req.params; - + } + static async getWallItems(req: Request, res: Response) { + try { + const { organization } = req.params; - const findValue = await wallItenmModel -(organization).find() - if (!findValue) { - res.status(200).json("wallitems not found"); - } else { - - res.status(201).json(findValue); - } - } catch (error) { - console.error('Error get wallitems:', error); - res.status(500).json({ error: "Failed to get wallitems" }); - } + const findValue = await wallItemModel(organization).find(); + if (!findValue) { + res.status(200).json("wallitems not found"); + } else { + res.status(201).json(findValue); + } + } catch (error) { + console.error("Error get wallitems:", error); + res.status(500).json({ error: "Failed to get wallitems" }); } - static async deleteWallItems(req: Request, res: Response) { - try { - const { modelUuid,modelName,organization } = req.body; - + } + static async deleteWallItems(req: Request, res: Response) { + try { + const { modelUuid, modelName, organization } = req.body; - const findValue = await wallItenmModel -(organization).findOneAndDelete({modelUuid:modelUuid,modelName:modelName}) - if (!findValue) { - res.status(200).json("user not found"); - } else { - - res.status(201).json(findValue); - } - } catch (error) { - console.error('Error get wallitems:', error); - res.status(500).json({ error: "Failed to get wallitems" }); - } + const findValue = await wallItemModel(organization).findOneAndDelete({ + modelUuid: modelUuid, + modelName: modelName, + }); + if (!findValue) { + res.status(200).json("user not found"); + } else { + res.status(201).json(findValue); + } + } catch (error) { + console.error("Error get wallitems:", error); + res.status(500).json({ error: "Failed to get wallitems" }); } + } } diff --git a/src/api-server/controller/camera/camera-Services.ts b/src/api-server/controller/camera/camera-Services.ts index d9a10f7..d473d6b 100644 --- a/src/api-server/controller/camera/camera-Services.ts +++ b/src/api-server/controller/camera/camera-Services.ts @@ -2,88 +2,96 @@ import { Request, Response } from "express"; import cameraModel from "../../../shared/model/camera/camera-Model.ts"; import userModel from "../../../shared/model/user-Model.ts"; -export class camera { - static async createCamera(req: Request, res: Response) { - try { - const { userId, position, target, rotation,organization } = req.body - +export class Camera { + static async createCamera(req: Request, res: Response) { + try { + const { userId, position, target, rotation, organization } = req.body; - 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 }); - res.status(201).json(updateCamera); + const findCamera = await cameraModel(organization).findOne({ + userId: userId, + }); - } else { - const newCamera = await cameraModel(organization).create({ userId, position, target,rotation }); - - 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"}); - } - } - static async getCamera(req: Request, res: Response) { - try { - const { userId, organization } = req.params; - -// if (!userId) { -// res.status(201).json("User data is insufficient"); -// } - const findCamera = await cameraModel(organization).findOne({ userId: userId }) - if (!findCamera) { - res.status(200).json("user not found"); - } else { - - res.status(201).json(findCamera); - } - } catch (error) { - console.error('Error get camera:', error); - res.status(500).json({ error: "Failed to get camera" }); - } - } - - static async onlineActiveDatas(req: Request, res: Response) { - const {organization } = req.params; - try { - const findactiveUsers = await userModel(organization).find({activeStatus:"online"}) - - - const cameraDataPromises = findactiveUsers.map(async (activeUser:any) => { - const cameraData = await cameraModel(organization) - .findOne({ userId: activeUser._id }) - .select("position target rotation -_id"); - - if (cameraData) { - return { - position: cameraData.position, - target: cameraData.target, - rotation:cameraData.rotation, - userData: { - _id: activeUser._id, - userName: activeUser.userName, - email: activeUser.email, - activeStatus: activeUser.activeStatus, - }, - }; - } - - // Return null if no camera data is found for the user - return null; + if (findCamera) { + const updateCamera = await cameraModel(organization).findOneAndUpdate( + { userId: userId }, + { position: position, target: target, rotation: rotation }, + { new: true } + ); + res.status(201).json(updateCamera); + } else { + const newCamera = await cameraModel(organization).create({ + userId, + position, + target, + rotation, }); - const cameraDatas = (await Promise.all(cameraDataPromises)).filter((singledata:any) => singledata !== null); + res.status(201).json(newCamera); + } - - res.status(200).send({ cameraDatas }); - - } catch (error:any) { - res.status(500).send(error); - } + // Send response with the created document + } catch (error) { + console.error("Error creating camera:", error); + res.status(500).json({ message: "Failed to create camera" }); } + } + static async getCamera(req: Request, res: Response) { + try { + const { userId, organization } = req.params; + + const findCamera = await cameraModel(organization).findOne({ + userId: userId, + }); + if (!findCamera) { + res.status(200).json("user not found"); + } else { + res.status(201).json(findCamera); + } + } catch (error) { + console.error("Error get camera:", error); + res.status(500).json({ error: "Failed to get camera" }); + } + } + + static async onlineActiveDatas(req: Request, res: Response) { + const { organization } = req.params; + try { + const findactiveUsers = await userModel(organization).find({ + activeStatus: "online", + }); + + const cameraDataPromises = findactiveUsers.map( + async (activeUser: any) => { + const cameraData = await cameraModel(organization) + .findOne({ userId: activeUser._id }) + .select("position target rotation -_id"); + + if (cameraData) { + return { + position: cameraData.position, + target: cameraData.target, + rotation: cameraData.rotation, + userData: { + _id: activeUser._id, + userName: activeUser.userName, + email: activeUser.email, + activeStatus: activeUser.activeStatus, + }, + }; + } + + // Return null if no camera data is found for the user + return null; + } + ); + + const cameraDatas = (await Promise.all(cameraDataPromises)).filter( + (singledata: any) => singledata !== null + ); + + res.status(200).send({ cameraDatas }); + } catch (error: any) { + res.status(500).send(error); + } + } } diff --git a/src/api-server/controller/environments/environments-Services.ts b/src/api-server/controller/environments/environments-Services.ts index 9981319..49d92d9 100644 --- a/src/api-server/controller/environments/environments-Services.ts +++ b/src/api-server/controller/environments/environments-Services.ts @@ -1,7 +1,7 @@ import { Request, Response } from "express"; import environmentModel from "../../../shared/model/environments/environments-Model.ts"; -export class environment { +export class Environment { static async setEnvironment(req: Request, res: Response) { try { const { diff --git a/src/api-server/controller/lines/line-Services.ts b/src/api-server/controller/lines/line-Services.ts index f9fc7bb..d8866e5 100644 --- a/src/api-server/controller/lines/line-Services.ts +++ b/src/api-server/controller/lines/line-Services.ts @@ -1,125 +1,116 @@ import { Request, Response } from "express"; import lineModel from "../../../shared/model/lines/lines-Model.ts"; -export class lines { - static async setLines(req: Request, res: Response) { - try { - const {organization,layer,line,type}=req.body - const newLine = await lineModel(organization).create({ layer,line,type }); - - - 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"}); - } +export class Lines { + static async setLines(req: Request, res: Response) { + try { + const { organization, layer, line, type } = req.body; + const newLine = await lineModel(organization).create({ + layer, + line, + type, + }); + + 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" }); } - 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 + } + 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 + ); + + 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" }); + } + } + static async getLines(req: Request, res: Response) { + try { + const { organization } = req.params; + + const findValue = await lineModel(organization).find(); + if (!findValue) { + res.status(200).json("user not found"); + } else { + res.status(201).json(findValue); + } + } catch (error) { + console.error("Error get Lines:", error); + res.status(500).json({ error: "Failed to get Lines" }); + } + } + static async deleteLineItems(req: Request, res: Response) { + try { + const { organization, layer, line, type } = req.body; + + const inputUuids = line.map((item: any) => item.uuid); + const findValue = await lineModel(organization).findOneAndDelete({ + "line.uuid": { $all: inputUuids }, + }); + + if (!findValue) { + res.status(200).json("data not found"); + } else { + res.status(201).json(findValue); + } + } catch (error) { + console.error("Error delete Lines:", error); + res.status(500).json({ error: "Failed to delete Lines" }); + } + } + static async deleteLinPoiteItems(req: Request, res: Response) { + try { + const { organization, layer, uuid, type } = req.body; + + const findValue = await lineModel(organization).deleteMany({ + "line.uuid": uuid, + }); + + if (!findValue) { + res.status(200).json("data not found"); + } else { + res.status(201).json(findValue); + } + } catch (error) { + console.error("Error delete Lines:", error); + res.status(500).json({ error: "Failed to delete Lines" }); + } + } + + static async deleteLayer(req: Request, res: Response) { + try { + const { organization, layer } = req.body; + + const findValue = await lineModel(organization).find({ layer: layer }); + + if (!findValue) { + res.status(200).json("data not found"); + } else { + await lineModel(organization).deleteMany({ layer: layer }); + 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 + { layer: { $gt: layer } }, + { $inc: { layer: -1 } } ); - - 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"}); - } - } - static async getLines(req: Request, res: Response) { - try { - const { organization } = req.params; - - - const findValue = await lineModel(organization).find() - if (!findValue) { - res.status(200).json("user not found"); - } else { - - res.status(201).json(findValue); - } - } catch (error) { - console.error('Error get Lines:', error); - res.status(500).json({ error: "Failed to get Lines" }); - } - } - static async deleteLineItems(req: Request, res: Response) { - try { - const {organization,layer,line,type}=req.body - - 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 - }); - - if (!findValue) { - res.status(200).json("data not found"); - } else { - - res.status(201).json(findValue); - } - } catch (error) { - console.error('Error delete Lines:', error); - res.status(500).json({ error: "Failed to delete Lines" }); - } - } - static async deleteLinPoiteItems(req: Request, res: Response) { - try { - const {organization,layer,uuid,type}=req.body - - const findValue = await lineModel(organization).deleteMany({ 'line.uuid': uuid }) - - if (!findValue) { - res.status(200).json("data not found"); - } else { - - res.status(201).json(findValue); - } - } catch (error) { - console.error('Error delete Lines:', error); - res.status(500).json({ error: "Failed to delete Lines" }); - } - } - - static async deleteLayer(req: Request, res: Response) { - try { - const {organization,layer}=req.body - - // Fetch the documents with the specified layer value - const findValue = await lineModel(organization).find({ layer: layer }); - - if (!findValue) { - res.status(200).json("data not found"); - } else { - await lineModel(organization).deleteMany({ layer: layer }); - // console.log(`Documents with layer ${layer} have been deleted.`); - - // Update documents with layer greater than -1 - const updateResult = await lineModel(organization).updateMany( - { layer: { $gt:layer} }, - { $inc: { layer: -1 } } // Example operation: decrementing layer by 1 - ); - - - res.status(201).json(updateResult); - } - } catch (error) { - console.error('Error delete Lines:', error); - res.status(500).json({ error: "Failed to delete Lines" }); - } + + res.status(201).json(updateResult); + } + } catch (error) { + console.error("Error delete Lines:", error); + res.status(500).json({ error: "Failed to delete Lines" }); } + } } diff --git a/src/api-server/controller/lines/zone-Services.ts b/src/api-server/controller/lines/zone-Services.ts deleted file mode 100644 index 5ce8cdc..0000000 --- a/src/api-server/controller/lines/zone-Services.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { Request, Response } from "express"; -import zoneModel from "../../../shared/model/lines/zone-Model.ts"; -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 - 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") - res.status(201).json({ message: 'zone updated', data: updateZone, organization: organization }) - } else { - const zoneCreate = await zoneModel(organization).create({ - zoneId, createBy: userId, zoneName: zoneName, points, layer, viewPortCenter, viewPortposition - }) - const createdZone = await zoneModel(organization) - .findById(zoneCreate._id) - .select('-_id -__v') - .lean(); - res.status(201).json({ message: 'zone created', data: createdZone, organization: organization }) - } - } catch (error) { - console.log('error: ', error); - res.status(500).json({ message: 'Zone not found', error }) - } - } - static async deleteZone(req: Request, res: Response) { - try { - const { organization, userId, zoneId } = req.body - - const findZoneId = await zoneModel(organization).findOne({ zoneId: zoneId }) - if (findZoneId) { - const deleteZone = await zoneModel(organization).findOneAndDelete( - { zoneId: zoneId, createBy: userId } - ).select("-_id -__v") - res.status(201).json({ message: 'zone deleted', data: deleteZone, organization: organization }) - } else { - - res.status(500).json({ message: 'Invalid zone ID' }) - - } - } catch (error) { - console.log('error: ', error); - res.status(500).json({ message: 'Zone not found', error }) - } - } - static async getZones(req: Request, res: Response) { - try { - const { organization, userId } = req.params - - - const findZoneId = await zoneModel(organization) - .find() - .select("zoneId zoneName layer points viewPortCenter viewPortposition -_id"); - - if (!findZoneId) { - res.status(500).json({ message: 'Invalid zone' }) - - } - res.status(201).json({ data: findZoneId, organization: organization }) - } catch (error) { - console.log('error: ', error); - res.status(500).json({ message: 'Zone not found', error }) - } - } - - static async ZoneData(req: Request, res: Response): Promise { - try { - const organization = req.params.organization; - const zoneId = req.params.zoneId; - 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) { - return res.status(500).send(error.message); - } - } -} diff --git a/src/api-server/controller/lines/zoneService.ts b/src/api-server/controller/lines/zoneService.ts index 6f2a643..4017d91 100644 --- a/src/api-server/controller/lines/zoneService.ts +++ b/src/api-server/controller/lines/zoneService.ts @@ -2,7 +2,7 @@ import { Request, Response } from "express"; import zoneSchema from "../../../shared/model/builder/lines/zone-Model.ts"; import panelSchema from "../../../shared/model/vizualization/panelmodel.ts"; import widgetSchema from "../../../shared/model/vizualization/widgemodel.ts"; -export class Zoneservice { +export class ZoneService { static async addandUpdateZone(req: Request, res: Response): Promise { try { const organization = req.body.organization; diff --git a/src/api-server/controller/newassets/wallcontroller.ts b/src/api-server/controller/newassets/wallcontroller.ts new file mode 100644 index 0000000..2ede5cf --- /dev/null +++ b/src/api-server/controller/newassets/wallcontroller.ts @@ -0,0 +1,59 @@ +import { Request, Response } from "express"; +import { WallItems } from "../../../shared/services/wall/wallItemservice.ts"; +import { error } from "console"; + +export const WallSetup = async (req: Request, res: Response): Promise => { + try { + const { + modelUuid, + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + organization, + } = req.body; + if ( + !modelUuid || + !modelName || + !position || + !type || + !csgscale || + !csgposition || + !quaternion || + !scale || + !organization + ) { + res.status(400).json({ + message: "All fields are required!", + }); + return; + } + const result = await WallItems.setWallItems({ + modelUuid, + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + organization, + }); + switch (result.state) { + case "Updated successfully": + res.status(201).json(result.data); + break; + case "wall Item created successfully": + res.status(201).json(result.data); + break; + default: + res.status(500).json(error); + break; + } + } catch (error: unknown) { + res.status(500).json({ message: "Unknown error" }); + } +}; diff --git a/src/api-server/controller/share/share-Controller.ts b/src/api-server/controller/share/share-Controller.ts index 4865ae5..7463a87 100644 --- a/src/api-server/controller/share/share-Controller.ts +++ b/src/api-server/controller/share/share-Controller.ts @@ -1,43 +1,46 @@ import { Request, Response } from "express"; import userModel from "../../../shared/model/user-Model.ts"; +export class Share { + static async shareUser(req: Request, res: Response) { + try { + const { email, isShare, organization } = req.body; -export class share { - static async shareUser(req: Request, res: Response) { - try { - const { email, isShare, organization } = req.body - + const findValue = await userModel(organization).findOneAndUpdate( + { email: email }, + { isShare: isShare }, + { new: true } + ); - const findValue = await userModel(organization).findOneAndUpdate({email:email},{isShare:isShare},{new:true}) - - res.status(201).json({message:"scene shared successfully",data:findValue}); - 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"}); - } + res + .status(201) + .json({ message: "scene shared successfully", data: findValue }); + 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" }); } - - static async findshareUser(req: Request, res: Response) { - try { - const organization = req.query.organization as string; - - - const findValue = await userModel(organization).find({}).select("isShare email userName -_id") - // console.log('findValue: ', findValue); - - res.status(201).json({message:"scene shared datas",data:findValue}); - 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 "}); - } - } - + } + + static async findshareUser(req: Request, res: Response) { + try { + const organization = req.query.organization as string; + + const findValue = await userModel(organization) + .find({}) + .select("isShare email userName -_id"); + + res.status(201).json({ message: "scene shared datas", data: findValue }); + 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 " }); + } + } } diff --git a/src/api-server/controller/simulation/assetsFloorservice.ts b/src/api-server/controller/simulation/assetsFloorservice.ts index e251350..f9d9f4f 100644 --- a/src/api-server/controller/simulation/assetsFloorservice.ts +++ b/src/api-server/controller/simulation/assetsFloorservice.ts @@ -1,182 +1,9 @@ import { Request, Response } from "express"; import assetModel from "../../../shared/model/builder/assets/asset-Model.ts"; -import actionModel from "../../../shared/model/simulation/actionmodel.ts"; -import triggerModel from "../../../shared/model/simulation/triggersmodel.ts"; import pointModel from "../../../shared/model/builder/assets/assetPoint-Model.ts"; import EventsDataModel from "../../../shared/model/simulation/eventsDataModel.ts"; -export class assetsFloorservice { - // static async setFloorassets(req: Request, res: Response): Promise { - // try { - // const { - // modelUuid, - // modelName, - // position, - // modelfileID, - // rotation, - // isLocked, - // isVisible, - // organization, - // eventData, - // } = req.body; - // console.log("req.body: ", req.body); - - // const findvalue = await assetModel(organization).findOne({ - // modelUuid, - // // modelName, - // isArchive: false, - // }); - // const checkpointType = await pointModel(organization).findOne({ - // modelfileID: modelfileID, - // isArchive: false, - // }); - - // if (findvalue) { - // const updatevalue = await assetModel(organization).findOneAndUpdate( - // { modelUuid, isArchive: false }, - // { - // modelName: modelName, - // position, - // rotation, - // isVisible, - // isLocked, - // }, - // { new: true } - // ); - // return res.status(201).json(updatevalue); - // } else { - // let assetData: any = { - // modelUuid, - // modelName, - // position, - // modelfileID, - // rotation, - // isLocked, - // isVisible, - // }; - - // console.log("eventData: ", eventData); - // if (eventData) { - // if (eventData.type === "Conveyor") { - // assetData.speed = eventData.speed; - // } else if (eventData.type === "Vehicle") { - // assetData.speed = eventData.points.speed; - // if (!eventData.points) { - // return res - // .status(400) - // .json({ message: "Vehicle points must be a single object" }); - // } - // // if (eventData.points.rotation) { - // // return res.status(400).json({ - // // message: "Rotation is not allowed for Vehicle points", - // // }); - // // } - - // if (eventData.points.triggers) { - // return res.status(400).json({ - // message: "triggers is not allowed for Vehicle points", - // }); - // } - // } - // // else if(eventData.type === "ArmBot"){ - // // assetData.speed = eventData.position; - // // }else if(eventData.type === "StaticMachine"){ - // // assetData.speed = eventData.position; - // // } - - // assetData.points = eventData.points; - // assetData.type = eventData.type; - // } - // const assetDoc = await assetModel(organization).create(assetData); - // await assetDoc.save(); - - // return res.status(201).json({ - // message: "Model stored successfully", - // modelId: assetDoc._id, - // }); - // } - // } catch (error) { - // console.error("Error creating flooritems:", error); - // res.status(500).json({ message: "Failed to create flooritems" }); - // } - // } - // static async getFloorItems(req: Request, res: Response): Promise { - // try { - // const { organization } = req.params; - // const findValues = await assetModel(organization) - // .find({ isArchive: false }) - // .select("-_id -isArchive"); - - // if (!findValues || findValues.length === 0) { - // return res.status(200).json({ message: "floorItems not found" }); - // } - - // const response = findValues.map((item) => { - // // console.log("item: ", item); - // // console.log("item: ", item.type); - // // console.log('findValues: ', findValues); - // // console.log("item.points: ", item.points); - // const responseItem: any = { - // modelUuid: item.modelUuid, - // modelName: item.modelName, - // position: item.position, - // rotation: item.rotation, - // modelfileID: item.modelfileID, - // isLocked: item.isLocked, - // isVisible: item.isVisible, - // }; - // if (item.type === "Conveyor" && item.points.length > 0) { - // responseItem.eventData = { - // speed: item.speed, - // points: item.points, - // type: item.type, - // }; - // } - - // if (item.type === "Vehicle" && item.points) { - // responseItem.eventData = { - // type: item.type, - // points: item.points, - // }; - // } - // if (item.type === "ArmBot" && item.points) { - // responseItem.eventData = { - // type: item.type, - // points: item.points, - // }; - // } - // if (item.type === "StaticMachine" && item.points) { - // responseItem.eventData = { - // type: item.type, - // points: item.points, - // }; - // } - // return responseItem; - // }); - - // return res.status(200).json(response); - // } catch (error) { - // res.status(500).json({ error: "Failed to get flooritems" }); - // } - // } - // static async deleteFloorItems(req: Request, res: Response): Promise { - // try { - // const { modelUuid, modelName, organization } = req.body; - - // const findValue = await assetModel(organization).findOneAndDelete({ - // modelUuid: modelUuid, - // modelName: modelName, - // isArchive: false, - // }); - // if (!findValue) { - // res.status(200).json("user not found"); - // } else { - // res.status(201).json(findValue); - // } - // } catch (error) { - // res.status(500).json({ error: "Failed to get flooritems" }); - // } - // } +export class AssetsFloorService { static async updateAssetPositionRotation( req: Request, res: Response @@ -186,11 +13,11 @@ export class assetsFloorservice { modelUuid, modelName, position, - modelfileID, rotation, isLocked, isVisible, organization, + // modelfileID, //optional // eventData, // Optional } = req.body; @@ -244,7 +71,6 @@ export class assetsFloorservice { return res.status(500).send(error.message); } } - //update setfoolrassets//getFloorItems//deleteFloorItems......... static async setFloorassets(req: Request, res: Response): Promise { try { const { @@ -265,7 +91,7 @@ export class assetsFloorservice { // modelName, isArchive: false, }); - const checkpointType = await pointModel(organization).findOne({ + await pointModel(organization).findOne({ modelfileID: modelfileID, isArchive: false, }); @@ -292,10 +118,9 @@ export class assetsFloorservice { rotation, isLocked, isVisible, - eventData + eventData, }; - console.log("eventData: ", eventData); if (eventData) { if (eventData.type === "Conveyor") { assetData.speed = eventData.speed; @@ -306,24 +131,12 @@ export class assetsFloorservice { .status(400) .json({ message: "Vehicle points must be a single object" }); } - // if (eventData.points.rotation) { - // return res.status(400).json({ - // message: "Rotation is not allowed for Vehicle points", - // }); - // } - if (eventData.points.triggers) { return res.status(400).json({ message: "triggers is not allowed for Vehicle points", }); } } - // else if(eventData.type === "ArmBot"){ - // assetData.speed = eventData.position; - // }else if(eventData.type === "StaticMachine"){ - // assetData.speed = eventData.position; - // } - assetData.points = eventData.points; assetData.type = eventData.type; } @@ -352,10 +165,6 @@ export class assetsFloorservice { } const response = findValues.map((item) => { - // console.log("item: ", item); - // console.log("item: ", item.type); - // console.log('findValues: ', findValues); - // console.log("item.points: ", item.points); const responseItem: any = { modelUuid: item.modelUuid, modelName: item.modelName, @@ -366,36 +175,9 @@ export class assetsFloorservice { isVisible: item.isVisible, eventData: item.eventData, }; - // if (item.type === "Conveyor" && item.points.length > 0) { - // responseItem.eventData = { - // speed: item.speed, - // points: item.points, - // type: item.type, - // }; - // } - - // if (item.type === "Vehicle" && item.points) { - // responseItem.eventData = { - // type: item.type, - // points: item.points, - // }; - // } - // if (item.type === "ArmBot" && item.points) { - // responseItem.eventData = { - // type: item.type, - // points: item.points, - // }; - // } - // if (item.type === "StaticMachine" && item.points) { - // responseItem.eventData = { - // type: item.type, - // points: item.points, - // }; - // } return responseItem; }); - // console.log('response: ', response); return res.status(200).json(response); } catch (error) { res.status(500).json({ error: "Failed to get flooritems" }); @@ -404,36 +186,35 @@ export class assetsFloorservice { static async deleteFloorItems(req: Request, res: Response): Promise { try { const { modelUuid, modelName, organization } = req.body; - console.log('req.body:', req.body); - + const asset = await assetModel(organization).findOne({ modelUuid, modelName, isArchive: false, }); - + if (!asset) { return res.status(404).json({ message: "Model not found" }); } - + const archivedAsset = await assetModel(organization).findOneAndUpdate( { modelUuid, modelName }, { $set: { isArchive: true } }, { new: true } ); - + if (!archivedAsset) { return res.status(500).json({ message: "Failed to archive asset" }); } - + const updatedEvents = 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); diff --git a/src/api-server/controller/simulation/productFlowservice.ts b/src/api-server/controller/simulation/productFlowservice.ts deleted file mode 100644 index eedcf86..0000000 --- a/src/api-server/controller/simulation/productFlowservice.ts +++ /dev/null @@ -1,249 +0,0 @@ -// import { Request, Response } from "express"; -// // import assetModel from "../../../shared/model/assets/flooritems-Model.ts"; -// import assetModel from "../../../shared/model/builder/assets/asset-Model.ts"; -// import actionModel from "../../../shared/model/simulation/actionmodel.ts"; -// import triggerModel from "../../../shared/model/simulation/triggersmodel.ts"; -// import productFlowModel from "../../../shared/model/simulation/ProductFlowmodel.ts"; - -// export class productFlowservice { -// static async setproductFlow(req: Request, res: Response): Promise { -// try { -// const { -// productName, -// modelUuid, -// modelName, -// eventData, -// organization, -// productID, -// } = req.body; - -// // Validate required fields -// if (!modelUuid || !modelName || !organization) { -// return res.status(400).json({ message: "Missing required fields" }); -// } - -// // Check if asset exists -// const existingAsset = await assetModel(organization).findOne({ -// modelUuid: modelUuid, -// isArchive: false, -// }); -// if (!existingAsset) { -// return res.status(404).json({ message: "Asset not found for the ID" }); -// } - -// // Prepare point references -// let pointRefs: any[] = []; -// if (eventData?.points && Array.isArray(eventData.points)) { -// for (const point of eventData.points) { -// let actionRefs: any[] = []; -// let triggerRefs: any[] = []; - -// // Process actions -// if (Array.isArray(point.actions)) { -// for (const action of point.actions) { -// const actionDoc = await actionModel(organization).create({ -// pointsUUID: point.uuid, -// isArchive: false, -// uuid: action.uuid, -// name: action.name, -// type: action.type, -// material: action.material || null, -// delay: action.delay || null, -// spawn_Interval: action.spawn_Interval || null, -// }); -// actionRefs.push({ -// _id: actionDoc._id, -// ...action, -// }); -// } -// } - -// // Process triggers -// if (Array.isArray(point.triggers)) { -// for (const trigger of point.triggers) { -// const triggerDoc = await triggerModel(organization).create({ -// pointsUUID: point.uuid, -// isArchive: false, -// uuid: trigger.uuid, -// name: trigger.name, -// type: trigger.type, -// bufferTime: trigger.bufferTime || null, -// }); -// triggerRefs.push({ -// _id: triggerDoc._id, -// ...trigger, -// }); -// } -// } - -// pointRefs.push({ -// pointuuid: point.uuid, -// position: point.position || [], -// rotation: point.rotation || [], -// actions: actionRefs, -// triggers: triggerRefs, -// connections: point.connections || null, -// }); -// } -// } - -// // Check if product flow exists -// const existingproductData = await productFlowModel(organization).findOne({ -// _id: productID, -// }); - -// let result; -// if (existingproductData) { -// // Update existing product flow -// result = await productFlowModel(organization).findOneAndUpdate( -// { _id: productID }, -// { -// $push: { -// ProductData: { -// AssetName: modelName, -// Assetuuid: modelUuid, -// paths: { -// Points: pointRefs, -// }, -// isArchive: false, -// }, -// }, -// }, -// { new: true } -// ); -// } else { -// // Create new product flow -// result = await productFlowModel(organization).create({ -// _id: productID, -// productName: productName, -// ProductData: [ -// { -// AssetName: modelName, -// Assetuuid: modelUuid, -// paths: { -// Points: pointRefs, -// }, -// isArchive: false, -// }, -// ], -// eventType: eventData?.type || null, -// speed: eventData?.speed || null, -// }); -// } - -// res.status(201).json({ -// message: "Product flow processed successfully", -// data: result, -// }); -// } catch (error) { -// console.error("Error creating flooritems:", error); -// res.status(500).json({ message: "Failed to create flooritems" }); -// } -// } -// static async pointActionList(req: Request, res: Response): Promise {} -// static async productpathsList(req: Request, res: Response): Promise { -// try { -// const { organization } = req.params; -// const productFlowList = await productFlowModel(organization) -// .find() -// .select("ProductData productName -_id") -// .exec(); - -// const formattedData = await Promise.all( -// productFlowList.map(async (item) => ({ -// productName: item.productName, -// paths: await Promise.all( -// item.ProductData.map(async (data: any) => ({ -// Points: await Promise.all( -// data.paths.Points.map(async (point: any) => { -// const actions = await actionModel(organization) -// .find({ _id: { $in: point.actions } }) -// .select( -// "-_id -pointsUUID -isArchive -createdAt -updatedAt -__v" -// ) -// .lean(); -// const triggers = await triggerModel(organization) -// .find({ _id: { $in: point.triggers } }) -// .select( -// "-_id -pointsUUID -isArchive -createdAt -updatedAt -__v" -// ) -// .lean(); -// return { -// connections: point.connections || null, -// pointuuid: point.pointuuid, -// actions: actions, -// triggers: triggers, -// position: point.position, -// rotation: point.rotation, -// }; -// }) -// ), -// })) -// ), -// })) -// ); - -// return res.status(200).json(formattedData); -// } catch (error) { -// console.error("Error get flooritems:", error); -// res.status(500).json({ error: "Failed to get flooritems" }); -// } -// } -// // static async deleteFloorItems(req: Request, res: Response): Promise { -// // try { -// // const { modelUuid, modelName, organization } = req.body; - -// // const findValue = await assetModel(organization).findOneAndDelete({ -// // modelUuid: modelUuid, -// // modelName: modelName, -// // isArchive: false, -// // }); -// // if (!findValue) { -// // res.status(200).json("user not found"); -// // } else { -// // res.status(201).json(findValue); -// // } -// // } catch (error) { -// // console.error("Error get flooritems:", error); -// // res.status(500).json({ error: "Failed to get flooritems" }); -// // } -// // } -// // static async updateAssetPositionRotation( -// // req: Request, -// // res: Response -// // ): Promise { -// // try { -// // const { -// // modelUuid, -// // modelName, -// // position, -// // modelfileID, -// // rotation, -// // isLocked, -// // isVisible, -// // organization, -// // // eventData, // Optional -// // } = req.body; - -// // const existingAsset = await assetModel(organization).findOne({ -// // modelUuid: modelUuid, -// // isArchive: false, -// // }); -// // if (!existingAsset) return res.send("Asset not found"); -// // const updateAsset = await assetModel(organization).updateMany( -// // { modelUuid: modelUuid, modelName: modelName, isArchive: false }, -// // { -// // position: position, -// // rotation: rotation, -// // isVisible: isVisible, -// // isLocked: isLocked, -// // } -// // ); -// // if (updateAsset) -// // return res.status(200).json({ message: "Asset updated successfully" }); -// // } catch (error: any) { -// // return res.send(error.message); -// // } -// // } -// // static async updateActionsDatas(req: Request, res: Response) {} -// } diff --git a/src/api-server/controller/simulation/productService.ts b/src/api-server/controller/simulation/productService.ts index d360ff3..690b117 100644 --- a/src/api-server/controller/simulation/productService.ts +++ b/src/api-server/controller/simulation/productService.ts @@ -2,256 +2,237 @@ import { Request, Response } from "express"; import ProductModel from "../../../shared/model/simulation/productModel.ts"; import EventsDataModel from "../../../shared/model/simulation/eventsDataModel.ts"; -export class productFlowservice { - - static async productAdd(req: Request, res: Response): Promise { - try { - const { productName, productId, eventDatas, organization } = req.body; - if (!organization) { - return res - .json({ message: "organization not found" }); +export class ProductFlowservice { + static async productAdd(req: Request, res: Response): Promise { + try { + const { productName, productId, eventDatas, organization } = req.body; + if (!organization) { + return res.json({ message: "organization not found" }); + } + const existingProduct = await ProductModel(organization).findOne({ + productId: productId, + isArchive: false, + }); + if (existingProduct) { + const existingEventData = await EventsDataModel(organization).findOne({ + productId: productId, + 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, } - const existingProduct = await ProductModel(organization).findOne({ - productId: productId, - isArchive: false, - }) - if (existingProduct) { - const existingEventData = await EventsDataModel(organization).findOne( - { - productId: productId, - modelUuid: eventDatas.modelUuid, - isArchive: false, - }) - if (existingEventData) { - const updateEventData = 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 res - .status(200) - .json({ message: "EventData updated successfully" }); - } else { - const addEventData = 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 res - .status(201) - .json({ message: "EventData add successfully" }); - } - } else { - const newProduct = await ProductModel(organization).create({ - productId: productId, - productName: productName - - }) - if (newProduct) { - - if (eventDatas) { - const addEventData = 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 res - .status(201) - .json({ message: "Product created successfully" }); - - } - } catch (error) { - res.status(500).json({ message: "Failed to create product" }); + ); + 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 res + .status(201) + .json({ message: "EventData add successfully" }); } - } - static async getProductDatas(req: Request, res: Response): Promise { - try { - const { productId, organization } = req.query - if (typeof productId !== "string" || typeof organization !== "string") { - return res.status(400).json({ message: "Missing or invalid query parameters" }); - } - const existingProduct = await ProductModel(organization).findOne({ - productId: productId, - isArchive: false, - }) - - if (!existingProduct) - return res.status(404).json({ message: "Product not found" }); - - - const existingEventDatas = await EventsDataModel(organization).find({ productId: productId }).select("-productId") - - return res - .status(200) - .json(existingEventDatas); - } catch (error) { - - res.status(500).json({ message: "Failed to get product" }); + } 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 res + .status(201) + .json({ message: "Product created successfully" }); + } + } catch (error) { + res.status(500).json({ message: "Failed to create product" }); } - static async productDataDelete(req: Request, res: Response): Promise { - try { - const { productId, organization } = req.query - if (typeof productId !== "string" || typeof organization !== "string") { - return res.status(400).json({ message: "Missing or invalid query parameters" }); - } - const existingProduct = await ProductModel(organization).findOne({ - productId: productId, - isArchive: false, - }) + } + static async getProductDatas(req: Request, res: Response): Promise { + try { + const { productId, organization } = req.query; + if (typeof productId !== "string" || typeof organization !== "string") { + return res + .status(400) + .json({ message: "Missing or invalid query parameters" }); + } + const existingProduct = await ProductModel(organization).findOne({ + productId: productId, + isArchive: false, + }); - if (!existingProduct) - return res.status(404).json({ message: "Product not found" }); + if (!existingProduct) + return res.status(404).json({ message: "Product not found" }); - const productDelete = await ProductModel(organization).findOneAndUpdate( - { productId: productId }, - { - isArchive: true, - }, { new: true } - - ) - const existingEventDatas = await EventsDataModel(organization).find({ productId: productId }) - if (existingEventDatas) { - for (const event of existingEventDatas) { - - await EventsDataModel(organization).updateMany( - { productId }, - { $set: { isArchive: true } } - ); - - } - } - return res.status(201).json({ message: "product deleted successfully" }); - - } catch (error) { - res.status(500).json({ message: "Failed to delete product" }); - } + const existingEventDatas = await EventsDataModel(organization) + .find({ productId: productId }) + .select("-productId"); + return res.status(200).json(existingEventDatas); + } catch (error) { + res.status(500).json({ message: "Failed to get product" }); } - static async EventDataDelete(req: Request, res: Response): Promise { - try { - const { productId, organization, modelUuid } = req.body + } + static async productDataDelete(req: Request, res: Response): Promise { + try { + const { productId, organization } = req.query; + if (typeof productId !== "string" || typeof organization !== "string") { + return res + .status(400) + .json({ message: "Missing or invalid query parameters" }); + } + const existingProduct = await ProductModel(organization).findOne({ + productId: productId, + isArchive: false, + }); - const existingProduct = await ProductModel(organization).findOne({ - productId: productId, - isArchive: false, - }) - - if (!existingProduct) - return res.status(404).json({ message: "Product not found" }); - - - const existingEventDatas = await EventsDataModel(organization).findOneAndUpdate( - { productId: productId, modelUuid: modelUuid }, { - isArchive: true, - }, { new: true } - - ) - - return res.status(201).json({ message: "EventData deleted successfully" }); - } catch (error) { - res.status(500).json({ message: "Failed to delete Eventdata" }); - } + if (!existingProduct) + return res.status(404).json({ message: "Product not found" }); + await ProductModel(organization).findOneAndUpdate( + { productId: productId }, + { + isArchive: true, + }, + { new: true } + ); + const existingEventDatas = await EventsDataModel(organization).find({ + productId: productId, + }); + if (existingEventDatas) { + // for (const event of existingEventDatas) { + await EventsDataModel(organization).updateMany( + { productId }, + { $set: { isArchive: true } } + ); + // } + } + return res.status(201).json({ message: "product deleted successfully" }); + } catch (error) { + res.status(500).json({ message: "Failed to delete product" }); } - static async AllProductDatas(req: Request, res: Response): Promise { - try { - const { organization } = req.params + } + static async EventDataDelete(req: Request, res: Response): Promise { + try { + const { productId, organization, modelUuid } = req.body; - if (!organization) { - return res - .json({ message: "organization not found" }); - } + const existingProduct = await ProductModel(organization).findOne({ + productId: productId, + isArchive: false, + }); - const existingProduct = await ProductModel(organization).find({ - isArchive: false, - }) - if (!existingProduct) { - return res.status(404).json({ message: 'No products found' }); - } - const result = []; + if (!existingProduct) + return res.status(404).json({ message: "Product not found" }); - for (const product of existingProduct) { - - - // Fetch events data for each product, excluding productId field - const eventDatas = await EventsDataModel(organization) - .find({ productId: product.productId, isArchive: false }) - .select("-productId -isArchive -createdAt -updatedAt -__v -_id"); - - - - // Combine product and event data - result.push({ - // product: { - productName: product.productName, - productId: product.productId, - eventDatas, - // }, - }); - } - - // Return combined data - return res.status(200).json(result); - - } catch (error) { - res.status(500).json({ message: "Failed to get Allproduct" }); - } + await EventsDataModel(organization).findOneAndUpdate( + { productId: productId, modelUuid: modelUuid }, + { + isArchive: true, + }, + { new: true } + ); + return res + .status(201) + .json({ message: "EventData deleted successfully" }); + } catch (error) { + res.status(500).json({ message: "Failed to delete Eventdata" }); } - static async productRename(req: Request, res: Response): Promise { + } + static async AllProductDatas(req: Request, res: Response): Promise { + try { + const { organization } = req.params; - try { - const { productId, productName, organization } = req.body + if (!organization) { + return res.json({ message: "organization not found" }); + } + const existingProduct = await ProductModel(organization).find({ + isArchive: false, + }); + if (!existingProduct) { + return res.status(404).json({ message: "No products found" }); + } + const result = []; - const existingProduct = await ProductModel(organization).findOne({ - productId: productId, - isArchive: false, - }) + for (const product of existingProduct) { + const eventDatas = await EventsDataModel(organization) + .find({ productId: product.productId, isArchive: false }) + .select("-productId -isArchive -createdAt -updatedAt -__v -_id"); - if (!existingProduct) - return res.status(404).json({ message: "Product not found" }); - - const productDelete = await ProductModel(organization).findOneAndUpdate( - { productId: productId }, - { - productName: productName, - }, { new: true } - - ) - - return res.status(201).json({ message: "product Rename successfully" }); - } catch (error) { - res.status(500).json({ message: "Failed to product Rename" }); - } + result.push({ + // product: { + productName: product.productName, + productId: product.productId, + eventDatas, + // }, + }); + } + return res.status(200).json(result); + } catch (error) { + res.status(500).json({ message: "Failed to get Allproduct" }); } + } + static async productRename(req: Request, res: Response): Promise { + try { + const { productId, productName, organization } = req.body; + + const existingProduct = await ProductModel(organization).findOne({ + productId: productId, + isArchive: false, + }); + + if (!existingProduct) + return res.status(404).json({ message: "Product not found" }); + + await ProductModel(organization).findOneAndUpdate( + { productId: productId }, + { + productName: productName, + }, + { new: true } + ); + + return res.status(201).json({ message: "product Rename successfully" }); + } catch (error) { + res.status(500).json({ message: "Failed to product Rename" }); + } + } } diff --git a/src/api-server/controller/user-Controller.ts b/src/api-server/controller/user-Controller.ts index 0e2cb59..01106b6 100644 --- a/src/api-server/controller/user-Controller.ts +++ b/src/api-server/controller/user-Controller.ts @@ -1,12 +1,9 @@ import { Request, Response } from "express"; -import { Server } from 'http'; import userModel from "../../shared/model/user-Model.ts"; -import { isSharedArrayBuffer } from "util/types"; import {hashGenerate,hashValidator} from "../../shared/security/Hasing.ts" -// import {hashGenerate} from '../security/Hasing' let serverAlive = true; -export class user { +export class User { static async signup(req: Request, res: Response) { try { let role; @@ -43,7 +40,6 @@ export class user { try { let role; const { email, password,organization } = req.body; - // console.log(' req.body: ', req.body); const existingMail = await userModel(organization).findOne({ email:email @@ -57,7 +53,6 @@ export class user { password, hashedpassword ) - // console.log('checkpassword: ', checkpassword); if (checkpassword) { // const tokenValidation=await tokenGenerator(existingMail.email) res.status(200).send({ @@ -77,27 +72,5 @@ export class user { res.status(500).send(error); } } - - // static async checkserverHealth(server:Server,organization: string){ - // try { - // if (server.listening) { - // console.log('Server is running'); - // serverAlive = true; - // // Update all users to online status - // } else { - // // await userModel(organization).updateMany({}, { activeStatus: "offline" }); // Replace `activeStatus` with your actual field - // throw new Error('Server is not running'); - // } - // } catch (error:any) { - // console.error('Server health check failed:', error.message); - // serverAlive = false; - - // // Update all users to offline status - // // await userModel(organization).updateMany({}, { activeStatus: "offline" }); - // } - // } - } -// export const startHealthCheck = (server: Server, organization: string) => { -// setInterval(() => user.checkserverHealth(server, organization), 5000); -// }; + diff --git a/src/api-server/controller/visualization/3dWidgetService.ts b/src/api-server/controller/visualization/3dWidgetService.ts index 80fbc6a..ae721e9 100644 --- a/src/api-server/controller/visualization/3dWidgetService.ts +++ b/src/api-server/controller/visualization/3dWidgetService.ts @@ -1,7 +1,7 @@ import { Request, Response } from "express"; import zoneSchema from "../../../shared/model/builder/lines/zone-Model.ts"; import widget3dModel from "../../../shared/model/vizualization/3dwidget.ts"; -export class widget3dService { +export class Widget3dService { static async add3Dwidget(req: Request, res: Response): Promise { try { const { organization, widget, zoneId } = req.body; diff --git a/src/api-server/controller/visualization/floatWidgetService.ts b/src/api-server/controller/visualization/floatWidgetService.ts index 3d1fff2..bf45cbc 100644 --- a/src/api-server/controller/visualization/floatWidgetService.ts +++ b/src/api-server/controller/visualization/floatWidgetService.ts @@ -1,7 +1,7 @@ import { Request, Response } from "express"; import floatWidgetModel from "../../../shared/model/vizualization/floatWidget.ts"; import zoneSchema from "../../../shared/model/builder/lines/zone-Model.ts"; -export class floatWidgetService { +export class FloatWidgetService { static async addfloatWidget(req: Request, res: Response): Promise { try { const { organization, widget, zoneId } = req.body; @@ -19,9 +19,7 @@ export class floatWidgetService { zoneId: zoneId, }); if (existingFloatWidget) { - const updateFloatWidget = await floatWidgetModel( - organization - ).findOneAndUpdate( + await floatWidgetModel(organization).findOneAndUpdate( { floatWidgetID: widget.id, isArchive: false, @@ -141,65 +139,4 @@ export class floatWidgetService { return res.status(500).send(error.message); } } - // static async updatewidget(req: Request, res: Response): Promise { - // try { - // const { organization, widgetID, values } = req.body; - // const findwidget = await widgetSchema(organization).findOne({ - // widgetID: widgetID, - // isArchive: false, - // }); - // if (!findwidget) - // return res.status(404).send({ message: "Data not found" }); - // const updateData = { - // widgetName: values.widgetName, - // widgetSide: values.widgetSide, // Fixed typo from widgetside to widgetSide - // elementType: values.type, - // Data: { - // measurement: values.Data.measurement, - // duration: values.Data.duration, - // }, - // elementColor: values.color, - // fontFamily: values.fontFamily, - // fontStyle: values.fontStyle, - // fontWeight: values.fontWeight, - // isArchive: false, - // }; - - // const changedWidget = await widgetSchema(organization).findOneAndUpdate( - // { widgetID: widgetID, isArchive: false }, - // updateData, - // { - // new: true, - // upsert: true, - // setDefaultsOnInsert: true, - // } - // ); - - // return res.status(200).json({ - // message: "Widget updated successfully", - // }); - // } catch (error: any) { - // return res.status(500).send(error.message); - // } - // } - - // static async getDatafromWidget(req: Request, res: Response): Promise { - // const { organization, widgetID } = req.params; - // try { - // const existingWidget = await widgetSchema(organization) - // .findOne({ - // widgetID: widgetID, - // isArchive: false, - // }) - // .select("Data -_id"); - // const Datastructure = { - // measurements: existingWidget.Data.measurements || {}, - // duration: existingWidget.Data.duration || "1h", - // }; - - // if (existingWidget) return res.status(200).json({ Data: Datastructure }); - // } catch (error: any) { - // return res.status(500).send(error.message); - // } - // } } diff --git a/src/api-server/controller/visualization/panelService.ts b/src/api-server/controller/visualization/panelService.ts index 12f65ab..3ee7689 100644 --- a/src/api-server/controller/visualization/panelService.ts +++ b/src/api-server/controller/visualization/panelService.ts @@ -3,12 +3,12 @@ import panelSchema from "../../../shared/model/vizualization/panelmodel.ts"; import zoneSchema from "../../../shared/model/builder/lines/zone-Model.ts"; import widgetSchema from "../../../shared/model/vizualization/widgemodel.ts"; -export class panelService { +export class PanelService { static async AddPanel(req: Request, res: Response): Promise { try { const organization = req.body.organization; const zoneId = req.body.zoneId; - const panelName = req.body.panelName; + // const panelName = req.body.panelName; const panelOrder = req.body.panelOrder; const findZone = await zoneSchema(organization).findOne({ zoneId: zoneId, @@ -18,7 +18,7 @@ export class panelService { if (!findZone) { return res.status(404).json({ message: "Zone not found" }); } - const updatezone = await zoneSchema(organization).findOneAndUpdate( + await zoneSchema(organization).findOneAndUpdate( { zoneId: zoneId, isArchive: false }, { panelOrder: panelOrder }, { new: true } @@ -52,10 +52,6 @@ export class panelService { message: "No new panels were created. All panels already exist.", }); } - // const IDdata = createdPanels.map((ID: any) => { - // return ID._id; - // }); - createdPanels; return res.status(201).json({ message: "Panels created successfully", panelID: createdPanels, @@ -66,7 +62,6 @@ export class panelService { } static async deletePanel(req: Request, res: Response): Promise { try { - console.log("req.body: ", req.body); const { organization, panelName, zoneId } = req.body; const existingZone = await zoneSchema(organization).findOne({ zoneId: zoneId, @@ -81,7 +76,7 @@ export class panelService { }); if (!existingPanel) return res.status(409).json({ message: "Panel Already Deleted" }); - const updatePanel = await panelSchema(organization).findOneAndUpdate( + await panelSchema(organization).findOneAndUpdate( { _id: existingPanel._id, isArchive: false }, { isArchive: true }, { new: true } @@ -96,12 +91,11 @@ export class panelService { } if (existingZone.panelOrder.includes(existingPanel.panelName)) { - const index1 = existingZone.panelOrder.indexOf(existingPanel.panelName); + existingZone.panelOrder.indexOf(existingPanel.panelName); const zonepanelname = await zoneSchema(organization).updateOne( { _id: existingZone._id }, { $pull: { panelOrder: existingPanel.panelName } } ); - console.log("zonepanelname: ", zonepanelname); } return res.status(200).json({ message: "Panel deleted successfully" }); @@ -111,7 +105,6 @@ export class panelService { } static async clearPanel(req: Request, res: Response): Promise { try { - console.log("req.body;: ", req.body); const { organization, panelName, zoneId } = req.body; const existingZone = await zoneSchema(organization).findOne({ zoneId: zoneId, diff --git a/src/api-server/controller/visualization/templateService.ts b/src/api-server/controller/visualization/templateService.ts index d459cba..9e08a61 100644 --- a/src/api-server/controller/visualization/templateService.ts +++ b/src/api-server/controller/visualization/templateService.ts @@ -5,7 +5,7 @@ import panelSchema from "../../../shared/model/vizualization/panelmodel.ts"; import widgetSchema from "../../../shared/model/vizualization/widgemodel.ts"; import floatWidgetModel from "../../../shared/model/vizualization/floatWidget.ts"; -export class templateService { +export class TemplateService { static async AddTemplate(req: Request, res: Response): Promise { try { const { @@ -18,7 +18,6 @@ export class templateService { // snapshot, // floatWidgets, } = req.body; - // console.log("req.body: ", req.body); const existingTemplate = await templateModel(organization).findOne({ templateID: template.id, isArchive: false, @@ -181,7 +180,6 @@ export class templateService { } static async Deletezone(req: Request, res: Response): Promise { try { - console.log("req.params: ", req.params); const { organization, templateID } = req.params; const existingTemplate = await templateModel(organization).findOne({ templateID: templateID, diff --git a/src/api-server/controller/visualization/widgetService.ts b/src/api-server/controller/visualization/widgetService.ts index f743885..0abde31 100644 --- a/src/api-server/controller/visualization/widgetService.ts +++ b/src/api-server/controller/visualization/widgetService.ts @@ -2,11 +2,9 @@ import { Request, Response } from "express"; import panelSchema from "../../../shared/model/vizualization/panelmodel.ts"; import zoneSchema from "../../../shared/model/builder/lines/zone-Model.ts"; import widgetSchema from "../../../shared/model/vizualization/widgemodel.ts"; -export class widgetService { +export class WidgetService { static async addWidget(req: Request, res: Response): Promise { try { - // console.log("req.body: ", req.body); - console.log("req.body: ", req.body); const { organization, // panel, @@ -34,7 +32,6 @@ export class widgetService { isArchive: false, // widgetOrder: widget.widgetOrder, }); - // console.log('existingWidget: ', widget.data.measurements); if (existingWidget) { const updateWidget = await widgetSchema( organization @@ -58,16 +55,13 @@ export class widgetService { }, { upsert: true, new: true } // Upsert: create if not exists, new: return updated document ); - console.log("updateWidget: ", updateWidget); if (!updateWidget) { return res.json({ message: "Widget update unsuccessful" }); } return res .status(200) .json({ message: "Widget updated successfully" }); - // return res - // .status(409) - // .json({ message: "Widget already exist for the widgetID" }); + } const newWidget = await widgetSchema(organization).create({ widgetID: widget.id, @@ -100,7 +94,6 @@ export class widgetService { static async deleteWidget(req: Request, res: Response): Promise { try { const { widgetID, organization, zoneId } = req.body; - console.log(" req.body: ", req.body); const findWidget = await widgetSchema(organization).findOne({ zoneId: zoneId, widgetID: widgetID, @@ -115,7 +108,7 @@ export class widgetService { if (widgetData) { // Find all widgets in the same panel and sort them by widgetOrder - const widgets = await widgetSchema(organization).find({ + await widgetSchema(organization).find({ panelID: findWidget.panelID, zoneId: zoneId, isArchive: false, @@ -146,7 +139,6 @@ export class widgetService { static async updatewidget(req: Request, res: Response): Promise { try { - console.log("req.body: ", req.body); const { organization, widgetID, values } = req.body; const findwidget = await widgetSchema(organization).findOne({ widgetID: widgetID, @@ -169,7 +161,7 @@ export class widgetService { isArchive: false, }; - const changedWidget = await widgetSchema(organization).findOneAndUpdate( + await widgetSchema(organization).findOneAndUpdate( { widgetID: widgetID, isArchive: false }, updateData, { diff --git a/src/api-server/main.ts b/src/api-server/main.ts index 15f2bcf..5b029a0 100644 --- a/src/api-server/main.ts +++ b/src/api-server/main.ts @@ -1,10 +1,8 @@ import app from './app.ts'; import http from 'http'; -import ip from 'ip'; // import { startHealthCheck } from './controller/user-Controller'; import swaggerUi from 'swagger-ui-express'; -import mongoAdminCreation from '../shared/security/mongosecurity.ts'; import fs from 'fs'; const server = http.createServer(app); @@ -34,6 +32,5 @@ 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(`Server is also accessible on IP address: ${ip.address()}`); }); diff --git a/src/shared/model/assets/flooritems-Model.ts b/src/shared/model/assets/flooritems-Model.ts index f3720f9..8b69411 100644 --- a/src/shared/model/assets/flooritems-Model.ts +++ b/src/shared/model/assets/flooritems-Model.ts @@ -1,57 +1,35 @@ -import mongoose, { Document, Schema } from 'mongoose'; -import MainModel from '../../connect/mongoose.ts'; +import { Document, Schema } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; -// Interface for TypeScript with PascalCase -export interface floorItenms extends Document { +export interface FloorItems extends Document { modelUuid: string; modelfileID: string; - modelName: string - isLocked:boolean - isVisible:boolean - position: [] + modelName: string; + isLocked: boolean; + isVisible: boolean; + position: []; rotation: { x: number; y: number; z: number; }; - - } -// Define the Mongoose Schema const floorItemsSchema: Schema = new Schema({ modelUuid: { type: String }, modelfileID: { type: String }, modelName: { type: String }, - position: { type: Array}, - isLocked:{type:Boolean}, - isVisible:{type:Boolean}, + position: { type: Array }, + isLocked: { type: Boolean }, + isVisible: { type: Boolean }, rotation: { x: { type: Number, required: true }, y: { type: Number, required: true }, - z: { type: Number, required: true } - } + z: { type: Number, required: true }, + }, }); -// Model for MongoDB collection -// const cameraModel = model("Camera", cameraSchema); - -// export default cameraModel; -// const floorItemsModel = (db: string) => { -// const mongoUrl = process.env.MONGO_URI || ''; -// if (!mongoUrl) { -// throw new Error('MONGO_URI environment variable is not set'); -// } -// // Connect to the database -// const dbConnection = mongoose.createConnection(mongoUrl, { -// dbName: db, // Specify the database name here -// serverSelectionTimeoutMS: 30000, -// }); -// return dbConnection.model('floorItenms', floorItenmsSchema,`floorItenms`); -// } - -// export default floorItemsModel; -const floorItemsModel = (db:string) => { - return MainModel(db, "floorItems", floorItemsSchema, "floorItems") +const floorItemsModel = (db: string) => { + return MainModel(db, "floorItems", floorItemsSchema, "floorItems"); }; -export default floorItemsModel; \ No newline at end of file +export default floorItemsModel; diff --git a/src/shared/model/assets/wallitems-Model.ts b/src/shared/model/assets/wallitems-Model.ts deleted file mode 100644 index de94339..0000000 --- a/src/shared/model/assets/wallitems-Model.ts +++ /dev/null @@ -1,48 +0,0 @@ -import mongoose, { Document, Schema } from 'mongoose'; -import MainModel from '../../connect/mongoose.ts'; -// Interface for TypeScript with PascalCase -export interface wallitems extends Document { - modelUuid: string; - modelName: string - modelfileID: string; - type: string - csgposition: [] - csgscale: [] - position: [] - quaternion: [] - scale: [] - - -} - -// Define the Mongoose Schema -const wallItemsSchema: Schema = new Schema({ - modelUuid: { type: String}, - modelfileID: { type: String}, - modelName: { type: String}, - type: { type: String }, - csgposition: { type: Array}, - csgscale: { type: Array,}, - position: { type: Array }, - quaternion: { type: Array}, - scale: { type: Array} -}); - -// const wallItenmModel = (db: string) => { -// const mongoUrl = process.env.MONGO_URI || ''; -// if (!mongoUrl) { -// throw new Error('MONGO_URI environment variable is not set'); -// } -// // Connect to the database -// const dbConnection = mongoose.createConnection(mongoUrl, { -// dbName: db, // Specify the database name here -// serverSelectionTimeoutMS: 30000, -// }); -// return dbConnection.model('wallitenms', wallItenmsSchema, `wallitenms`); -// } - -// export default wallItenmModel; -const wallItenmModel = (db:string) => { - return MainModel(db, "wallitems", wallItemsSchema, "wallitems") - }; - export default wallItenmModel; \ No newline at end of file diff --git a/src/shared/model/builder/assets/asset-Model.ts b/src/shared/model/builder/assets/asset-Model.ts index 8bd9a46..404aa53 100644 --- a/src/shared/model/builder/assets/asset-Model.ts +++ b/src/shared/model/builder/assets/asset-Model.ts @@ -1,4 +1,4 @@ -import mongoose, { Document, Schema } from "mongoose"; +import { Document, Schema } from "mongoose"; import MainModel from "../../../connect/mongoose.ts"; interface ICommonBase { @@ -18,7 +18,7 @@ interface IPoint extends ICommonBase { rotation: [number, number, number]; }; } -export interface assetData extends Document { +export interface AssetData extends Document { modelUuid: string; modelfileID: string; modelName: string; @@ -43,7 +43,6 @@ const assetDataSchema: Schema = new Schema({ modelfileID: { type: String }, modelName: { type: String }, type: { type: String }, - // points: { type: Schema.Types.Mixed }, position: { type: Array }, rotation: { x: { type: Number }, @@ -58,101 +57,7 @@ const assetDataSchema: Schema = new Schema({ }, }); -// export default floorItemsModel; const assetModel = (db: string) => { return MainModel(db, "Assets", assetDataSchema, "Assets"); }; export default assetModel; - -// import mongoose, { Document, Schema } from "mongoose"; -// import MainModel from "../../../connect/mongoose.ts"; - -// export interface assetData extends Document { -// modelUuid: string; -// modelfileID: string; -// modelName: string; -// isLocked: boolean; -// type: string; -// isVisible: boolean; -// isArchive: false; -// // position: []; -// // rotation: { -// // x: number; -// // y: number; -// // z: number; -// // }; -// points: { -// uuid: string; -// position: []; -// rotation: []; -// actions: [mongoose.Types.ObjectId]; -// triggers: [mongoose.Types.ObjectId]; -// connections: { -// source: { -// modelUUID: string; -// pointUUID: string; -// }; -// targets: [ -// { -// modelUUID: string; -// pointUUID: string; -// } -// ]; -// }[]; -// }[]; -// position: []; -// // rotation: []; -// rotation: { -// x: number; -// y: number; -// z: number; -// }; -// speed: number | string; -// } - -// // Define the Mongoose Schema -// const assetDataSchema: Schema = new Schema({ -// isArchive: { type: Boolean, default: false }, -// modelUuid: { type: String }, -// modelfileID: { type: String }, -// modelName: { type: String }, -// type: { type: String }, -// // assetPosition: { type: Array }, -// points: [ -// { -// uuid: { type: String }, -// position: { type: Array }, -// rotation: { type: Array }, -// actions: [{ type: mongoose.Schema.Types.ObjectId, ref: "Actions" }], -// triggers: [{ type: mongoose.Schema.Types.ObjectId, ref: "Triggers" }], -// connections: { -// source: { -// modelUUID: { type: String }, -// pointUUID: { type: String }, -// }, -// targets: [ -// { -// modelUUID: { type: String }, -// pointUUID: { type: String }, -// }, -// ], -// }, -// }, -// ], -// position: { type: Array }, -// // rotation: { type: Array}, -// rotation: { -// x: { type: Number }, -// y: { type: Number }, -// z: { type: Number }, -// }, -// speed: { type: Schema.Types.Mixed }, -// isLocked: { type: Boolean }, -// isVisible: { type: Boolean }, -// }); - -// // export default floorItemsModel; -// const assetModel = (db: string) => { -// return MainModel(db, "Assets", assetDataSchema, "Assets"); -// }; -// export default assetModel; diff --git a/src/shared/model/builder/assets/assetPoint-Model.ts b/src/shared/model/builder/assets/assetPoint-Model.ts index 62a20ea..06a1ef5 100644 --- a/src/shared/model/builder/assets/assetPoint-Model.ts +++ b/src/shared/model/builder/assets/assetPoint-Model.ts @@ -1,31 +1,6 @@ -import mongoose, { Schema, Document } from "mongoose"; +import { Schema, Document } from "mongoose"; import MainModel from "../../../connect/mongoose.ts"; -// Common Interfaces -// interface ITriggerConveyor { -// uuid: string; -// name: string; -// type: string; -// isUsed: boolean; -// bufferTime: number; -// } -// interface ITriggerVehicle { -// uuid: string; -// name: string; -// type: string; -// isUsed: boolean; -// } - -// interface IConnectionConveyor { -// source: { modelUUID: string; pointUUID: string }; -// targets: { modelUUID: string; pointUUID: string }[]; -// } -// interface IConnectionVehicle { -// source: { modelUUID: string; pointUUID: string }; -// targets: { modelUUID: string; pointUUID: string }[]; -// } - -// Point Types interface IPointBase { uuid: string; position: number[]; @@ -127,322 +102,8 @@ const PointSchema = new Schema( { timestamps: true } ); -// Model Creation const pointModel = (db: string) => { return MainModel(db, "Points", PointSchema, "Points"); }; export default pointModel; - -// %%%%%%%%%%%%%%%%%%%%%%%%%%%%% - -// import mongoose, { Schema, Document } from "mongoose"; -// import MainModel from "../../../connect/mongoose.ts"; - -// interface IActionConveyor { -// uuid: string; -// name: string; -// type: string; -// material: string; -// delay: number | string; -// spawnInterval: number | string; -// spawnMaterial: string; -// isUsed: boolean; -// hitCount: number; -// start: string; -// end: string; -// buffer: number; -// } - -// interface ITriggers { -// uuid: string; -// name: string; -// type: string; -// isUsed: boolean; -// bufferTime: number; -// } - -// interface IConnection { -// source: { modelUUID: string; pointUUID: string }; -// targets: { modelUUID: string; pointUUID: string }[]; -// } -// interface IActionVehicle { -// uuid: string; -// name: string; -// type: string; -// isUsed: boolean; -// hitCount: number; -// start: string; -// end: string; -// buffer: number; -// } -// interface IPointConveyor { -// uuid: string; -// position: number[]; -// rotation: number[]; -// actions: IActionConveyor[]; -// triggers: ITriggers[]; -// connections: IConnection; -// } -// interface IPointVehicle { -// uuid: string; -// position: number[]; -// actions: IActionVehicle[]; -// triggers: ITriggers[]; -// connections: IConnection; -// } - -// interface IBaseModel extends Document { -// modelfileID: string; -// type: "Conveyor" | "Vehicle"; -// points: IPointConveyor[] | IPointVehicle; -// } -// const PointconveyorSchema = new Schema({ -// uuid: { type: String, required: true }, -// position: { type: [Number] }, -// rotation: { type: [Number] }, -// actions: [ -// { -// uuid: { type: String, default: "" }, -// name: { type: String }, -// type: { type: String }, -// material: { type: String }, -// delay: { type: Schema.Types.Mixed }, -// spawnInterval: { type: Schema.Types.Mixed }, -// spawnMaterial: { type: String }, -// isUsed: { type: Boolean }, -// }, -// ], -// triggers: [ -// { -// uuid: { type: String, default: "" }, -// name: { type: String }, -// type: { type: String }, -// bufferTime: { type: Number }, -// isUsed: { type: Boolean }, -// }, -// ], -// connections: { -// source: { -// modelUUID: { type: String }, -// pointUUID: { type: String }, -// }, -// targets: [ -// { -// modelUUID: { type: String }, -// pointUUID: { type: String }, -// }, -// ], -// }, -// }); -// const PointvehicleSchema = new Schema({ -// uuid: { type: String, required: true }, -// position: { type: [Number] }, -// actions: [ -// { -// uuid: { type: String, default: "" }, -// name: { type: String }, -// type: { type: String }, -// isUsed: { type: Boolean }, -// hitCount: { type: String }, -// start: { type: String }, -// end: { type: String }, -// buffer: { type: String }, -// }, -// ], -// triggers: [ -// { -// uuid: { type: String, default: "" }, -// name: { type: String }, -// type: { type: String }, -// bufferTime: { type: Number }, -// isUsed: { type: Boolean }, -// }, -// ], -// connections: { -// source: { -// modelUUID: { type: String }, -// pointUUID: { type: String }, -// }, -// targets: [ -// { -// modelUUID: { type: String }, -// pointUUID: { type: String }, -// }, -// ], -// }, -// }); - -// const BaseSchema = new Schema( -// { -// modelfileID: { type: String }, -// type: { type: String, enum: ["Conveyor", "Vehicle"] }, -// points: { -// type: Schema.Types.Mixed, -// required: true, -// }, -// }, -// { discriminatorKey: "type", timestamps: true } -// ); - -// const pointModel = (db: string) => { -// const BasePointModel = MainModel(db, "Points", BaseSchema, "Points"); - -// const ConveyorModel = BasePointModel.discriminator( -// "Conveyor", -// new Schema({ -// points: [PointconveyorSchema], -// }) -// ); - -// const VehicleModel = BasePointModel.discriminator( -// "Vehicle", -// new Schema({ -// points: PointvehicleSchema, -// }) -// ); - -// return { ConveyorModel, VehicleModel }; -// }; - -// export default pointModel; - -// === -// const pointModel = (db: string) => { -// const BasePointModel = -// mongoose.models.Points || MainModel(db, "Points", BaseSchema, "Points"); - -// if (!BasePointModel.discriminators?.Conveyor) { -// BasePointModel.discriminator( -// "Conveyor", -// new Schema({ -// points: [PointconveyorSchema], -// }) -// ); -// } - -// if (!BasePointModel.discriminators?.Vehicle) { -// BasePointModel.discriminator( -// "Vehicle", -// new Schema({ -// points: PointvehicleSchema, -// }) -// ); -// } - -// const ConveyorModel = -// mongoose.models.Conveyor || BasePointModel.discriminators?.Conveyor; -// const VehicleModel = -// mongoose.models.Vehicle || BasePointModel.discriminators?.Vehicle; - -// return { ConveyorModel, VehicleModel, BasePointModel }; -// }; - -// export default pointModel; -// =========================================== -// === -// import mongoose, { Schema, Document } from "mongoose"; -// import MainModel from "../../../connect/mongoose.ts"; - -// interface IAction { -// uuid: string; -// name: string; -// type: string; -// material: string; -// delay: number | string; -// spawnInterval: number | string; -// spawnMaterial: string; -// isUsed: boolean; -// hitCount: number; -// start: string; -// end: string; -// buffer: number; -// } - -// interface ITriggers { -// uuid: string; -// name: string; -// type: string; -// isUsed: boolean; -// bufferTime: number; -// } - -// interface IConnection { -// source: { modelUUID: string; pointUUID: string }; -// targets: { modelUUID: string; pointUUID: string }[]; -// } -// interface IPoint { -// uuid: string; -// position: number[]; -// rotation: number[]; -// actions: IAction[]; -// triggers: ITriggers[]; -// connections: IConnection; -// } - -// interface IBaseModel extends Document { -// modelfileID: string; -// type: "Conveyor" | "Vehicle"; -// points: IPoint[] | IPoint; -// } - -// const PointSchema = new Schema({ -// uuid: { type: String, required: true }, -// position: { type: [Number] }, -// rotation: { type: [Number] }, -// actions: [ -// { -// uuid: { type: String, default: "" }, -// name: { type: String }, -// type: { type: String }, -// material: { type: String }, -// delay: { type: String }, -// spawnInterval: { type: String }, -// spawnMaterial: { type: String }, -// isUsed: { type: Boolean }, -// hitCount: { type: String }, -// start: { type: String }, -// end: { type: String }, -// buffer: { type: String }, -// }, -// ], -// triggers: [ -// { -// uuid: { type: String, default: "" }, -// name: { type: String }, -// type: { type: String }, -// bufferTime: { type: Number }, -// isUsed: { type: Boolean }, -// }, -// ], -// connections: { -// source: { -// modelUUID: { type: String }, -// pointUUID: { type: String }, -// }, -// targets: [ -// { -// modelUUID: { type: String }, -// pointUUID: { type: String }, -// }, -// ], -// }, -// }); -// // Base Schema - -// const BaseSchema = new Schema( -// { -// modelfileID: { type: String }, -// type: { type: String, enum: ["Conveyor", "Vehicle"] }, -// points: { -// type: Schema.Types.Mixed, -// required: true, -// }, -// }, -// { discriminatorKey: "type", timestamps: true } -// ); - -// const pointModel = (db: string) => { -// return MainModel(db, "Points", BaseSchema, "Points"); -// }; -// export default pointModel; diff --git a/src/shared/model/builder/assets/wallitems-Model.ts b/src/shared/model/builder/assets/wallitems-Model.ts index 8334cb8..f07c9a6 100644 --- a/src/shared/model/builder/assets/wallitems-Model.ts +++ b/src/shared/model/builder/assets/wallitems-Model.ts @@ -1,7 +1,6 @@ -import mongoose, { Document, Schema } from "mongoose"; +import { Document, Schema } from "mongoose"; import MainModel from "../../../connect/mongoose.ts"; -// Interface for TypeScript with PascalCase -export interface wallitems extends Document { +export interface WallItems extends Document { modelUuid: string; modelName: string; type: string; @@ -12,7 +11,6 @@ export interface wallitems extends Document { scale: []; } -// Define the Mongoose Schema const wallItemsSchema: Schema = new Schema({ modelUuid: { type: String, unique: true }, modelName: { type: String }, @@ -24,8 +22,7 @@ const wallItemsSchema: Schema = new Schema({ scale: { type: Array }, }); -// export default wallItenmModel; -const wallItenmModel = (db: string) => { +const wallItemModel = (db: string) => { return MainModel(db, "wallitems", wallItemsSchema, "wallitems"); }; -export default wallItenmModel; +export default wallItemModel; diff --git a/src/shared/model/builder/camera/camera-Model.ts b/src/shared/model/builder/camera/camera-Model.ts index 679f382..6ad13f0 100644 --- a/src/shared/model/builder/camera/camera-Model.ts +++ b/src/shared/model/builder/camera/camera-Model.ts @@ -1,7 +1,6 @@ -import mongoose, { Document, Schema } from "mongoose"; +import { Document, Schema } from "mongoose"; import MainModel from "../../../connect/mongoose.ts"; -// Interface for TypeScript with PascalCase export interface Camera extends Document { userId: string; position: { @@ -21,7 +20,6 @@ export interface Camera extends Document { }; } -// Define the Mongoose Schema const cameraSchema: Schema = new Schema({ userId: { type: String }, position: { @@ -41,7 +39,6 @@ const cameraSchema: Schema = new Schema({ }, }); -// export default cameraModel const cameraModel = (db: string) => { return MainModel(db, "Camera", cameraSchema, "Camera"); }; diff --git a/src/shared/model/builder/environments/environments-Model.ts b/src/shared/model/builder/environments/environments-Model.ts deleted file mode 100644 index 1ea37de..0000000 --- a/src/shared/model/builder/environments/environments-Model.ts +++ /dev/null @@ -1,24 +0,0 @@ -import mongoose, { Document, Schema } from 'mongoose'; -import MainModel from '../../../connect/mongoose.ts'; -// Interface for TypeScript with PascalCase -export interface environment extends Document { - userId: string; - roofVisibility: boolean - wallVisibility: boolean -} - -// Define the Mongoose Schema -const environmentSchema: Schema = new Schema({ - userId: { type: String, unique: true }, - roofVisibility: { type: Boolean, default: false }, - wallVisibility: { type: Boolean, default: false }, - shadowVisibility: { type: Boolean, default: false }, -}); - - - -// export default environmentModel; -const environmentModel = (db: string) => { - return MainModel(db, "environments", environmentSchema, "environments") -}; -export default environmentModel; \ No newline at end of file diff --git a/src/shared/model/builder/lines/lines-Model.ts b/src/shared/model/builder/lines/lines-Model.ts index e1c0f7f..d71fd29 100644 --- a/src/shared/model/builder/lines/lines-Model.ts +++ b/src/shared/model/builder/lines/lines-Model.ts @@ -1,4 +1,4 @@ -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 @@ -6,20 +6,17 @@ const positionSchema = new mongoose.Schema({ 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 }); -// export default lineModel; const lineModel = (db: string) => { return MainModel(db, "lines", LineSchema, "lines"); }; diff --git a/src/shared/model/builder/lines/zone-Model.ts b/src/shared/model/builder/lines/zone-Model.ts index 78cdae9..06602d3 100644 --- a/src/shared/model/builder/lines/zone-Model.ts +++ b/src/shared/model/builder/lines/zone-Model.ts @@ -1,40 +1,5 @@ -// import mongoose, { Schema, Document, model } from "mongoose"; -// import MainModel from "../../../connect/mongoose.ts"; -// export interface Zone extends Document { -// zoneName: string; -// // zoneUUID: string; -// zonePoints: []; -// centerPoints: []; -// isArchive: boolean; -// createdBy: string; -// sceneID: string; -// // createdBy: mongoose.Types.ObjectId; -// // sceneID: mongoose.Types.ObjectId; -// layer: number; -// } -// const zoneSchema: Schema = new Schema( -// { -// zoneName: { type: String }, -// // zoneUUID: { type: String }, -// createdBy: { type: String }, -// sceneID: { type: String }, -// layer: { type: Number }, -// centerPoints: { type: Array }, -// zonePoints: { type: Array }, -// isArchive: { type: Boolean, default: false }, -// // createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, -// // sceneID: { type: mongoose.Schema.Types.ObjectId, ref: "Scene" }, -// }, -// { timestamps: true } -// ); - -// const dataModel = (db: any) => { -// return MainModel(db, "Zones", zoneSchema, "Zones"); -// }; -// export default dataModel; - -import mongoose, { Schema, Document, model } from "mongoose"; +import { Schema, Document } from "mongoose"; import MainModel from "../../../connect/mongoose.ts"; export interface Zone extends Document { diff --git a/src/shared/model/camera/camera-Model.ts b/src/shared/model/camera/camera-Model.ts index 7c8e35b..692a174 100644 --- a/src/shared/model/camera/camera-Model.ts +++ b/src/shared/model/camera/camera-Model.ts @@ -1,87 +1,45 @@ -import mongoose, { Document, Schema } from 'mongoose'; -import MainModel from '../../connect/mongoose.ts'; +import { Document, Schema } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; -// Interface for TypeScript with PascalCase export interface Camera extends Document { userId: string; position: { x: number; y: number; 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 }; + }; } -// Define the Mongoose Schema const cameraSchema: Schema = new Schema({ userId: { type: String }, position: { x: { type: Number, required: true }, y: { type: Number, required: true }, - z: { type: Number, required: true } + z: { type: Number, required: true }, }, target: { x: { type: Number, required: true }, y: { type: Number, required: true }, - z: { 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 } - } + z: { type: Number, required: true }, + }, }); -// Model for MongoDB collection -// const cameraModel = model("Camera", cameraSchema); - -// export default cameraModel; -// const cameraModel = (db: string) => { -// const mongoUrl = process.env.MONGO_URI || ''; -// if (!mongoUrl) { -// throw new Error('MONGO_URI environment variable is not set'); -// } -// // Connect to the database -// const dbConnection = mongoose.createConnection(mongoUrl, { -// dbName: db, // Specify the database name here -// serverSelectionTimeoutMS: 30000, -// }); -// return dbConnection.model('Camera', cameraSchema,`Camera`); -// } - -// export default cameraModel; -// const cameraModel = (db: string) => { -// const mongoUrl = process.env.MONGO_URI || ''; -// if (!mongoUrl) { -// throw new Error('MONGO_URI environment variable is not set'); -// } - -// const dbConnection = mongoose.createConnection(mongoUrl, { -// dbName: db, -// serverSelectionTimeoutMS: 60000, // Increased timeout -// }); - -// dbConnection.on('error', (err) => { -// console.error(`MongoDB connection error for database ${db}:`, err); -// }); - -// dbConnection.once('open', () => { -// console.log(`Connected to MongoDB database: ${db}`); -// }); - -// return dbConnection.model('Camera', cameraSchema, 'Camera'); -// }; -// export default cameraModel -const cameraModel = (db:string) => { - return MainModel(db, "Camera", cameraSchema, "Camera") +const cameraModel = (db: string) => { + return MainModel(db, "Camera", cameraSchema, "Camera"); }; -export default cameraModel; \ No newline at end of file +export default cameraModel; diff --git a/src/shared/model/environments/environments-Model.ts b/src/shared/model/environments/environments-Model.ts index bbb9fe0..3b004f2 100644 --- a/src/shared/model/environments/environments-Model.ts +++ b/src/shared/model/environments/environments-Model.ts @@ -1,7 +1,7 @@ -import mongoose, { Document, Schema } from "mongoose"; +import { Document, Schema } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; -// Interface for TypeScript with PascalCase -export interface environment extends Document { + +export interface Environment extends Document { userId: string; roofVisibility: boolean; wallVisibility: boolean; @@ -10,7 +10,6 @@ export interface environment extends Document { limitDistance: boolean; } -// Define the Mongoose Schema const environmentSchema: Schema = new Schema({ userId: { type: String, unique: true }, roofVisibility: { type: Boolean, default: false }, @@ -20,24 +19,6 @@ const environmentSchema: Schema = new Schema({ limitDistance: { type: Boolean, default: true }, }); -// Model for MongoDB collection -// const cameraModel = model("Camera", cameraSchema); - -// export default cameraModel; -// const environmentModel = (db: string) => { -// const mongoUrl = process.env.MONGO_URI || ''; -// if (!mongoUrl) { -// throw new Error('MONGO_URI environment variable is not set'); -// } -// // Connect to the database -// const dbConnection = mongoose.createConnection(mongoUrl, { -// dbName: db, // Specify the database name here -// serverSelectionTimeoutMS: 30000, -// }); -// return dbConnection.model('environments', environmentSchema,`environments`); -// } - -// export default environmentModel; const environmentModel = (db: string) => { return MainModel(db, "environments", environmentSchema, "environments"); }; diff --git a/src/shared/model/project/project-model.ts b/src/shared/model/project/project-model.ts index e3bf659..a675252 100644 --- a/src/shared/model/project/project-model.ts +++ b/src/shared/model/project/project-model.ts @@ -18,7 +18,7 @@ export interface Project extends Document { const projectSchema: Schema = new Schema( { projectUuid: { type: String }, - projectName: { type: String }, + projectName: { type: String }, thumbnail: { type: String }, isArchive: { type: Boolean, default: false }, createdBy: { type: Schema.Types.ObjectId, ref: "user" }, diff --git a/src/shared/model/simulation/actionmodel.ts b/src/shared/model/simulation/actionmodel.ts index 911d1c9..782d0dd 100644 --- a/src/shared/model/simulation/actionmodel.ts +++ b/src/shared/model/simulation/actionmodel.ts @@ -1,12 +1,9 @@ -import mongoose, { Schema, Document, model } from "mongoose"; +import { Schema, Document } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; export interface Action extends Document { pointsUUID: string; - // actionUUID: string; isArchive: string; - // sceneID: string; - // eventData: { uuid: string; name: string; type: string; @@ -19,13 +16,11 @@ export interface Action extends Document { start: string; end: string; buffer: number; - // }; } const actionSchema: Schema = new Schema( { pointsUUID: { type: String }, isArchive: { type: Boolean, default: false }, - // actionUUID: { type: String }, uuid: { type: String, default: "" }, name: { type: String }, type: { type: String }, diff --git a/src/shared/model/simulation/eventsDataModel.ts b/src/shared/model/simulation/eventsDataModel.ts index 2286e33..a331e83 100644 --- a/src/shared/model/simulation/eventsDataModel.ts +++ b/src/shared/model/simulation/eventsDataModel.ts @@ -1,179 +1,182 @@ // models/Product.ts -import mongoose, { Schema, Document, Types } from "mongoose"; +import { Schema, Document } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; interface AssetEventSchema { - modelUuid: string; - modelName: string; - position: [number, number, number]; - rotation: [number, number, number]; - state: "idle" | "running" | "stopped" | "disabled" | "error"; -}; + modelUuid: string; + modelName: string; + position: [number, number, number]; + rotation: [number, number, number]; + state: "idle" | "running" | "stopped" | "disabled" | "error"; +} interface TriggerSchema { - triggerUuid: string; - triggerName: string; - triggerType: "onComplete" | "onStart" | "onStop" | "delay" | "onError"; - delay: number; - triggeredAsset: { - triggeredModel: { modelName: string, modelUuid: string }; - triggeredPoint: { pointName: string, pointUuid: string }; - triggeredAction: { actionName: string, actionUuid: string }; - } | null; + triggerUuid: string; + triggerName: string; + triggerType: "onComplete" | "onStart" | "onStop" | "delay" | "onError"; + delay: number; + triggeredAsset: { + triggeredModel: { modelName: string; modelUuid: string }; + triggeredPoint: { pointName: string; pointUuid: string }; + triggeredAction: { actionName: string; actionUuid: string }; + } | null; } interface ConveyorPointSchema { - uuid: string; - position: [number, number, number]; - rotation: [number, number, number]; - action: { - actionUuid: string; - actionName: string; - actionType: "default" | "spawn" | "swap" | "despawn"; - material: string; - delay: number | "inherit"; - spawnInterval: number | "inherit"; - spawnCount: number | "inherit"; - triggers: TriggerSchema[]; - }; + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + action: { + actionUuid: string; + actionName: string; + actionType: "default" | "spawn" | "swap" | "despawn"; + material: string; + delay: number | "inherit"; + spawnInterval: number | "inherit"; + spawnCount: number | "inherit"; + triggers: TriggerSchema[]; + }; } interface VehiclePointSchema { - uuid: string; - position: [number, number, number]; - rotation: [number, number, number]; - action: { - actionUuid: string; - actionName: string; - actionType: "travel"; - material: string | null; - unLoadDuration: number; - loadCapacity: number; - pickUpPoint: { x: number; y: number, z: number } | null; - unLoadPoint: { x: number; y: number, z: number } | null; - triggers: TriggerSchema[]; - }; + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + action: { + actionUuid: string; + actionName: string; + actionType: "travel"; + material: string | null; + unLoadDuration: number; + loadCapacity: number; + pickUpPoint: { x: number; y: number; z: number } | null; + unLoadPoint: { x: number; y: number; z: number } | null; + triggers: TriggerSchema[]; + }; } interface RoboticArmPointSchema { - uuid: string; - position: [number, number, number]; - rotation: [number, number, number]; - actions: { - actionUuid: string; - actionName: string; - actionType: "pickAndPlace"; - process: { startPoint: [number, number, number]; endPoint: [number, number, number] }; - triggers: TriggerSchema[]; - }[]; + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + actions: { + actionUuid: string; + actionName: string; + actionType: "pickAndPlace"; + process: { + startPoint: [number, number, number]; + endPoint: [number, number, number]; + }; + triggers: TriggerSchema[]; + }[]; } interface MachinePointSchema { - uuid: string; - position: [number, number, number]; - rotation: [number, number, number]; - action: { - actionUuid: string; - actionName: string; - actionType: "process"; - processTime: number; - swapMaterial: string; - triggers: TriggerSchema[]; - }; + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + action: { + actionUuid: string; + actionName: string; + actionType: "process"; + processTime: number; + swapMaterial: string; + triggers: TriggerSchema[]; + }; } interface StoragePointSchema { - uuid: string; - position: [number, number, number]; - rotation: [number, number, number]; - action: { - actionUuid: string; - actionName: string; - actionType: "storage"; - materials: { materialName: string; materialId: string; }[]; - storageCapacity: number; - }; + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + action: { + actionUuid: string; + actionName: string; + actionType: "storage"; + materials: { materialName: string; materialId: string }[]; + storageCapacity: number; + }; } interface ConveyorEventSchema extends AssetEventSchema { - type: "transfer"; - speed: number; - points: ConveyorPointSchema[]; + type: "transfer"; + speed: number; + points: ConveyorPointSchema[]; } interface VehicleEventSchema extends AssetEventSchema { - type: "vehicle"; - speed: number; - point: VehiclePointSchema; + type: "vehicle"; + speed: number; + point: VehiclePointSchema; } interface RoboticArmEventSchema extends AssetEventSchema { - type: "roboticArm"; - speed: number; - point: RoboticArmPointSchema; + type: "roboticArm"; + speed: number; + point: RoboticArmPointSchema; } interface MachineEventSchema extends AssetEventSchema { - type: "machine"; - // speed: number; - point: MachinePointSchema; + type: "machine"; + // speed: number; + point: MachinePointSchema; } interface StorageEventSchema extends AssetEventSchema { - type: "storageUnit"; - // speed: number; - point: StoragePointSchema; + type: "storageUnit"; + // speed: number; + point: StoragePointSchema; } interface IPointModel extends Document { - modelUuid:String, - modelName:String, - position:String, - rotation:String, - state:String, - productId:String, - isArchive:boolean, - type: "transfer" | "vehicle" | "roboticArm" | "machine" |"storageUnit"; + modelUuid: String; + modelName: String; + position: String; + rotation: String; + state: String; + productId: String; + isArchive: boolean; + type: "transfer" | "vehicle" | "roboticArm" | "machine" | "storageUnit"; speed: number; - point: VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema - points: ConveyorEventSchema[] - + point: + | VehicleEventSchema + | RoboticArmEventSchema + | MachineEventSchema + | StorageEventSchema; + points: ConveyorEventSchema[]; } // type EventsSchema = ConveyorEventSchema | VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema; - const BaseEventSchema = new Schema( - { - modelUuid: { type: String, required: true }, - modelName: { type: String, required: true }, - position: { type: [Number], required: true }, - rotation: { type: [Number], required: true }, - speed: { type: Number,}, - state: { - type: String, - enum: ["idle", "running", "stopped", "disabled", "error"], - default: "idle" - }, - type: { - type: String, - required: true, - enum: ["transfer", "vehicle", "roboticArm", "machine", "storageUnit"] - }, - point:{ - type:Schema.Types.Mixed, - - }, - points:{ - type:Schema.Types.Mixed, - - }, - productId: { type:String,required: true }, - isArchive: { type: Boolean, default: false } + { + modelUuid: { type: String, required: true }, + modelName: { type: String, required: true }, + position: { type: [Number], required: true }, + rotation: { type: [Number], required: true }, + speed: { type: Number }, + state: { + type: String, + enum: ["idle", "running", "stopped", "disabled", "error"], + default: "idle", }, - { discriminatorKey: "type", timestamps: true } - ); - - const EventsDataModel = (db: string) => { - return MainModel(db, "EventDatas", BaseEventSchema, "EventDatas"); - }; - - export default EventsDataModel; \ No newline at end of file + type: { + type: String, + required: true, + enum: ["transfer", "vehicle", "roboticArm", "machine", "storageUnit"], + }, + point: { + type: Schema.Types.Mixed, + }, + points: { + type: Schema.Types.Mixed, + }, + productId: { type: String, required: true }, + isArchive: { type: Boolean, default: false }, + }, + { discriminatorKey: "type", timestamps: true } +); + +const EventsDataModel = (db: string) => { + return MainModel(db, "EventDatas", BaseEventSchema, "EventDatas"); +}; + +export default EventsDataModel; diff --git a/src/shared/model/simulation/productFlowmodel.ts b/src/shared/model/simulation/productFlowmodel.ts deleted file mode 100644 index 4755676..0000000 --- a/src/shared/model/simulation/productFlowmodel.ts +++ /dev/null @@ -1,97 +0,0 @@ -// import mongoose, { Schema, Document, model } from "mongoose"; -// import MainModel from "../../connect/mongoose.ts"; - -// export interface ProductFlow extends Document { -// productName: string; -// ProductData: [ -// { -// AssetName: string; -// Assetuuid: string; -// paths: { -// Points: [ -// { -// pointuuid: string; -// actions: [mongoose.Types.ObjectId]; -// triggers: [mongoose.Types.ObjectId]; -// position: []; -// rotation: [number]; -// connections: { -// source: { -// // modelUUID: { type: String }; -// pointUUID: string; -// }; -// targets: [ -// { -// // modelUUID: { type: String }; -// pointUUID: string; -// } -// ]; -// }; -// } -// ]; -// // endPoint: { -// // pointuuid: string; -// // actions: [mongoose.Types.ObjectId]; -// // triggers: [mongoose.Types.ObjectId]; -// // position: []; -// // rotation: []; -// // }; -// }; -// isArchive: false; -// } -// ]; -// isArchive: false; -// } -// const productFlowSchema: Schema = new Schema( -// { -// productName: { type: String }, -// ProductData: [ -// { -// AssetName: { type: String }, -// Assetuuid: { type: String }, -// paths: { -// Points: [ -// { -// pointuuid: { type: String }, -// actions: [ -// { type: mongoose.Schema.Types.ObjectId, ref: "Actions" }, -// ], -// triggers: [ -// { type: mongoose.Schema.Types.ObjectId, ref: "Triggers" }, -// ], -// connections: { -// source: { -// // modelUUID: { type: String }; -// pointUUID: { type: String }, -// }, -// targets: [ -// { -// // modelUUID: { type: String }; -// pointUUID: { type: String }, -// }, -// ], -// }, -// position: { type: Array }, -// rotation: { -// type: [Number], -// validate: { -// validator: function (value: number[]) { -// return value && value.length > 0; // Ensures it's only stored if it has values -// }, -// message: "Rotation array should not be empty", -// }, -// }, -// }, -// ], -// }, -// isArchive: { type: Boolean, default: false }, -// }, -// ], -// }, -// { timestamps: true } -// ); - -// const productFlowModel = (db: any) => { -// return MainModel(db, "ProductFlow", productFlowSchema, "ProductFlow"); -// }; -// export default productFlowModel; diff --git a/src/shared/model/simulation/productModel.ts b/src/shared/model/simulation/productModel.ts index bf0fc76..4be6b9b 100644 --- a/src/shared/model/simulation/productModel.ts +++ b/src/shared/model/simulation/productModel.ts @@ -1,24 +1,20 @@ -import mongoose, { Schema, Document, model } from "mongoose"; +import { Schema, Document } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; -export interface product extends Document { +export interface Product extends Document { productName: string; productId: string; eventsData: []; isArchive: boolean; - } - -// Product Schema const ProductSchema = new Schema({ productName: { type: String, required: true }, productId: { type: String, required: true }, isArchive: { type: Boolean, default: false }, }); - const ProductModel = (db: string) => { return MainModel(db, "Product", ProductSchema, "Product"); }; -export default ProductModel; \ No newline at end of file +export default ProductModel; diff --git a/src/shared/model/simulation/triggersmodel.ts b/src/shared/model/simulation/triggersmodel.ts index 83a0b7c..3b12c54 100644 --- a/src/shared/model/simulation/triggersmodel.ts +++ b/src/shared/model/simulation/triggersmodel.ts @@ -1,4 +1,4 @@ -import mongoose, { Schema, Document, model } from "mongoose"; +import { Schema, Document } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; export interface Trigger extends Document { diff --git a/src/shared/model/user-Model.ts b/src/shared/model/user-Model.ts index 2f1e13d..ab19c2c 100644 --- a/src/shared/model/user-Model.ts +++ b/src/shared/model/user-Model.ts @@ -1,4 +1,4 @@ -import mongoose, { Document, Schema } from "mongoose"; +import { Document, Schema } from "mongoose"; import MainModel from "../connect/mongoose.ts"; export interface User extends Document { userName: String; @@ -48,24 +48,8 @@ const signupschema: Schema = new Schema({ default: [], }, }); -// const userModel = (db: string) => { -// const mongoUrl = process.env.MONGO_URI || ""; -// if (!mongoUrl) { -// throw new Error("MONGO_URI environment variable is not set"); -// } -// // Connect to the database -// const dbConnection = mongoose.createConnection(mongoUrl, { -// dbName: db, // Specify the database name here -// serverSelectionTimeoutMS: 30000, -// }); - -// // Return the model -// return dbConnection.model("Users", signupschema, "Users"); -// }; - -// export default userModel; -const userModel = (db: string) => { - return MainModel(db, "Users", signupschema, "Users"); +const userModel = (db:string) => { + return MainModel(db, "Users", signupschema, "Users") }; export default userModel; diff --git a/src/shared/model/vizualization/3dwidget.ts b/src/shared/model/vizualization/3dwidget.ts index 568fa7c..734268d 100644 --- a/src/shared/model/vizualization/3dwidget.ts +++ b/src/shared/model/vizualization/3dwidget.ts @@ -1,4 +1,4 @@ -import mongoose, { Schema, Document, model } from "mongoose"; +import { Schema, Document, model } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; export interface Widget3d extends Document { diff --git a/src/shared/model/vizualization/floatWidget.ts b/src/shared/model/vizualization/floatWidget.ts index c4c4646..512a77e 100644 --- a/src/shared/model/vizualization/floatWidget.ts +++ b/src/shared/model/vizualization/floatWidget.ts @@ -1,7 +1,7 @@ -import mongoose, { Schema, Document, model } from "mongoose"; +import { Schema, Document, model } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; -export interface floatingWidget extends Document { +export interface FloatingWidget extends Document { className: string; iconName: string; header: string; diff --git a/src/shared/model/vizualization/panelmodel.ts b/src/shared/model/vizualization/panelmodel.ts index ef15939..cd5582f 100644 --- a/src/shared/model/vizualization/panelmodel.ts +++ b/src/shared/model/vizualization/panelmodel.ts @@ -1,8 +1,7 @@ -import mongoose, { Schema, Document, model } from "mongoose"; +import mongoose, { Schema, Document } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; export interface Panel extends Document { - // zoneId: mongoose.Types.ObjectId; zoneId: string; panelName: string; widgets: [mongoose.Types.ObjectId]; @@ -10,7 +9,6 @@ export interface Panel extends Document { } const panelSchema: Schema = new Schema( { - // zoneId: { type: mongoose.Schema.Types.ObjectId, ref: "Zone" }, zoneId: { type: String }, panelName: { type: String }, widgets: [{ type: mongoose.Schema.Types.ObjectId, ref: "Widget" }], diff --git a/src/shared/model/vizualization/templatemodel.ts b/src/shared/model/vizualization/templatemodel.ts index 2499beb..b616253 100644 --- a/src/shared/model/vizualization/templatemodel.ts +++ b/src/shared/model/vizualization/templatemodel.ts @@ -1,4 +1,4 @@ -import mongoose, { Schema, Document, model } from "mongoose"; +import { Schema, Document } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; export interface Template extends Document { diff --git a/src/shared/model/vizualization/widgemodel.ts b/src/shared/model/vizualization/widgemodel.ts index 2db2613..2a2749c 100644 --- a/src/shared/model/vizualization/widgemodel.ts +++ b/src/shared/model/vizualization/widgemodel.ts @@ -1,4 +1,4 @@ -import mongoose, { Schema, Document, model } from "mongoose"; +import mongoose, { Schema, Document } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; export interface widget extends Document { diff --git a/src/shared/services/project/project-Services.ts b/src/shared/services/project/project-Services.ts index 7a23cad..66dd66a 100644 --- a/src/shared/services/project/project-Services.ts +++ b/src/shared/services/project/project-Services.ts @@ -1,6 +1,5 @@ import projectModel from "../../model/project/project-model.ts"; import userModel from "../../model/user-Model.ts"; -import { Types } from "mongoose"; import versionModel from "../../model/version/versionModel.ts"; import { existingProject, diff --git a/src/shared/services/wall/wallItemservice.ts b/src/shared/services/wall/wallItemservice.ts new file mode 100644 index 0000000..2cad661 --- /dev/null +++ b/src/shared/services/wall/wallItemservice.ts @@ -0,0 +1,115 @@ +import { Request, Response } from "express"; +import wallItemModel from "../../../shared/model/builder/assets/wallitems-Model.ts"; +interface IWallSetupData { + modelUuid: string; + modelName: string; + type: string; + csgposition: []; + csgscale: []; + position: []; + quaternion: []; + scale: []; + organization: string; +} +interface IWallItemResult { + data: {}; + state: string; +} +export class WallItems { + static async setWallItems(data: IWallSetupData): Promise { + try { + const { + modelUuid, + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + organization, + } = data; + const findvalue = await wallItemModel(organization).findOne({ + modelUuid: modelUuid, + }); + + if (findvalue) { + const updatevalue = await wallItemModel(organization).findOneAndUpdate( + { modelUuid: modelUuid }, + { + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + }, + { new: true } // Return the updated document + ); + return { + state: "Updated successfully", + data: updatevalue, + }; + // res.status(201).json(updatevalue); + } else { + const newValue = await wallItemModel(organization).create({ + modelUuid, + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + }); + return { + 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) { + try { + const { organization } = req.params; + + const findValue = await wallItemModel(organization).find(); + if (!findValue) { + res.status(200).json("wallitems not found"); + } else { + res.status(201).json(findValue); + } + } catch (error) { + console.error("Error get wallitems:", error); + res.status(500).json({ error: "Failed to get wallitems" }); + } + } + static async deleteWallItems(req: Request, res: Response) { + try { + const { modelUuid, modelName, organization } = req.body; + + const findValue = await wallItemModel(organization).findOneAndDelete({ + modelUuid: modelUuid, + modelName: modelName, + }); + if (!findValue) { + res.status(200).json("user not found"); + } else { + res.status(201).json(findValue); + } + } catch (error) { + console.error("Error get wallitems:", error); + res.status(500).json({ error: "Failed to get wallitems" }); + } + } +} diff --git a/src/socket-server/services/assets/wallitem-Controller.ts b/src/socket-server/services/assets/wallitem-Controller.ts index 013bbb4..16dcaf8 100644 --- a/src/socket-server/services/assets/wallitem-Controller.ts +++ b/src/socket-server/services/assets/wallitem-Controller.ts @@ -1,60 +1,99 @@ import { Request, Response } from "express"; -import wallItenmModel from "../../../shared/model/assets/wallitems-Model.ts"; - +import wallItemModel from "../../../shared/model/builder/assets/wallitems-Model.ts"; export const setWallItems = async (data: any) => { - try { - const { modelUuid,modelfileID, modelName, position, type, csgposition, csgscale, quaternion, scale, organization } = data + try { + const { + modelUuid, + modelfileID, + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + organization, + } = data; - - const findvalue = await wallItenmModel(organization).findOne({ modelUuid: modelUuid }) - if (findvalue) { - - const updatevalue = await wallItenmModel(organization).findOneAndUpdate( - { modelUuid: modelUuid }, - { - modelName, - position, - type, - csgposition, - csgscale, - quaternion, - scale, - }, - { new: true } // Return the updated document - ); - return { success: true, message: 'wallIitem updated', data: updatevalue, organization: organization } - - - } else { - - const newValue = await wallItenmModel(organization).create({ modelUuid,modelfileID, modelName, position, type, csgposition, csgscale, quaternion, scale }); - return { success: true, message: 'wallIitem created', data: newValue, organization: organization } - } - - // Send response with the created document - } catch (error) { - console.error('Error creating wallIitem:', error); - return { success: false, message: 'Error creating or updating camera', error } + const findvalue = await wallItemModel(organization).findOne({ + modelUuid: modelUuid, + }); + if (findvalue) { + const updatevalue = await wallItemModel(organization).findOneAndUpdate( + { modelUuid: modelUuid }, + { + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + }, + { new: true } // Return the updated document + ); + return { + success: true, + message: "wallIitem updated", + data: updatevalue, + organization: organization, + }; + } else { + const newValue = await wallItemModel(organization).create({ + modelUuid, + modelfileID, + modelName, + position, + type, + csgposition, + csgscale, + quaternion, + scale, + }); + return { + success: true, + message: "wallIitem created", + data: newValue, + organization: organization, + }; } -} + + // Send response with the created document + } catch (error) { + console.error("Error creating wallIitem:", error); + return { + success: false, + message: "Error creating or updating camera", + error, + }; + } +}; export const deleteWallItems = async (data: any) => { - try { - const { modelUuid, modelName, organization } = data; - - - const findValue = await wallItenmModel(organization).findOneAndDelete({ modelUuid: modelUuid, modelName: modelName }) - if (!findValue) { - return { success: false, message: 'model not found', organization: organization } - - } else { - - return { success: true, message: 'wallitem deleted', data: findValue, organization: organization } - } - } catch (error) { - console.error('Error get wallitem:', error); - return { success: false, message: 'Failed to delete wallitem', error } + try { + const { modelUuid, modelName, organization } = data; + const findValue = await wallItemModel(organization).findOneAndDelete({ + modelUuid: modelUuid, + modelName: modelName, + }); + if (!findValue) { + return { + success: false, + message: "model not found", + organization: organization, + }; + } else { + return { + success: true, + message: "wallitem deleted", + data: findValue, + organization: organization, + }; } -} + } catch (error) { + console.error("Error get wallitem:", error); + return { success: false, message: "Failed to delete wallitem", error }; + } +}; From 1c55013c2b7e09a1d8667db4a85f6086f81007a8 Mon Sep 17 00:00:00 2001 From: Nivetharamesh Date: Sat, 17 May 2025 11:15:53 +0530 Subject: [PATCH 2/6] Schema Model - new Version Added --- src/shared/V1Models/Auth/tokenModel.ts | 24 +++ src/shared/V1Models/Auth/user.ts | 46 +++++ src/shared/V1Models/Auth/userAuthModel.ts | 34 ++++ src/shared/V1Models/Builder/assetModel.ts | 71 +++++++ src/shared/V1Models/Builder/cameraModel.ts | 51 +++++ src/shared/V1Models/Builder/linesModel.ts | 29 +++ src/shared/V1Models/Builder/wallItemsModel.ts | 37 ++++ src/shared/V1Models/Builder/zoneModel.ts | 50 +++++ .../Environment/environments-Model.ts | 25 +++ src/shared/V1Models/Project/project-model.ts | 39 ++++ .../V1Models/Simulation/eventsDataModel.ts | 182 ++++++++++++++++++ .../V1Models/Simulation/productModel.ts | 26 +++ src/shared/V1Models/Version/versionModel.ts | 27 +++ src/shared/V1Models/Vizualization/3dwidget.ts | 37 ++++ .../V1Models/Vizualization/floatWidget.ts | 46 +++++ .../V1Models/Vizualization/panelmodel.ts | 23 +++ .../V1Models/Vizualization/templatemodel.ts | 39 ++++ .../V1Models/Vizualization/widgemodel.ts | 47 +++++ 18 files changed, 833 insertions(+) create mode 100644 src/shared/V1Models/Auth/tokenModel.ts create mode 100644 src/shared/V1Models/Auth/user.ts create mode 100644 src/shared/V1Models/Auth/userAuthModel.ts create mode 100644 src/shared/V1Models/Builder/assetModel.ts create mode 100644 src/shared/V1Models/Builder/cameraModel.ts create mode 100644 src/shared/V1Models/Builder/linesModel.ts create mode 100644 src/shared/V1Models/Builder/wallItemsModel.ts create mode 100644 src/shared/V1Models/Builder/zoneModel.ts create mode 100644 src/shared/V1Models/Environment/environments-Model.ts create mode 100644 src/shared/V1Models/Project/project-model.ts create mode 100644 src/shared/V1Models/Simulation/eventsDataModel.ts create mode 100644 src/shared/V1Models/Simulation/productModel.ts create mode 100644 src/shared/V1Models/Version/versionModel.ts create mode 100644 src/shared/V1Models/Vizualization/3dwidget.ts create mode 100644 src/shared/V1Models/Vizualization/floatWidget.ts create mode 100644 src/shared/V1Models/Vizualization/panelmodel.ts create mode 100644 src/shared/V1Models/Vizualization/templatemodel.ts create mode 100644 src/shared/V1Models/Vizualization/widgemodel.ts diff --git a/src/shared/V1Models/Auth/tokenModel.ts b/src/shared/V1Models/Auth/tokenModel.ts new file mode 100644 index 0000000..94b93e4 --- /dev/null +++ b/src/shared/V1Models/Auth/tokenModel.ts @@ -0,0 +1,24 @@ +import { Schema, Document } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +import { User } from "./userAuthModel.ts"; +export interface Token extends Document { + userId: User["_id"]; + isArchieve: Boolean; + refreshToken: string; + resetTokenExpiry?: Date; + resetToken: string; +} +const tokenSchema: Schema = new Schema({ + userId: { type: Schema.Types.ObjectId, ref: "User" }, + isArchieve: { type: Boolean, default: false }, + token: { type: String }, + refreshToken: { type: String }, + tokenCreatedAt: { type: Date }, + resetToken: { type: String }, + resetTokenExpiry: { type: Date }, +}); + +const tokenType = (db: any) => { + return MainModel(db, "Token", tokenSchema, "Token"); +}; +export default tokenType; diff --git a/src/shared/V1Models/Auth/user.ts b/src/shared/V1Models/Auth/user.ts new file mode 100644 index 0000000..dba27bc --- /dev/null +++ b/src/shared/V1Models/Auth/user.ts @@ -0,0 +1,46 @@ +import { Schema, Document } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +import { User } from "./userAuthModel.ts"; +export interface UserData extends Document { + userId: User["_id"]; + notificationEnable: boolean; + About: string; + isArchieve: boolean; + Role: string; + Profilepicture: string; + recentlyViewed: string[]; + CheckIn: number; + CheckOut: number; +} +const UserDataSchema: Schema = new Schema({ + userId: { type: Schema.Types.ObjectId, ref: "User" }, + isArchieve: { type: Boolean, default: false }, + notificationEnable: { type: Boolean, default: false }, + About: { + type: String, + }, + Role: { + type: String, + default: "User", + enum: ["User", "Admin"], + }, + recentlyViewed: { + type: [String], + default: [], + }, + Profilepicture: { + type: String, + // default: "default-profile-picture.jpg" + }, + CheckIn: { + type: Number, + }, + CheckOut: { + type: Number, + }, +}); + +const UsersDataModel = (db: any) => { + return MainModel(db, "UsersData", UserDataSchema, "UsersData"); +}; +export default UsersDataModel; diff --git a/src/shared/V1Models/Auth/userAuthModel.ts b/src/shared/V1Models/Auth/userAuthModel.ts new file mode 100644 index 0000000..d1ce57b --- /dev/null +++ b/src/shared/V1Models/Auth/userAuthModel.ts @@ -0,0 +1,34 @@ +import { Schema, Document } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +export interface User extends Document { + Username: string; + Email: string; + Password: string; + isArchieve: boolean; + visitorBrowserID: string; + lastPasswordReset: number; +} +const signupschema: Schema = new Schema({ + Username: { + type: String, + required: true, + }, + Email: { + type: String, + unique: true, + required: true, + }, + Password: { + type: String, + min: 8, + // required: true, + }, + isArchieve: { type: Boolean, default: false }, + lastPasswordReset: { type: Number }, + visitorBrowserID: { type: String }, +}); + +const userModel = (db: any) => { + return MainModel(db, "User", signupschema, "User"); +}; +export default userModel; diff --git a/src/shared/V1Models/Builder/assetModel.ts b/src/shared/V1Models/Builder/assetModel.ts new file mode 100644 index 0000000..94f0c64 --- /dev/null +++ b/src/shared/V1Models/Builder/assetModel.ts @@ -0,0 +1,71 @@ +import { Document, 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"; +interface ICommonBase { + type: string; +} +interface IPointsConveyor extends ICommonBase { + points?: { + Uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + }[]; +} +interface IPoint extends ICommonBase { + point?: { + Uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + }; +} +export interface AssetData extends Document { + userId: User["_id"]; + projectId: Project["_id"]; + versionId: Version["_id"]; + modelUuid: string; + modelfileID: string; + modelName: string; + isLocked: boolean; + type: string; + isVisible: boolean; + isArchive: false; + // points: [] | {}; + position: []; + rotation: { + x: number; + y: number; + z: number; + }; + speed: number | string; + eventData: IPoint | IPointsConveyor; +} + +const assetDataSchema: Schema = new Schema({ + userId: { type: Schema.Types.ObjectId, ref: "User" }, + projectId: { type: Schema.Types.ObjectId, ref: "Project" }, + versionId: { type: Schema.Types.ObjectId, ref: "Version" }, + isArchive: { type: Boolean, default: false }, + modelUuid: { type: String }, + modelfileID: { type: String }, + modelName: { type: String }, + type: { type: String }, + position: { type: Array }, + rotation: { + x: { type: Number }, + y: { type: Number }, + z: { type: Number }, + }, + speed: { type: Schema.Types.Mixed }, + isLocked: { type: Boolean }, + isVisible: { type: Boolean }, + eventData: { + type: Schema.Types.Mixed, + }, +}); + +const assetModel = (db: string) => { + return MainModel(db, "Assets", assetDataSchema, "Assets"); +}; +export default assetModel; diff --git a/src/shared/V1Models/Builder/cameraModel.ts b/src/shared/V1Models/Builder/cameraModel.ts new file mode 100644 index 0000000..183430a --- /dev/null +++ b/src/shared/V1Models/Builder/cameraModel.ts @@ -0,0 +1,51 @@ +import { Document, 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"; +export interface Camera extends Document { + userId: User["_id"]; + projectId: Project["_id"]; + versionId: Version["_id"]; + position: { + x: number; + y: number; + z: number; + }; + target: { + 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 }; + }; +} + +const cameraSchema: Schema = new Schema({ + userId: { type: Schema.Types.ObjectId, ref: "User" }, + projectId: { type: Schema.Types.ObjectId, ref: "Project" }, + versionId: { type: Schema.Types.ObjectId, ref: "Version" }, + position: { + x: { type: Number, required: true }, + y: { type: Number, required: true }, + z: { type: Number, required: true }, + }, + target: { + 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 }, + }, +}); + +const cameraModel = (db: string) => { + return MainModel(db, "Camera", cameraSchema, "Camera"); +}; +export default cameraModel; diff --git a/src/shared/V1Models/Builder/linesModel.ts b/src/shared/V1Models/Builder/linesModel.ts new file mode 100644 index 0000000..484bb9a --- /dev/null +++ b/src/shared/V1Models/Builder/linesModel.ts @@ -0,0 +1,29 @@ +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"; +const positionSchema = new mongoose.Schema({ + x: { type: Number }, // Optional position fields + 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 +}); + +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 +}); + +const lineModel = (db: string) => { + return MainModel(db, "lines", LineSchema, "lines"); +}; +export default lineModel; diff --git a/src/shared/V1Models/Builder/wallItemsModel.ts b/src/shared/V1Models/Builder/wallItemsModel.ts new file mode 100644 index 0000000..acda930 --- /dev/null +++ b/src/shared/V1Models/Builder/wallItemsModel.ts @@ -0,0 +1,37 @@ +import { Document, 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"; +export interface WallItems extends Document { + userId: User["_id"]; + projectId: Project["_id"]; + versionId: Version["_id"]; + modelUuid: string; + modelName: string; + type: string; + csgposition: []; + csgscale: []; + position: []; + quaternion: []; + scale: []; +} + +const wallItemsSchema: Schema = new Schema({ + userId: { type: Schema.Types.ObjectId, ref: "User" }, + projectId: { type: Schema.Types.ObjectId, ref: "Project" }, + versionId: { type: Schema.Types.ObjectId, ref: "Version" }, + modelUuid: { type: String, unique: true }, + modelName: { type: String }, + type: { type: String }, + csgposition: { type: Array }, + csgscale: { type: Array }, + position: { type: Array }, + quaternion: { type: Array }, + scale: { type: Array }, +}); + +const wallItemModel = (db: string) => { + return MainModel(db, "wallitems", wallItemsSchema, "wallitems"); +}; +export default wallItemModel; diff --git a/src/shared/V1Models/Builder/zoneModel.ts b/src/shared/V1Models/Builder/zoneModel.ts new file mode 100644 index 0000000..a6457c2 --- /dev/null +++ b/src/shared/V1Models/Builder/zoneModel.ts @@ -0,0 +1,50 @@ +import { Schema, Document } 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"; +export interface Zone extends Document { + zoneName: string; + zoneId: string; + zonePoints: []; + viewPortCenter: []; + viewPortposition: []; + isArchive: boolean; + panelOrder: string[]; + lockedPanel: string[]; + createdBy: User["_id"]; + projectId: Project["_id"]; + versionId: Version["_id"]; + layer: number; +} +const zoneSchema: Schema = new Schema( + { + zoneName: { type: String }, + zoneId: { type: String }, + createdBy: { type: Schema.Types.ObjectId, ref: "User" }, + projectId: { type: Schema.Types.ObjectId, ref: "Project" }, + versionId: { type: Schema.Types.ObjectId, ref: "Version" }, + layer: { type: Number }, + points: { type: Array }, + isArchive: { type: Boolean, default: false }, + panelOrder: { + type: [String], + enum: ["left", "right", "top", "bottom"], + }, + viewPortCenter: { type: Array, required: true }, + viewPortposition: { type: Array, required: true }, + lockedPanel: { + type: [String], + default: [], + enum: ["left", "right", "top", "bottom"], + }, + // createdBy: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, + // sceneID: { type: mongoose.Schema.Types.ObjectId, ref: "Scene" }, + }, + { timestamps: true } +); + +const zoneModel = (db: any) => { + return MainModel(db, "zones", zoneSchema, "zones"); +}; +export default zoneModel; diff --git a/src/shared/V1Models/Environment/environments-Model.ts b/src/shared/V1Models/Environment/environments-Model.ts new file mode 100644 index 0000000..59e7383 --- /dev/null +++ b/src/shared/V1Models/Environment/environments-Model.ts @@ -0,0 +1,25 @@ +import { Document, Schema } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +import { User } from "../Auth/userAuthModel.ts"; +export interface Environment extends Document { + userId: User["_id"]; + roofVisibility: boolean; + wallVisibility: boolean; + renderDistance: number; + shadowVisibility: boolean; + limitDistance: boolean; +} + +const environmentSchema: Schema = new Schema({ + userId: { type: Schema.Types.ObjectId, ref: "User", unique: true }, + roofVisibility: { type: Boolean, default: false }, + wallVisibility: { type: Boolean, default: false }, + shadowVisibility: { type: Boolean, default: false }, + renderDistance: { type: Number, default: 40 }, + limitDistance: { type: Boolean, default: true }, +}); + +const environmentModel = (db: string) => { + return MainModel(db, "Environment", environmentSchema, "Environment"); +}; +export default environmentModel; diff --git a/src/shared/V1Models/Project/project-model.ts b/src/shared/V1Models/Project/project-model.ts new file mode 100644 index 0000000..0f996dc --- /dev/null +++ b/src/shared/V1Models/Project/project-model.ts @@ -0,0 +1,39 @@ +import { Schema, Document } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +import { User } from "../Auth/userAuthModel.ts"; + +export interface Project extends Document { + projectUuid: string; + 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 }, + 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 } +); + +const projectModel = (db: string) => { + return MainModel(db, "Projects", projectSchema, "Projects"); +}; + +export default projectModel; diff --git a/src/shared/V1Models/Simulation/eventsDataModel.ts b/src/shared/V1Models/Simulation/eventsDataModel.ts new file mode 100644 index 0000000..a331e83 --- /dev/null +++ b/src/shared/V1Models/Simulation/eventsDataModel.ts @@ -0,0 +1,182 @@ +// models/Product.ts +import { Schema, Document } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; + +interface AssetEventSchema { + modelUuid: string; + modelName: string; + position: [number, number, number]; + rotation: [number, number, number]; + state: "idle" | "running" | "stopped" | "disabled" | "error"; +} + +interface TriggerSchema { + triggerUuid: string; + triggerName: string; + triggerType: "onComplete" | "onStart" | "onStop" | "delay" | "onError"; + delay: number; + triggeredAsset: { + triggeredModel: { modelName: string; modelUuid: string }; + triggeredPoint: { pointName: string; pointUuid: string }; + triggeredAction: { actionName: string; actionUuid: string }; + } | null; +} + +interface ConveyorPointSchema { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + action: { + actionUuid: string; + actionName: string; + actionType: "default" | "spawn" | "swap" | "despawn"; + material: string; + delay: number | "inherit"; + spawnInterval: number | "inherit"; + spawnCount: number | "inherit"; + triggers: TriggerSchema[]; + }; +} + +interface VehiclePointSchema { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + action: { + actionUuid: string; + actionName: string; + actionType: "travel"; + material: string | null; + unLoadDuration: number; + loadCapacity: number; + pickUpPoint: { x: number; y: number; z: number } | null; + unLoadPoint: { x: number; y: number; z: number } | null; + triggers: TriggerSchema[]; + }; +} + +interface RoboticArmPointSchema { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + actions: { + actionUuid: string; + actionName: string; + actionType: "pickAndPlace"; + process: { + startPoint: [number, number, number]; + endPoint: [number, number, number]; + }; + triggers: TriggerSchema[]; + }[]; +} + +interface MachinePointSchema { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + action: { + actionUuid: string; + actionName: string; + actionType: "process"; + processTime: number; + swapMaterial: string; + triggers: TriggerSchema[]; + }; +} + +interface StoragePointSchema { + uuid: string; + position: [number, number, number]; + rotation: [number, number, number]; + action: { + actionUuid: string; + actionName: string; + actionType: "storage"; + materials: { materialName: string; materialId: string }[]; + storageCapacity: number; + }; +} + +interface ConveyorEventSchema extends AssetEventSchema { + type: "transfer"; + speed: number; + points: ConveyorPointSchema[]; +} + +interface VehicleEventSchema extends AssetEventSchema { + type: "vehicle"; + speed: number; + point: VehiclePointSchema; +} + +interface RoboticArmEventSchema extends AssetEventSchema { + type: "roboticArm"; + speed: number; + point: RoboticArmPointSchema; +} + +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; + isArchive: boolean; + type: "transfer" | "vehicle" | "roboticArm" | "machine" | "storageUnit"; + speed: number; + point: + | VehicleEventSchema + | RoboticArmEventSchema + | MachineEventSchema + | StorageEventSchema; + points: ConveyorEventSchema[]; +} +// type EventsSchema = ConveyorEventSchema | VehicleEventSchema | RoboticArmEventSchema | MachineEventSchema | StorageEventSchema; + +const BaseEventSchema = new Schema( + { + modelUuid: { type: String, required: true }, + modelName: { type: String, required: true }, + position: { type: [Number], required: true }, + rotation: { type: [Number], required: true }, + speed: { type: Number }, + state: { + type: String, + enum: ["idle", "running", "stopped", "disabled", "error"], + default: "idle", + }, + type: { + type: String, + required: true, + enum: ["transfer", "vehicle", "roboticArm", "machine", "storageUnit"], + }, + point: { + type: Schema.Types.Mixed, + }, + points: { + type: Schema.Types.Mixed, + }, + productId: { type: String, required: true }, + isArchive: { type: Boolean, default: false }, + }, + { discriminatorKey: "type", timestamps: true } +); + +const EventsDataModel = (db: string) => { + return MainModel(db, "EventDatas", BaseEventSchema, "EventDatas"); +}; + +export default EventsDataModel; diff --git a/src/shared/V1Models/Simulation/productModel.ts b/src/shared/V1Models/Simulation/productModel.ts new file mode 100644 index 0000000..4daf732 --- /dev/null +++ b/src/shared/V1Models/Simulation/productModel.ts @@ -0,0 +1,26 @@ +import { Schema, Document } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +import { Project } from "../Project/project-model.ts"; +import { Version } from "../Version/versionModel.ts"; +export interface Product extends Document { + productName: string; + productId: string; + projectId: Project["_id"]; + versionId: Version["_id"]; + eventsData: []; + isArchive: boolean; +} + +const ProductSchema = new Schema({ + projectId: { type: Schema.Types.ObjectId, ref: "Project" }, + versionId: { type: Schema.Types.ObjectId, ref: "Version" }, + productName: { type: String, required: true }, + productId: { type: String, required: true }, + isArchive: { type: Boolean, default: false }, +}); + +const ProductModel = (db: string) => { + return MainModel(db, "Product", ProductSchema, "Product"); +}; + +export default ProductModel; diff --git a/src/shared/V1Models/Version/versionModel.ts b/src/shared/V1Models/Version/versionModel.ts new file mode 100644 index 0000000..920174c --- /dev/null +++ b/src/shared/V1Models/Version/versionModel.ts @@ -0,0 +1,27 @@ +import { Schema, Document } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +import { Project } from "../Project/project-model.ts"; +import { User } from "../Auth/userAuthModel.ts"; +export interface Version extends Document { + versionName: string; + projectId: Project["_id"]; + createdBy: User["_id"]; + isArchive: boolean; + version: number; +} +const versionSchema: Schema = new Schema( + { + versionName: { type: String }, + version: { type: Number }, + isArchive: { type: Boolean, default: false }, + projectId: { type: Schema.Types.ObjectId, ref: "project" }, + createdBy: { type: Schema.Types.ObjectId, ref: "user" }, + }, + { timestamps: true } +); + +const versionModel = (db: string) => { + return MainModel(db, "Versions", versionSchema, "Versions"); +}; + +export default versionModel; diff --git a/src/shared/V1Models/Vizualization/3dwidget.ts b/src/shared/V1Models/Vizualization/3dwidget.ts new file mode 100644 index 0000000..25de605 --- /dev/null +++ b/src/shared/V1Models/Vizualization/3dwidget.ts @@ -0,0 +1,37 @@ +import { Schema, Document, model } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +import { Zone } from "../Builder/zoneModel.ts"; +export interface Widget3d extends Document { + type: string; + widgetID: string; + widgetName: string; + position: []; + rotation: []; + isArchive: boolean; + zoneId: Zone["_id"]; + Data: { + measurements: {}; + duration: string; + }; +} +const Widget3dSchema: Schema = new Schema( + { + type: { type: String }, + widgetID: { type: String }, + widgetName: { type: String, default: "Widget3D" }, + position: { type: Array }, + rotation: { type: Array }, + zoneId: { type: Schema.Types.ObjectId, ref: "Zone" }, + Data: { + measurements: { type: Object, default: {} }, + duration: { type: String, default: "1h" }, + }, + isArchive: { type: Boolean, default: false }, + }, + { timestamps: true } +); + +const widget3dModel = (db: any) => { + return MainModel(db, "3dWidget", Widget3dSchema, "3dWidget"); +}; +export default widget3dModel; diff --git a/src/shared/V1Models/Vizualization/floatWidget.ts b/src/shared/V1Models/Vizualization/floatWidget.ts new file mode 100644 index 0000000..4973291 --- /dev/null +++ b/src/shared/V1Models/Vizualization/floatWidget.ts @@ -0,0 +1,46 @@ +import { Schema, Document, model } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +import { Zone } from "../Builder/zoneModel.ts"; +export interface FloatingWidget extends Document { + className: string; + iconName: string; + header: string; + floatWidgetID: string; + position: {}; + per: string; + value: string; + isArchive: boolean; + zoneId: Zone["_id"]; + Data: { + measurements: {}; + duration: string; + }; +} +const floatingWidgetSchema: Schema = new Schema( + { + className: { type: String }, + iconName: { type: String }, + header: { type: String }, + floatWidgetID: { type: String }, + position: { type: Object }, + per: { type: String }, + value: { type: String }, + zoneId: { type: Schema.Types.ObjectId, ref: "Zone" }, + Data: { + measurements: { type: Object, default: {} }, + duration: { type: String, default: "1h" }, + }, + isArchive: { type: Boolean, default: false }, + }, + { timestamps: true } +); + +const floatWidgetModel = (db: any) => { + return MainModel( + db, + "FloatingWidget", + floatingWidgetSchema, + "FloatingWidget" + ); +}; +export default floatWidgetModel; diff --git a/src/shared/V1Models/Vizualization/panelmodel.ts b/src/shared/V1Models/Vizualization/panelmodel.ts new file mode 100644 index 0000000..259cd94 --- /dev/null +++ b/src/shared/V1Models/Vizualization/panelmodel.ts @@ -0,0 +1,23 @@ +import mongoose, { Schema, Document } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +import { Zone } from "../Builder/zoneModel.ts"; +export interface Panel extends Document { + zoneId: Zone["_id"]; + panelName: string; + widgets: [mongoose.Types.ObjectId]; + isArchive: boolean; +} +const panelSchema: Schema = new Schema( + { + zoneId: { type: Schema.Types.ObjectId, ref: "Zone" }, + panelName: { type: String }, + widgets: [{ type: mongoose.Schema.Types.ObjectId, ref: "Widget" }], + isArchive: { type: Boolean, default: false }, + }, + { timestamps: true } +); + +const panelModel = (db: any) => { + return MainModel(db, "Panel", panelSchema, "Panel"); +}; +export default panelModel; diff --git a/src/shared/V1Models/Vizualization/templatemodel.ts b/src/shared/V1Models/Vizualization/templatemodel.ts new file mode 100644 index 0000000..71848fe --- /dev/null +++ b/src/shared/V1Models/Vizualization/templatemodel.ts @@ -0,0 +1,39 @@ +import { Schema, Document } 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"; +export interface Template extends Document { + userId: User["_id"]; + projectId: Project["_id"]; + versionId: Version["_id"]; + templateName: string; + templateID: string; + snapshot: string; + panelOrder: []; + widgets: []; + floatWidgets: []; + Widgets3D: []; + isArchive: boolean; +} +const templateSchema: Schema = new Schema( + { + userId: { type: Schema.Types.ObjectId, ref: "User" }, + projectId: { type: Schema.Types.ObjectId, ref: "Project" }, + versionId: { type: Schema.Types.ObjectId, ref: "Version" }, + templateName: { type: String }, + templateID: { type: String }, + snapshot: { type: String }, + panelOrder: { type: Array }, + widgets: { type: Array }, + floatWidgets: { type: Array }, + Widgets3D: { type: Array }, + isArchive: { type: Boolean, default: false }, + }, + { timestamps: true } +); + +const templateModel = (db: any) => { + return MainModel(db, "Template", templateSchema, "Template"); +}; +export default templateModel; diff --git a/src/shared/V1Models/Vizualization/widgemodel.ts b/src/shared/V1Models/Vizualization/widgemodel.ts new file mode 100644 index 0000000..ccc7821 --- /dev/null +++ b/src/shared/V1Models/Vizualization/widgemodel.ts @@ -0,0 +1,47 @@ +import mongoose, { Schema, Document } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; +import { Zone } from "../Builder/zoneModel.ts"; +export interface widget extends Document { + widgetName: string; + widgetside: string; + widgetID: string; + widgetOrder: string; + elementType: string; + elementColor: string; + fontFamily: string; + fontStyle: string; + fontWeight: string; + isArchive: boolean; + panelID: mongoose.Types.ObjectId; + Data: { + measurements: {}; + duration: string; + }; + zoneId: Zone["_id"]; +} +const widgetSchema: Schema = new Schema( + { + widgetName: { type: String, default: "Widget" }, + widgetside: { type: String }, + widgetID: { type: String }, + widgetOrder: { type: String }, + elementType: { type: String }, + elementColor: { type: String }, + fontFamily: { type: String }, + fontStyle: { type: String }, + Data: { + measurements: { type: Object, default: {} }, + duration: { type: String, default: "1h" }, + }, + fontWeight: { type: String }, + isArchive: { type: Boolean, default: false }, + panelID: { type: mongoose.Schema.Types.ObjectId, ref: "Panel" }, + zoneId: { type: Schema.Types.ObjectId, ref: "Zone" }, + }, + { timestamps: true } +); + +const widgetModel = (db: any) => { + return MainModel(db, "Widget", widgetSchema, "Widget"); +}; +export default widgetModel; From 2aa8c479fa8246d9cd724921cbd2a92fc150a0eb Mon Sep 17 00:00:00 2001 From: Nivetharamesh Date: Sat, 17 May 2025 11:29:43 +0530 Subject: [PATCH 3/6] zoneId modified to string in schema model bcz of zoneUUId --- src/shared/V1Models/Vizualization/3dwidget.ts | 4 ++-- src/shared/V1Models/Vizualization/floatWidget.ts | 4 ++-- src/shared/V1Models/Vizualization/panelmodel.ts | 4 ++-- src/shared/V1Models/Vizualization/widgemodel.ts | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/shared/V1Models/Vizualization/3dwidget.ts b/src/shared/V1Models/Vizualization/3dwidget.ts index 25de605..6e84c6d 100644 --- a/src/shared/V1Models/Vizualization/3dwidget.ts +++ b/src/shared/V1Models/Vizualization/3dwidget.ts @@ -8,7 +8,7 @@ export interface Widget3d extends Document { position: []; rotation: []; isArchive: boolean; - zoneId: Zone["_id"]; + zoneId: string; Data: { measurements: {}; duration: string; @@ -21,7 +21,7 @@ const Widget3dSchema: Schema = new Schema( widgetName: { type: String, default: "Widget3D" }, position: { type: Array }, rotation: { type: Array }, - zoneId: { type: Schema.Types.ObjectId, ref: "Zone" }, + zoneId: { type: String }, Data: { measurements: { type: Object, default: {} }, duration: { type: String, default: "1h" }, diff --git a/src/shared/V1Models/Vizualization/floatWidget.ts b/src/shared/V1Models/Vizualization/floatWidget.ts index 4973291..cb2712a 100644 --- a/src/shared/V1Models/Vizualization/floatWidget.ts +++ b/src/shared/V1Models/Vizualization/floatWidget.ts @@ -10,7 +10,7 @@ export interface FloatingWidget extends Document { per: string; value: string; isArchive: boolean; - zoneId: Zone["_id"]; + zoneId: string; Data: { measurements: {}; duration: string; @@ -25,7 +25,7 @@ const floatingWidgetSchema: Schema = new Schema( position: { type: Object }, per: { type: String }, value: { type: String }, - zoneId: { type: Schema.Types.ObjectId, ref: "Zone" }, + zoneId: { type: String }, Data: { measurements: { type: Object, default: {} }, duration: { type: String, default: "1h" }, diff --git a/src/shared/V1Models/Vizualization/panelmodel.ts b/src/shared/V1Models/Vizualization/panelmodel.ts index 259cd94..78ab7ea 100644 --- a/src/shared/V1Models/Vizualization/panelmodel.ts +++ b/src/shared/V1Models/Vizualization/panelmodel.ts @@ -2,14 +2,14 @@ import mongoose, { Schema, Document } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; import { Zone } from "../Builder/zoneModel.ts"; export interface Panel extends Document { - zoneId: Zone["_id"]; + zoneId: string; panelName: string; widgets: [mongoose.Types.ObjectId]; isArchive: boolean; } const panelSchema: Schema = new Schema( { - zoneId: { type: Schema.Types.ObjectId, ref: "Zone" }, + zoneId: { type: String }, panelName: { type: String }, widgets: [{ type: mongoose.Schema.Types.ObjectId, ref: "Widget" }], isArchive: { type: Boolean, default: false }, diff --git a/src/shared/V1Models/Vizualization/widgemodel.ts b/src/shared/V1Models/Vizualization/widgemodel.ts index ccc7821..cfe5e11 100644 --- a/src/shared/V1Models/Vizualization/widgemodel.ts +++ b/src/shared/V1Models/Vizualization/widgemodel.ts @@ -17,7 +17,7 @@ export interface widget extends Document { measurements: {}; duration: string; }; - zoneId: Zone["_id"]; + 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: Schema.Types.ObjectId, ref: "Zone" }, + zoneId: { type: String }, }, { timestamps: true } ); From ac8de5d33d0a3dff6ceabe79991fcd78e02818f0 Mon Sep 17 00:00:00 2001 From: Nivetharamesh Date: Mon, 19 May 2025 16:06:09 +0530 Subject: [PATCH 4/6] Role nd token Based Routing completed for Project,trash,home which is in Controller. Token, Auth Purpose,Rolebased middlewares created. Auth API,Project token Based API, Home Token Based API, Trash Token Based API In v1 AuthRoutes --- .env | 12 + package-lock.json | 119 +++++ package.json | 3 + .../authController/authControllers.ts | 245 +++++++++ .../versionController/versioncontroller.ts | 31 ++ src/api-server/V1/v1Routes/authRoutes.ts | 83 ++++ src/api-server/app.ts | 8 +- .../controller/home/homeControllers.ts | 9 +- .../controller/project/projectController.ts | 78 ++- .../controller/trash/trashcontrollers.ts | 26 +- src/api-server/controller/user-Controller.ts | 2 +- src/shared/V1Models/Auth/tokenModel.ts | 4 +- src/shared/V1Models/Auth/user.ts | 31 +- src/shared/V1Models/Auth/userAuthModel.ts | 16 +- src/shared/V1Models/Project/share-model.ts | 52 ++ src/shared/middleware/rbacMiddleware.ts | 13 + src/shared/redis/redis.ts | 21 + src/shared/security/token.ts | 38 -- src/shared/services/auth/authServices.ts | 466 ++++++++++++++++++ src/shared/services/builder/cameraService.ts | 155 ++++++ .../services/helpers/ProjecthelperFn.ts | 15 +- src/shared/services/home/homeService.ts | 42 +- .../services/project/project-Services.ts | 85 ++-- src/shared/services/trash/trashService.ts | 33 +- src/shared/services/version/versionService.ts | 127 +++++ src/shared/{security => utils}/Hasing.ts | 49 +- .../{security => utils}/mongosecurity.ts | 66 +-- src/shared/utils/token.ts | 143 ++++++ 28 files changed, 1748 insertions(+), 224 deletions(-) create mode 100644 src/api-server/V1/v1Controllers/authController/authControllers.ts create mode 100644 src/api-server/V1/v1Controllers/versionController/versioncontroller.ts create mode 100644 src/api-server/V1/v1Routes/authRoutes.ts create mode 100644 src/shared/V1Models/Project/share-model.ts create mode 100644 src/shared/middleware/rbacMiddleware.ts create mode 100644 src/shared/redis/redis.ts delete mode 100644 src/shared/security/token.ts create mode 100644 src/shared/services/auth/authServices.ts create mode 100644 src/shared/services/builder/cameraService.ts create mode 100644 src/shared/services/version/versionService.ts rename src/shared/{security => utils}/Hasing.ts (62%) rename src/shared/{security => utils}/mongosecurity.ts (97%) create mode 100644 src/shared/utils/token.ts diff --git a/.env b/.env index f7cfbd6..122147a 100644 --- a/.env +++ b/.env @@ -18,3 +18,15 @@ MinIO_URL=185.100.212.76 MinIO_PORT=9999 MinIO_accessKey=sabarinathan MinIO_secretKey=sabarinathan + + +# token +JWT_SECRET="DwinzoProject" +REFRESH_JWT_SECRET="RefreshDwinzoProject" + +# redis +REDIS_ENV= true +REDIS_LOCAL =127.0.0.1 +REDIS_PORT=6379 +# REDIS_DOCKER =185.100.212.76 +# REDIS_PORT=6666 \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index fb2e2c2..bc6d21c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,11 +14,13 @@ "express": "^4.21.1", "fs": "^0.0.1-security", "http": "^0.0.1-security", + "ioredis": "^5.6.1", "ip": "^2.0.1", "jsonwebtoken": "^9.0.2", "minio": "^8.0.5", "mongoose": "^8.8.1", "multer": "^1.4.5-lts.2", + "nodemailer": "^7.0.3", "socket.io": "^4.8.1", "swagger-autogen": "^2.23.7", "swagger-ui-express": "^5.0.1" @@ -32,6 +34,7 @@ "@types/mime-types": "^2.1.4", "@types/multer": "^1.4.12", "@types/node": "^22.9.0", + "@types/nodemailer": "^6.4.17", "@types/swagger-ui-express": "^4.1.7", "nodemon": "^3.1.7", "ts-node": "^10.9.2", @@ -50,6 +53,11 @@ "node": ">=12" } }, + "node_modules/@ioredis/commands": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@ioredis/commands/-/commands-1.2.0.tgz", + "integrity": "sha512-Sx1pU8EM64o2BrqNpEO1CNLtKQwyhuXuqyfH7oGKCk+1a33d2r5saW8zNwm3j6BTExtjrv2BxTgzzkMwts6vGg==" + }, "node_modules/@jridgewell/resolve-uri": { "version": "3.1.2", "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", @@ -239,6 +247,15 @@ "undici-types": "~6.20.0" } }, + "node_modules/@types/nodemailer": { + "version": "6.4.17", + "resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-6.4.17.tgz", + "integrity": "sha512-I9CCaIp6DTldEg7vyUTZi8+9Vo0hi1/T8gv3C89yk1rSAAzoKQ8H8ki/jBYJSFoH/BisgLP8tkZMlQ91CIquww==", + "dev": true, + "dependencies": { + "@types/node": "*" + } + }, "node_modules/@types/qs": { "version": "6.9.18", "resolved": "https://registry.npmjs.org/@types/qs/-/qs-6.9.18.tgz", @@ -589,6 +606,14 @@ "fsevents": "~2.3.2" } }, + "node_modules/cluster-key-slot": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", + "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/concat-map": { "version": "0.0.1", "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", @@ -730,6 +755,14 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/denque": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz", + "integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==", + "engines": { + "node": ">=0.10" + } + }, "node_modules/depd": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", @@ -1235,6 +1268,50 @@ "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" }, + "node_modules/ioredis": { + "version": "5.6.1", + "resolved": "https://registry.npmjs.org/ioredis/-/ioredis-5.6.1.tgz", + "integrity": "sha512-UxC0Yv1Y4WRJiGQxQkP0hfdL0/5/6YvdfOOClRgJ0qppSarkhneSa6UvkMkms0AkdGimSH3Ikqm+6mkMmX7vGA==", + "dependencies": { + "@ioredis/commands": "^1.1.1", + "cluster-key-slot": "^1.1.0", + "debug": "^4.3.4", + "denque": "^2.1.0", + "lodash.defaults": "^4.2.0", + "lodash.isarguments": "^3.1.0", + "redis-errors": "^1.2.0", + "redis-parser": "^3.0.0", + "standard-as-callback": "^2.1.0" + }, + "engines": { + "node": ">=12.22.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/ioredis" + } + }, + "node_modules/ioredis/node_modules/debug": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz", + "integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/ioredis/node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, "node_modules/ip": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/ip/-/ip-2.0.1.tgz", @@ -1438,11 +1515,21 @@ "resolved": "https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz", "integrity": "sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==" }, + "node_modules/lodash.defaults": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/lodash.defaults/-/lodash.defaults-4.2.0.tgz", + "integrity": "sha512-qjxPLHd3r5DnsdGacqOMU6pb/avJzdh9tFX2ymgoZE27BmjXrNy/y4LoaiTeAb+O3gL8AfpJGtqfX/ae2leYYQ==" + }, "node_modules/lodash.includes": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/lodash.includes/-/lodash.includes-4.3.0.tgz", "integrity": "sha512-W3Bx6mdkRTGtlJISOvVD/lbqjTlPPUDTMnlXZFnVwi9NKJ6tiAk6LVdlhZMm17VZisqhKcgzpO5Wz91PCt5b0w==" }, + "node_modules/lodash.isarguments": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/lodash.isarguments/-/lodash.isarguments-3.1.0.tgz", + "integrity": "sha512-chi4NHZlZqZD18a0imDHnZPrDeBbTtVN7GXMwuGdRH9qotxAjYs3aVLKc7zNOG9eddR5Ksd8rvFEBc9SsggPpg==" + }, "node_modules/lodash.isboolean": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/lodash.isboolean/-/lodash.isboolean-3.0.3.tgz", @@ -1758,6 +1845,14 @@ "node": ">= 0.6" } }, + "node_modules/nodemailer": { + "version": "7.0.3", + "resolved": "https://registry.npmjs.org/nodemailer/-/nodemailer-7.0.3.tgz", + "integrity": "sha512-Ajq6Sz1x7cIK3pN6KesGTah+1gnwMnx5gKl3piQlQQE/PwyJ4Mbc8is2psWYxK3RJTVeqsDaCv8ZzXLCDHMTZw==", + "engines": { + "node": ">=6.0.0" + } + }, "node_modules/nodemon": { "version": "3.1.9", "resolved": "https://registry.npmjs.org/nodemon/-/nodemon-3.1.9.tgz", @@ -2006,6 +2101,25 @@ "node": ">=8.10.0" } }, + "node_modules/redis-errors": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/redis-errors/-/redis-errors-1.2.0.tgz", + "integrity": "sha512-1qny3OExCf0UvUV/5wpYKf2YwPcOqXzkwKKSmKHiE6ZMQs5heeE/c8eXK+PNllPvmjgAbfnsbpkGZWy8cBpn9w==", + "engines": { + "node": ">=4" + } + }, + "node_modules/redis-parser": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/redis-parser/-/redis-parser-3.0.0.tgz", + "integrity": "sha512-DJnGAeenTdpMEH6uAJRK/uiyEIH9WVsUmoLwzudwGJUwZPp80PDBWPHXSAGNPwNvIXAbe7MSUB1zQFugFml66A==", + "dependencies": { + "redis-errors": "^1.0.0" + }, + "engines": { + "node": ">=4" + } + }, "node_modules/safe-buffer": { "version": "5.2.1", "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", @@ -2335,6 +2449,11 @@ "node": ">=6" } }, + "node_modules/standard-as-callback": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/standard-as-callback/-/standard-as-callback-2.1.0.tgz", + "integrity": "sha512-qoRRSyROncaz1z0mvYqIE4lCd9p2R90i6GxW3uZv5ucSu8tU7B5HXUP1gG8pVZsYNVaXjk8ClXHPttLyxAL48A==" + }, "node_modules/statuses": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", diff --git a/package.json b/package.json index b39f925..29bba9f 100644 --- a/package.json +++ b/package.json @@ -18,11 +18,13 @@ "express": "^4.21.1", "fs": "^0.0.1-security", "http": "^0.0.1-security", + "ioredis": "^5.6.1", "ip": "^2.0.1", "jsonwebtoken": "^9.0.2", "minio": "^8.0.5", "mongoose": "^8.8.1", "multer": "^1.4.5-lts.2", + "nodemailer": "^7.0.3", "socket.io": "^4.8.1", "swagger-autogen": "^2.23.7", "swagger-ui-express": "^5.0.1" @@ -36,6 +38,7 @@ "@types/mime-types": "^2.1.4", "@types/multer": "^1.4.12", "@types/node": "^22.9.0", + "@types/nodemailer": "^6.4.17", "@types/swagger-ui-express": "^4.1.7", "nodemon": "^3.1.7", "ts-node": "^10.9.2", diff --git a/src/api-server/V1/v1Controllers/authController/authControllers.ts b/src/api-server/V1/v1Controllers/authController/authControllers.ts new file mode 100644 index 0000000..710b4d4 --- /dev/null +++ b/src/api-server/V1/v1Controllers/authController/authControllers.ts @@ -0,0 +1,245 @@ +import { Request, Response } from "express"; +import { + AuthLogin, + AuthLogout, + AuthSignup, + forgetPassword, +} from "../../../../shared/services/auth/authServices.ts"; + +export const SignupController = async ( + req: Request, + res: Response +): Promise => { + try { + console.log("req.body: ", req.body); + const { userName, Email, Password, profilePicture } = req.body; + if (!userName || !Email || !Password) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await AuthSignup(req.body); + + switch (result.status) { + case "User already exists": + res.status(403).json({ + message: "User already exists", + }); + break; + + case "Success": + res.status(201).json({ + message: "New User created", + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "An unexpected error occurred", + }); + return; + } +}; +export const SignInController = async ( + req: Request, + res: Response +): Promise => { + try { + const { Email, Password, fingerprint } = req.body; + if (!fingerprint || !Email || !Password) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await AuthLogin(req.body); + + switch (result.status) { + case "User Not Found!!! Kindly signup...": + res.status(404).json({ + message: "User Not Found!!! Kindly signup...", + }); + break; + case "Email & Password is invalid...Check the credentials": + res.status(400).json({ + message: "Email & Password is invalid...Check the credentials", + }); + break; + case "Already LoggedIn on another browser....Please logout!!!": + res.status(403).json({ + message: "Already LoggedIn on another browser....Please logout!!!", + }); + break; + + case "User_Datas not found": + res.status(404).json({ + message: "User_Datas not found", + }); + break; + case "User update failed.": + res.status(400).json({ + message: "User update failed.", + }); + break; + case "Success": + res.status(200).json({ + message: result.data, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "An unexpected error occurred", + }); + return; + } +}; +export const SignOutController = async ( + req: Request, + res: Response +): Promise => { + try { + const { Email } = req.body; + if (!Email) { + res.status(400).json({ + message: "Email field is Mandatory", + }); + return; + } + const result = await AuthLogout(req.body); + + switch (result.status) { + case "User not found": + res.status(404).json({ + message: "User not found", + }); + break; + case "Token not found": + res.status(404).json({ + message: "Token not found", + }); + break; + case "Success": + res.status(200).json({ + message: "Logout Successfull", + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "An unexpected error occurred", + }); + return; + } +}; +export const ForgetPasswordController = async ( + req: Request, + res: Response +): Promise => { + try { + const { Email } = req.body; + if (!Email) { + res.status(400).json({ + message: "Email field is Mandatory", + }); + return; + } + const result = await forgetPassword(req.body); + switch (result.status) { + case "You can only reset your password once every 24 hours.": + res.status(400).json({ + message: "You can only reset your password once every 24 hours.", + }); + break; + case "Email not found": + res.status(404).json({ + message: "Email not found", + }); + break; + case "Success": + res.status(200).json({ + message: "Password reset link sent successfully", + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "An unexpected error occurred", + }); + return; + } +}; +export const ResetPasswordController = async ( + req: Request, + res: Response +): Promise => { + try { + const { newPassword, resetToken, confirmPassword } = req.body; + if (!newPassword || !resetToken || !confirmPassword) { + res.status(400).json({ + message: "All fields are Mandatory", + }); + return; + } + const result = await forgetPassword(req.body); + + switch (result.status) { + case "Invalid token payload.": + res.status(400).json({ + message: "Invalid token payload.", + }); + break; + case "Password mismatch": + res.status(400).json({ + message: "Password mismatch", + }); + break; + case "User not found": + res.status(404).json({ + message: "User not found", + }); + break; + case "Token is invalid or expired.": + res.status(404).json({ + message: "Token is invalid or expired.", + }); + break; + case "Success": + res.status(200).json({ + message: "Password reset successfull!!", + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "An unexpected error occurred", + }); + return; + } +}; diff --git a/src/api-server/V1/v1Controllers/versionController/versioncontroller.ts b/src/api-server/V1/v1Controllers/versionController/versioncontroller.ts new file mode 100644 index 0000000..7200793 --- /dev/null +++ b/src/api-server/V1/v1Controllers/versionController/versioncontroller.ts @@ -0,0 +1,31 @@ +import { Request, Response } from "express"; +import versionService from "../../../../shared/services/version/versionService.ts"; + +export const versioncontroller = async ( + req: Request, + res: Response +): Promise => { + 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, + userId, + description + ); + + console.log(result); + } catch (error) { + res.status(500).json({ + message: "An unexpected error occurred", + }); + return; + } +}; diff --git a/src/api-server/V1/v1Routes/authRoutes.ts b/src/api-server/V1/v1Routes/authRoutes.ts new file mode 100644 index 0000000..34e5528 --- /dev/null +++ b/src/api-server/V1/v1Routes/authRoutes.ts @@ -0,0 +1,83 @@ +import express from "express"; +import { + ForgetPasswordController, + ResetPasswordController, + SignInController, + SignOutController, + SignupController, +} from "../v1Controllers/authController/authControllers.ts"; +import { versioncontroller } from "../v1Controllers/versionController/versioncontroller.ts"; +import { + createProjectController, + GetProjects, + RemoveProject, + updateProjectController, + ViewData, +} from "../../controller/project/projectController.ts"; +import { tokenValidator } from "../../../shared/utils/token.ts"; +import authorizedRoles from "../../../shared/middleware/rbacMiddleware.ts"; +import { recentDataController } from "../../controller/home/homeControllers.ts"; +import { + GetTrashList, + RestoreTrash, +} from "../../controller/trash/trashcontrollers.ts"; + +const Authrouter = express.Router(); +Authrouter.post("/Auth/signup", SignupController); +Authrouter.post("/Auth/login", SignInController); +Authrouter.post("/Auth/logout", SignOutController); +Authrouter.post("/Auth/forgetPassword", ForgetPasswordController); +Authrouter.post("/Auth/reset-password/:resetToken", ResetPasswordController); +Authrouter.post("/Auth/versionData", versioncontroller); + +// project +Authrouter.post("/Auth/upsertProject", tokenValidator, createProjectController); +Authrouter.get( + "/Auth/Projects", + tokenValidator, + authorizedRoles("Admin", "User"), + GetProjects +); +Authrouter.patch( + "/Auth/Project/archive/:projectId", + tokenValidator, + authorizedRoles("Admin", "User"), + RemoveProject +); + +Authrouter.patch( + "/Auth/Project/modify", + tokenValidator, + authorizedRoles("Admin", "User"), + updateProjectController +); +Authrouter.get( + "/Auth/Project/view", + tokenValidator, + authorizedRoles("Admin", "User"), + ViewData +); + +//home-Page +Authrouter.get( + "/Auth/RecentlyViewed", + tokenValidator, + authorizedRoles("Admin", "User"), + recentDataController +); + +//trash +Authrouter.get( + "/Auth/Trash/Lists", + tokenValidator, + authorizedRoles("Admin", "User"), + GetTrashList +); + +Authrouter.patch( + "/Auth/restore", + tokenValidator, + authorizedRoles("Admin", "User"), + RestoreTrash +); +export default Authrouter; diff --git a/src/api-server/app.ts b/src/api-server/app.ts index a4e996e..a3a8ae3 100644 --- a/src/api-server/app.ts +++ b/src/api-server/app.ts @@ -20,8 +20,10 @@ import productRouter from "./Routes/productRoutes.ts"; import projectRouter from "./Routes/projectRoutes.ts"; import trashRouter from "./Routes/trashRoutes.ts"; import homePageRouter from "./Routes/homepageRoutes.ts"; +import redis from "../shared/redis/redis.ts"; +import Authrouter from "./V1/v1Routes/authRoutes.ts"; // import productFlowRoutes from "./Routes/productFlowRouts.ts"; - +redis; const app = express(); app.use(cors()); // const allowedOriginsDev = [ @@ -87,4 +89,8 @@ app.use("/api/v2", productRouter); app.use("/api/v1", projectRouter); app.use("/api/v1", trashRouter); app.use("/api/v1", homePageRouter); + +//New versions +app.use("/API/V1", Authrouter); + export default app; diff --git a/src/api-server/controller/home/homeControllers.ts b/src/api-server/controller/home/homeControllers.ts index a608482..9907c9e 100644 --- a/src/api-server/controller/home/homeControllers.ts +++ b/src/api-server/controller/home/homeControllers.ts @@ -1,19 +1,20 @@ import { Request, Response } from "express"; import { RecentlyAdded, searchProject, searchTrashProject } from "../../../shared/services/home/homeService.ts"; +import { AuthenticatedRequest } from "../../../shared/utils/token.ts"; export const recentDataController = async ( - req: Request, + req: AuthenticatedRequest, res: Response ): Promise => { try { - const { userId, organization } = req.params; - if (!userId || !organization) { + const { userId, organization,role } = req.user||{}; + if (!userId || !organization||!role) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await RecentlyAdded({ userId, organization }); + const result = await RecentlyAdded({ userId, organization,role }); switch (result.status) { case "User not found": diff --git a/src/api-server/controller/project/projectController.ts b/src/api-server/controller/project/projectController.ts index a061d11..c86a4ee 100644 --- a/src/api-server/controller/project/projectController.ts +++ b/src/api-server/controller/project/projectController.ts @@ -6,20 +6,27 @@ import { updateProject, viewProject, } from "../../../shared/services/project/project-Services.ts"; +import { AuthenticatedRequest } from "../../../shared/utils/token.ts"; export const createProjectController = async ( - req: Request, + req: AuthenticatedRequest, res: Response ): Promise => { try { - const { projectUuid, userId, thumbnail, organization } = req.body; - if (!projectUuid || !userId || !thumbnail || !organization) { + const { userId, organization } = req.user || {}; + console.log("req.user: ", req.user); + const { projectUuid, thumbnail } = req.body; + if (!req.user || !req.user.userId || !req.user.organization) { + res.status(401).json({ message: "Unauthorized" }); + return; + } + if (!projectUuid || !thumbnail) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await createProject(req.body); + const result = await createProject({ ...req.body, userId, organization }); switch (result.status) { case "project_exists": @@ -54,18 +61,19 @@ export const createProjectController = async ( } }; export const GetProjects = async ( - req: Request, + req: AuthenticatedRequest, res: Response ): Promise => { try { - const { userId, organization } = req.params; - if (!userId || !organization) { + const { userId, organization, role } = req.user || {}; + // const { userId, organization } = req.params; + if (!userId || !organization || !role) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await GetAllProjects({ userId, organization }); + const result = await GetAllProjects({ userId, organization, role }); switch (result?.status) { case "User not found": res.status(404).json({ @@ -92,19 +100,34 @@ export const GetProjects = async ( } }; export const RemoveProject = async ( - req: Request, + req: AuthenticatedRequest, res: Response ): Promise => { try { const { projectId } = req.params; - const { organization, userId } = req.body; - if (!projectId || !organization || !userId) { + // const { organization, userId } = req.body; + const { organization, userId, role } = req.user || {}; + if ( + !req.user || + !req.user.userId || + !req.user.organization || + !req.user.role + ) { + res.status(401).json({ message: "Unauthorized" }); + return; + } + if (!projectId || !organization || !userId || !role) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await DeleteProject({ projectId, organization, userId }); + const result = await DeleteProject({ + projectId, + organization, + userId, + role, + }); switch (result?.status) { case "Project not found": res.status(404).json({ @@ -135,13 +158,13 @@ export const RemoveProject = async ( } }; export const updateProjectController = async ( - req: Request, + req: AuthenticatedRequest, res: Response ): Promise => { try { - const { projectId, organization, projectName, thumbnail, userId } = - req.body; - if (!userId || !organization || !projectId) { + const { userId, organization, role } = req.user || {}; + const { projectId, projectName, thumbnail } = req.body; + if (!userId || !organization || !projectId || !role) { res.status(400).json({ message: "All fields are required", }); @@ -153,6 +176,7 @@ export const updateProjectController = async ( userId, projectName, thumbnail, + role, }); switch (result?.status) { case "Project not found": @@ -184,14 +208,25 @@ export const updateProjectController = async ( return; } }; -export const ViewData = async (req: Request, res: Response): Promise => { +export const ViewData = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { try { - const { projectId, organization, userId } = req.query as { - organization: string; + const { organization, userId, role } = req.user || {}; + if ( + !req.user || + !req.user.userId || + !req.user.organization || + !req.user.role + ) { + res.status(401).json({ message: "Unauthorized" }); + return; + } + const { projectId } = req.query as { projectId: string; - userId: string; }; - if (!userId || !organization || !projectId) { + if (!userId || !organization || !projectId || !role) { res.status(400).json({ message: "All fields are required", }); @@ -201,6 +236,7 @@ export const ViewData = async (req: Request, res: Response): Promise => { projectId, organization, userId, + role, }); switch (result?.status) { case "Project not found": diff --git a/src/api-server/controller/trash/trashcontrollers.ts b/src/api-server/controller/trash/trashcontrollers.ts index 7b02590..bfc54ee 100644 --- a/src/api-server/controller/trash/trashcontrollers.ts +++ b/src/api-server/controller/trash/trashcontrollers.ts @@ -3,20 +3,21 @@ import { TrashDatas, RestoreTrashData, } from "../../../shared/services/trash/trashService.ts"; +import { AuthenticatedRequest } from "../../../shared/utils/token.ts"; export const GetTrashList = async ( - req: Request, + req: AuthenticatedRequest, res: Response ): Promise => { try { - const { organization } = req.query as { organization: string }; - if (!organization) { + const { organization, role, userId } = req.user || {}; + if (!organization || !role || !userId) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await TrashDatas({ organization }); + const result = await TrashDatas({ organization, role, userId }); switch (result.status) { case "Trash is Empty": @@ -28,7 +29,6 @@ export const GetTrashList = async ( case "Success": res.status(200).json({ - // message: "Project created Successfully", TrashDatas: result.ListDatas, }); break; @@ -47,22 +47,26 @@ export const GetTrashList = async ( }; export const RestoreTrash = async ( - req: Request, + req: AuthenticatedRequest, res: Response ): Promise => { try { - const { organization, projectId } = req.query as { - organization: string; + const { organization, role, userId } = req.user || {}; + const { projectId } = req.query as { projectId: string; }; - console.log("organization: ", organization); - if (!organization || !projectId) { + if (!organization || !projectId || !role || !userId) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await RestoreTrashData({ organization, projectId }); + const result = await RestoreTrashData({ + organization, + projectId, + role, + userId, + }); switch (result.status) { case "Project not found": diff --git a/src/api-server/controller/user-Controller.ts b/src/api-server/controller/user-Controller.ts index 01106b6..9ad5701 100644 --- a/src/api-server/controller/user-Controller.ts +++ b/src/api-server/controller/user-Controller.ts @@ -1,6 +1,6 @@ import { Request, Response } from "express"; import userModel from "../../shared/model/user-Model.ts"; -import {hashGenerate,hashValidator} from "../../shared/security/Hasing.ts" +import {hashGenerate,hashValidator} from "../../shared/utils/Hasing.ts" let serverAlive = true; export class User { diff --git a/src/shared/V1Models/Auth/tokenModel.ts b/src/shared/V1Models/Auth/tokenModel.ts index 94b93e4..30ed6fa 100644 --- a/src/shared/V1Models/Auth/tokenModel.ts +++ b/src/shared/V1Models/Auth/tokenModel.ts @@ -3,14 +3,14 @@ import MainModel from "../../connect/mongoose.ts"; import { User } from "./userAuthModel.ts"; export interface Token extends Document { userId: User["_id"]; - isArchieve: Boolean; + isArchive: Boolean; refreshToken: string; resetTokenExpiry?: Date; resetToken: string; } const tokenSchema: Schema = new Schema({ userId: { type: Schema.Types.ObjectId, ref: "User" }, - isArchieve: { type: Boolean, default: false }, + isArchive: { type: Boolean, default: false }, token: { type: String }, refreshToken: { type: String }, tokenCreatedAt: { type: Date }, diff --git a/src/shared/V1Models/Auth/user.ts b/src/shared/V1Models/Auth/user.ts index dba27bc..4988c43 100644 --- a/src/shared/V1Models/Auth/user.ts +++ b/src/shared/V1Models/Auth/user.ts @@ -3,41 +3,44 @@ import MainModel from "../../connect/mongoose.ts"; import { User } from "./userAuthModel.ts"; export interface UserData extends Document { userId: User["_id"]; + isShare: Boolean; + activeStatus: string; notificationEnable: boolean; About: string; - isArchieve: boolean; - Role: string; - Profilepicture: string; + isArchive: boolean; + role: string; + profilePicture: string; recentlyViewed: string[]; - CheckIn: number; - CheckOut: number; } const UserDataSchema: Schema = new Schema({ userId: { type: Schema.Types.ObjectId, ref: "User" }, - isArchieve: { type: Boolean, default: false }, + isArchive: { type: Boolean, default: false }, notificationEnable: { type: Boolean, default: false }, About: { type: String, }, - Role: { + role: { type: String, default: "User", enum: ["User", "Admin"], }, + isShare: { + type: Boolean, + default: false, + }, + activeStatus: { + type: String, + enum: ["online", "offline"], + default: "offline", + }, recentlyViewed: { type: [String], default: [], }, - Profilepicture: { + profilePicture: { type: String, // default: "default-profile-picture.jpg" }, - CheckIn: { - type: Number, - }, - CheckOut: { - type: Number, - }, }); const UsersDataModel = (db: any) => { diff --git a/src/shared/V1Models/Auth/userAuthModel.ts b/src/shared/V1Models/Auth/userAuthModel.ts index d1ce57b..c85e3a0 100644 --- a/src/shared/V1Models/Auth/userAuthModel.ts +++ b/src/shared/V1Models/Auth/userAuthModel.ts @@ -1,15 +1,15 @@ import { Schema, Document } from "mongoose"; import MainModel from "../../connect/mongoose.ts"; export interface User extends Document { - Username: string; + userName: string; Email: string; Password: string; - isArchieve: boolean; + isArchive: boolean; visitorBrowserID: string; lastPasswordReset: number; } -const signupschema: Schema = new Schema({ - Username: { +const AuthSchema: Schema = new Schema({ + userName: { type: String, required: true, }, @@ -23,12 +23,12 @@ const signupschema: Schema = new Schema({ min: 8, // required: true, }, - isArchieve: { type: Boolean, default: false }, + isArchive: { type: Boolean, default: false }, lastPasswordReset: { type: Number }, visitorBrowserID: { type: String }, }); -const userModel = (db: any) => { - return MainModel(db, "User", signupschema, "User"); +const AuthModel = (db: any) => { + return MainModel(db, "UserAuth", AuthSchema, "UserAuth"); }; -export default userModel; +export default AuthModel; diff --git a/src/shared/V1Models/Project/share-model.ts b/src/shared/V1Models/Project/share-model.ts new file mode 100644 index 0000000..316be17 --- /dev/null +++ b/src/shared/V1Models/Project/share-model.ts @@ -0,0 +1,52 @@ +import mongoose, { Document, Schema } from "mongoose"; +import MainModel from "../../connect/mongoose.ts"; + +export interface IShare extends Document { + Createdby: { + userId: mongoose.Types.ObjectId; + Email: string; + }; + isActive: boolean; + Share_People: [ + { + userId: mongoose.Types.ObjectId; + Email: string; + AccessPoint: string; + } + ]; + Description: string; + createdAt: number; + projectId: mongoose.Types.ObjectId; +} + +const shareSchema: Schema = new Schema({ + CreatedBy: { + userId: { + type: mongoose.Schema.Types.ObjectId, + ref: "User", + required: true, + }, + Email: { type: String, ref: "User", required: true }, + }, + isActive: { type: Boolean, default: false }, + Share_People: [ + { + userId: { type: mongoose.Schema.Types.ObjectId, ref: "User" }, + Email: { type: String, ref: "User", required: true }, + AccessPoint: { + type: String, + default: "Can view", + enum: ["Can view", "Can edit", "Can comment"], + }, + }, + ], + createdAt: { + type: Number, + default: Date.now(), + }, + projectId: { type: mongoose.Schema.Types.ObjectId, ref: "Scene" }, +}); +const shareModel = (db: any) => { + return MainModel(db, "Shared", shareSchema, "Shared"); +}; +export default shareModel; diff --git a/src/shared/middleware/rbacMiddleware.ts b/src/shared/middleware/rbacMiddleware.ts new file mode 100644 index 0000000..3a7497a --- /dev/null +++ b/src/shared/middleware/rbacMiddleware.ts @@ -0,0 +1,13 @@ +import { Response, Request, NextFunction } from "express"; +import { AuthenticatedRequest } from "../../shared/utils/token.ts"; +type Role = "Admin" | "User"; +const authorizedRoles = (...allowedRoles: Role[]) => { + return (req: AuthenticatedRequest, res: Response, next: NextFunction) => { + if (!req.user || !allowedRoles.includes(req.user.role as Role)) { + res.status(403).json({ message: "Access Denied" }); + return; + } + next(); + }; +}; +export default authorizedRoles; diff --git a/src/shared/redis/redis.ts b/src/shared/redis/redis.ts new file mode 100644 index 0000000..cda43ab --- /dev/null +++ b/src/shared/redis/redis.ts @@ -0,0 +1,21 @@ +import Redis from "ioredis"; +import * as dotenv from "dotenv"; +dotenv.config(); +const redis = new Redis.default({ + host: + process.env.REDIS_ENV === "true" + ? process.env.REDIS_DOCKER + : process.env.REDIS_LOCAL, + port: parseInt(process.env.REDIS_PORT || "6379"), + password: "", + db: 0, +}); +redis.on("connect", () => { + console.log(`Connected to Redis to ${redis.options.port}`); +}); + +redis.on("error", (err: unknown) => { + console.error("Redis connection error:", err); +}); + +export default redis; diff --git a/src/shared/security/token.ts b/src/shared/security/token.ts deleted file mode 100644 index ea71280..0000000 --- a/src/shared/security/token.ts +++ /dev/null @@ -1,38 +0,0 @@ -import { Request, Response, NextFunction } from 'express'; -import * as Jwt from 'jsonwebtoken'; // Correct way to import jsonwebtoken - -// Define a new interface extending Request -interface AuthenticatedRequest extends Request { - user?: { - email: string; - // Add more fields as needed based on your JWT payload - }; -} -const tokenGenerator = (email: string) => { - const token = Jwt.sign({ email: email }, "Milestone", { - expiresIn: "3hours", - }); - return token; - }; - -const tokenValidator = (req: AuthenticatedRequest, res: Response, next: NextFunction): void => { - const token: string | undefined = req.headers.token as string | undefined; - if (!token) { - res.status(403).json({ - msg: "No token present", - }); - return; // Make sure to return after sending a response - } - - try { - const decoded = Jwt.verify(token,"Milestone") as { email: string }; // adjust if your JWT payload has more fields - req.user = decoded; - next(); - } catch (err) { - res.status(401).json({ - msg: "Invalid Token", - }); - } -}; - -export { tokenValidator,tokenGenerator }; diff --git a/src/shared/services/auth/authServices.ts b/src/shared/services/auth/authServices.ts new file mode 100644 index 0000000..f6b3717 --- /dev/null +++ b/src/shared/services/auth/authServices.ts @@ -0,0 +1,466 @@ +import AuthModel from "../../V1Models/Auth/userAuthModel.ts"; +import UsersDataModel from "../../V1Models/Auth/user.ts"; +import nodemailer from "nodemailer"; +import tokenType from "../../V1Models/Auth/tokenModel.ts"; +import Jwt from "jsonwebtoken"; + +import { hashValidator, hashGenerate } from "../../utils/Hasing.ts"; +import redis from "../../redis/redis.ts"; +import { tokenGenerator, tokenRefreshGenerator } from "../../utils/token.ts"; +interface Iserviceuser { + userName: string; + Email: string; + Password: string; + profilePicture: string; +} +interface IloginUser { + Email: string; + Password: string; + fingerprint: string; +} +interface IresetToken { + resetToken: string; + newPassword: string; + confirmPassword: string; +} +interface IUser { + Email: string; + userName: string; + _id: string; +} +const jwt_secret = process.env.JWT_SECRET as string; +export function extractOrg(Email: string) { + return Email.split("@")[1].split(".")[0]; +} +async function findExistingUserEmail(Email: string) { + const organization = extractOrg(Email); + const existingUser = await AuthModel(organization).findOne({ + Email: Email, + isArchive: false, + }); + return existingUser; +} + +export const AuthSignup = async ( + data: Iserviceuser +): Promise<{ + status: string; +}> => { + const { userName, Email, Password, profilePicture } = data; + try { + let role; + const caseChange = Email.toLowerCase(); + const organization = extractOrg(caseChange); + const Existing_User = await findExistingUserEmail(caseChange); + if (Existing_User) { + return { status: "User already exists" }; + } else { + const hashPassword = await hashGenerate(Password); + const userCount = await AuthModel(organization).countDocuments({}); + role = userCount === 0 ? "Admin" : "User"; + const isShare = "true"; + const newuser = await AuthModel(organization).create({ + userName: userName, + Email: caseChange, + Password: hashPassword, + }); + const UserDatas = await UsersDataModel(organization).create({ + userId: newuser._id, + role: role, + isShare: isShare, + profilePicture: profilePicture, + }); + return { status: "Success" }; + } + } catch (error: unknown) { + if (error instanceof Error) { + return { + status: error.message, + }; + } else { + return { + status: "An unexpected error occurred", + }; + } + } +}; + +export const AuthLogin = async ( + data: IloginUser +): Promise<{ status: string; data?: Object }> => { + try { + const { Email, Password, fingerprint } = data; + const caseChange = Email.toLowerCase(); + const organization = extractOrg(caseChange); + const Existing_User = await findExistingUserEmail(caseChange); + if (!Existing_User) return { status: "User Not Found!!! Kindly signup..." }; + else { + const existingMail = await getUserFromCacheOrDB(caseChange); + const checkPassword = await hashValidator( + Password, + existingMail.Password + ); + if (!checkPassword) + return { + status: "Email & Password is invalid...Check the credentials", + }; + + const browserID = existingMail.visitorBrowserID; + if (browserID && browserID !== fingerprint) { + await Promise.all([ + redis.del(`token:${caseChange}`), + redis.del(`user:${caseChange}`), + ]); + await AuthModel(organization).updateOne( + { Email: caseChange }, + { visitorBrowserID: "" } + ); + await tokenType(organization).updateOne( + { userId: Existing_User._id }, + { refreshToken: "" } + ); + return { + status: "Already LoggedIn on another browser....Please logout!!!", + }; + } + const UserData = await UsersDataModel(organization).findOne({ + userId: existingMail._id, + isArchive: false, + }); + if (!UserData) + return { + status: "User_Datas not found", + }; + const redisTokenRaw = await redis.get(`token:${caseChange}`); + if (redisTokenRaw) { + const cachedTokens = JSON.parse(redisTokenRaw); + try { + Jwt.verify(cachedTokens.token, jwt_secret); + return { + status: "Success", + data: { + message: "login successfull", + email: existingMail.Email, + name: existingMail.userName, + userId: existingMail._id, + isShare: UserData.isShare, + token: cachedTokens.token, + refreshToken: cachedTokens.refreshToken, + }, + }; + } catch (err) { + console.log("Access token expired. Generating new..."); + } + } + const tokenValidation = tokenGenerator( + existingMail.Email, + UserData.role, + existingMail._id, + organization + ); + const refreshTokenvalidation = tokenRefreshGenerator( + existingMail.Email, + UserData.role, + existingMail._id, + organization + ); + + await handleTokenCache( + existingMail._id.toString(), + existingMail.Email, + tokenValidation, + refreshTokenvalidation + ); + + const updatedUser = await AuthModel(organization) + .findByIdAndUpdate( + existingMail._id, + { visitorBrowserID: fingerprint }, + { new: true } + ) + .select("-__v -Profilepicture"); + if (!updatedUser) + return { + status: "User update failed.", + }; + await redis.setex( + `user:${existingMail.Email}`, + 3600, + JSON.stringify(updatedUser) + ); + const finalResult = { + message: "login successfull", + email: existingMail.Email, + name: existingMail.userName, + userId: existingMail._id, + isShare: UserData.isShare, + // updatedUser: updatedUser as IUser, + token: tokenValidation, + refreshToken: refreshTokenvalidation, + }; + return { + status: "Success", + data: finalResult, + }; + } + } catch (error: unknown) { + if (error instanceof Error) { + return { + status: error.message, + }; + } else { + return { + status: "An unexpected error occurred", + }; + } + } +}; +export const AuthLogout = async ({ + Email, +}: Iserviceuser): Promise<{ status: string }> => { + try { + const caseChange = Email.toLowerCase(); + const organization = extractOrg(caseChange); + const Existing_User = await findExistingUserEmail(caseChange); + if (!Existing_User) return { status: "User not found" }; + + const tokenData = await tokenType(organization).findOne({ + userId: Existing_User._id, + isArchive: false, + }); + + if (!tokenData) return { status: "Token not found" }; + await Promise.all([ + redis.del(`token:${caseChange}`), + redis.del(`user:${caseChange}`), + ]); + tokenData.refreshToken = ""; + await tokenData.save(); + Existing_User.visitorBrowserID = ""; + await Existing_User.save(); + return { status: "Success" }; + } catch (error: unknown) { + if (error instanceof Error) { + return { + status: error.message, + }; + } else { + return { + status: "An unexpected error occurred", + }; + } + } +}; +export const forgetPassword = async ({ + Email, +}: Iserviceuser): Promise<{ status: string }> => { + try { + const caseChange = Email.toLowerCase(); + const organization = extractOrg(caseChange); + const Existing_User = await findExistingUserEmail(caseChange); + if (Existing_User) { + if (Existing_User.lastPasswordReset) { + const lastPasswordReset = Existing_User.lastPasswordReset; + const now = Date.now(); + const timeDiff = now - lastPasswordReset; + const diffInHours = Math.floor(timeDiff / (1000 * 60 * 60)); + if (diffInHours < 24) + return { + status: "You can only reset your password once every 24 hours.", + }; + } + const transport = nodemailer.createTransport({ + service: "gmail", + secure: true, + auth: { + user: process.env.EMAIL_USER, + pass: process.env.EMAIL_PASS, + }, + }); + const resetToken = tokenGenerator( + Email, + Existing_User.Role as string, + Existing_User._id as string, + organization + ); + const userTokenData = await tokenType(organization).findOne({ + Email: Email, + isArchive: false, + }); + if (!userTokenData) { + await tokenType(organization).create({ + Email: Existing_User.Email, + userId: Existing_User._id, + resetToken: resetToken, + resetTokenExpiry: Date.now(), + }); + } else { + userTokenData.resetToken = resetToken; + userTokenData.resetTokenExpiry = new Date(); + await userTokenData.save(); + } + const Receiver = { + from: process.env.EMAIL_USER, + to: Email, + subject: "Password Reset Request", + text: `Click the below link to generate the new password \n ${ + process.env.CLIENT_URL + }/reset-password/${tokenGenerator( + Email, + Existing_User.Role as string, + Existing_User._id as string, + organization + )}`, + }; + await transport.sendMail(Receiver); + + return { status: "Success" }; + } else { + return { status: "Email not found" }; + } + } catch (error: unknown) { + if (error instanceof Error) { + return { + status: error.message, + }; + } else { + return { + status: "An unexpected error occurred", + }; + } + } +}; +export const resetPassword = async ({ + resetToken, + newPassword, + confirmPassword, +}: IresetToken): Promise<{ status: string }> => { + try { + const decoded = Jwt.verify(resetToken, "Milestone"); + if (typeof decoded === "string" || !("email" in decoded)) + return { status: "Invalid token payload." }; + + const Email = decoded.email; + const organization = extractOrg(Email); + if (newPassword !== confirmPassword) return { status: "Password mismatch" }; + + const userData = await AuthModel(organization).findOne({ + Email: Email, + isArchive: false, + }); + const userTokenData = await tokenType(organization).findOne({ + Email: Email, + isArchive: false, + }); + if (!userData || !userTokenData) return { status: "User not found" }; + else { + const tokenexpiry = userTokenData.resetTokenExpiry as Date; + const now = Date.now(); + const tokenAge = tokenexpiry ? now - tokenexpiry.getTime() : 0; + const TOKEN_EXPIRATION_TIME = 15 * 60 * 1000; + + if (!tokenexpiry || tokenAge > TOKEN_EXPIRATION_TIME) + return { status: "Token is invalid or expired." }; + const hashPassword = await hashGenerate(newPassword); + const lastPasswordReset = Date.now(); + await AuthModel(organization).findByIdAndUpdate( + userData._id, + { Password: hashPassword, lastPasswordReset: lastPasswordReset }, + { new: true } + ); + userTokenData.resetToken = ""; + userTokenData.resetTokenExpiry = undefined; + await userTokenData.save(); + await ResetFromCacheOrDB(Email); + return { status: "Success" }; + } + } catch (error: unknown) { + if (error instanceof Error) { + return { + status: error.message, + }; + } else { + return { + status: "An unexpected error occurred", + }; + } + } +}; + +async function getUserFromCacheOrDB(Email: string) { + const redisUserKey = `user:${Email}`; + try { + const cachedUser = await redis.get(redisUserKey); + if (cachedUser) return JSON.parse(cachedUser); + + const Existing_User = await findExistingUserEmail(Email); + + if (Existing_User) { + await redis.setex(redisUserKey, 3600, JSON.stringify(Existing_User)); + } + return Existing_User; + } catch (error) { + return error; + } +} + +async function ResetFromCacheOrDB(Email: string) { + const redisUserKey = `user:${Email}`; + try { + const organization = extractOrg(Email); + const cachedUser = await redis.get(redisUserKey); + if (cachedUser) { + const user = await AuthModel(organization) + .findOne({ + Email: Email, + isArchive: false, + }) + .lean() + .select("-__v -Profilepicture"); + + if (user) { + await redis.setex(redisUserKey, 3600, JSON.stringify(user)); + } + return user; + } + } catch (error) { + return error; + } +} + +async function handleTokenCache( + userId: string, + Email: string, + token: string, + refreshToken: string +) { + const redisTokenKey = `token:${Email}`; + try { + const organization = extractOrg(Email); + const tokenPayload = { + token, + refreshToken, + userId, + Email, + }; + await redis.setex(redisTokenKey, 3600, JSON.stringify(tokenPayload)); + + let tokenDoc = await tokenType(organization).findOne({ + userId, + isArchive: false, + }); + if (!tokenDoc) { + tokenDoc = await tokenType(organization).create({ userId, refreshToken }); + } else { + await tokenType(organization).findByIdAndUpdate( + tokenDoc._id, + { refreshToken }, + { new: true } + ); + } + + return tokenPayload; + } catch (error) { + return error; + } +} diff --git a/src/shared/services/builder/cameraService.ts b/src/shared/services/builder/cameraService.ts new file mode 100644 index 0000000..94c1d7c --- /dev/null +++ b/src/shared/services/builder/cameraService.ts @@ -0,0 +1,155 @@ +import projectModel from "../../model/project/project-model.ts"; +import userModel from "../../model/user-Model.ts"; +import versionModel from "../../model/version/versionModel.ts"; +import UsersDataModel from "../../V1Models/Auth/user.ts"; +import cameraModel from "../../V1Models/Builder/cameraModel.ts"; +import { existingProjectById } from "../helpers/ProjecthelperFn.ts"; +interface IcameraData { + userId: string; + position: Object; + target: Object; + rotation: Object; + organization: string; + projectId: string; + versionId: string; +} +interface IgetCameras { + organization: string; + userId?: string; +} +export const SetCamera = async ( + data: IcameraData +): Promise<{ status: string; data?: Object }> => { + try { + const { + userId, + position, + target, + rotation, + organization, + projectId, + versionId, + } = data; + const LivingProject = await existingProjectById( + projectId, + organization, + userId + ); + if (!LivingProject) return { status: "Project not found" }; + const existingCamera = await cameraModel(organization).findOne({ + userId: userId, + }); + if (existingCamera) { + const updateCamera = await cameraModel(organization).findOneAndUpdate( + { + userId: userId, + projectId: projectId, + versionId: versionId, + isArchive: false, + }, + { position: position, target: target, rotation: rotation }, + { new: true } + ); + return { + status: "Update Success", + data: updateCamera, + }; + } else { + const newCamera = await cameraModel(organization).create({ + userId, + projectId, + versionId, + position, + target, + rotation, + }); + + return { + status: "Creation Success", + data: newCamera, + }; + } + } catch (error: unknown) { + if (error instanceof Error) { + return { + status: error.message, + }; + } else { + return { + status: "An unexpected error occurred", + }; + } + } +}; +export const GetCamers = async ( + data: IgetCameras +): Promise<{ status: string; data?: Object }> => { + const { userId, organization } = data; + try { + const findCamera = await cameraModel(organization).findOne({ + userId: userId, + }); + if (!findCamera) { + return { status: "user not found" }; + } else { + return { status: "Success", data: findCamera }; + } + } catch (error: unknown) { + if (error instanceof Error) { + return { + status: error.message, + }; + } else { + return { + status: "An unexpected error occurred", + }; + } + } +}; +export const onlineActiveDatas = async ( + data: IgetCameras +): Promise<{ status: string; data?: Object }> => { + const { organization } = data; + try { + const findactiveUsers = await UsersDataModel(organization).find({ + activeStatus: "online", + }); + + const cameraDataPromises = findactiveUsers.map(async (activeUser: any) => { + const cameraData = await cameraModel(organization) + .findOne({ userId: activeUser._id }) + .select("position target rotation -_id"); + + if (cameraData) { + return { + position: cameraData.position, + target: cameraData.target, + rotation: cameraData.rotation, + userData: { + _id: activeUser._id, + userName: activeUser.userName, + email: activeUser.email, + activeStatus: activeUser.activeStatus, + }, + }; + } + return null; + }); + + const cameraDatas = (await Promise.all(cameraDataPromises)).filter( + (singledata: any) => singledata !== null + ); + + return { status: "Success", data: cameraDatas }; + } catch (error: unknown) { + if (error instanceof Error) { + return { + status: error.message, + }; + } else { + return { + status: "An unexpected error occurred", + }; + } + } +}; diff --git a/src/shared/services/helpers/ProjecthelperFn.ts b/src/shared/services/helpers/ProjecthelperFn.ts index 3f01f19..3ce8cc3 100644 --- a/src/shared/services/helpers/ProjecthelperFn.ts +++ b/src/shared/services/helpers/ProjecthelperFn.ts @@ -2,6 +2,7 @@ import projectModel from "../../model/project/project-model.ts"; import userModel from "../../model/user-Model.ts"; import { Types } from "mongoose"; import versionModel from "../../model/version/versionModel.ts"; +import AuthModel from "../../V1Models/Auth/userAuthModel.ts"; export const existingProject = async ( projectUuid: string, organization: string, @@ -20,7 +21,7 @@ export const existingUser = async (userId: string, organization: string) => { console.log("Invalid ObjectId format"); return null; } - const userData = await userModel(organization).findOne({ + const userData = await AuthModel(organization).findOne({ _id: userId, }); return userData; @@ -76,3 +77,15 @@ export const generateUntitledProjectName = async ( return newNumber === 0 ? "Untitled" : `Untitled ${newNumber}`; }; +export const existingProjectById = async ( + projectId: string, + organization: string, + userId: string +) => { + const projectData = await projectModel(organization).findOne({ + _id: projectId, + createdBy: userId, + isArchive: false, + }); + return projectData; +}; diff --git a/src/shared/services/home/homeService.ts b/src/shared/services/home/homeService.ts index 04c26fd..758d174 100644 --- a/src/shared/services/home/homeService.ts +++ b/src/shared/services/home/homeService.ts @@ -1,10 +1,12 @@ import projectModel from "../../model/project/project-model.ts"; import userModel from "../../model/user-Model.ts"; +import UsersDataModel from "../../V1Models/Auth/user.ts"; import { existingUser } from "../helpers/ProjecthelperFn.ts"; interface IRecentData { organization: string; userId: string; + role: string; } interface IProject { _id: string; @@ -19,26 +21,31 @@ interface searchProjectInterface { userId: string; organization: string; } +interface RoleFilter { + isArchive: boolean; + createdBy?: string; +} export const RecentlyAdded = async (data: IRecentData) => { try { - const { userId, organization } = data; + const { userId, organization, role } = data; const userExisting = await existingUser(userId, organization); if (!userExisting) return { status: "User not found" }; - const userRecentData = await userModel(organization) - .findOne({ _id: userId }) + const userRecentData = await UsersDataModel(organization) + .findOne({ userId: userId, isArchive: false }) .populate({ path: "recentlyViewed", model: projectModel(organization), select: "_id", }); + let filter = { isArchive: false } as RoleFilter; + if (role === "User") { + filter.createdBy = userId; + } const populatedProjects = userRecentData.recentlyViewed as IProject[]; const RecentDatas = await Promise.all( populatedProjects.map(async (project) => { const projectExisting = await projectModel(organization) - .findOne({ - _id: project._id, - isArchive: false, - }) + .findOne(filter) .select("_id projectName createdBy thumbnail createdAt isViewed"); return projectExisting; }) @@ -57,26 +64,29 @@ export const searchProject = async (data: searchProjectInterface) => { if (!userExisting) return { status: "User not found" }; const findprojectName = await projectModel(organization).find({ projectName: { $regex: `${searchName}`, $options: "i" }, // 'i' makes it case-insensitive - isArchive: false, - }) - if (!findprojectName||findprojectName.length===0) return { status: "Project not found" } + isArchive: false, + }); + if (!findprojectName || findprojectName.length === 0) + return { status: "Project not found" }; return { status: "Success", data: findprojectName }; } catch (error: unknown) { return { status: error }; } -} +}; export const searchTrashProject = async (data: searchProjectInterface) => { try { const { userId, organization, searchName } = data; const userExisting = await existingUser(userId, organization); if (!userExisting) return { status: "User not found" }; const findprojectName = await projectModel(organization).find({ - projectName: { $regex: `${searchName}`, $options: "i" }, - isArchive: true,isDeleted:false - }) - if (!findprojectName||findprojectName.length===0) return { status: "Project not found" } + projectName: { $regex: `${searchName}`, $options: "i" }, + isArchive: true, + isDeleted: false, + }); + if (!findprojectName || findprojectName.length === 0) + return { status: "Project not found" }; return { status: "Success", data: findprojectName }; } catch (error: unknown) { return { status: error }; } -} \ No newline at end of file +}; diff --git a/src/shared/services/project/project-Services.ts b/src/shared/services/project/project-Services.ts index 69d5a6c..17300cb 100644 --- a/src/shared/services/project/project-Services.ts +++ b/src/shared/services/project/project-Services.ts @@ -1,6 +1,8 @@ +import { ObjectId } from "mongoose"; import projectModel from "../../model/project/project-model.ts"; import userModel from "../../model/user-Model.ts"; import versionModel from "../../model/version/versionModel.ts"; +import { AuthenticatedRequest } from "../../utils/token.ts"; import { existingProject, existingUser, @@ -8,6 +10,7 @@ import { previousVersion, generateUntitledProjectName, } from "../helpers/ProjecthelperFn.ts"; +import UsersDataModel from "../../V1Models/Auth/user.ts"; interface CreateProjectInput { projectName: string; projectUuid: string; @@ -23,26 +26,32 @@ interface updateProjectInput { thumbnail?: string; sharedUsers?: string[]; organization: string; + role: string; } interface GetProjectsInterface { userId: string; organization: string; + role: string; } interface ProjectInterface { projectId: string; userId: string; organization: string; + role: string; +} +interface RoleFilter { + isArchive: boolean; + createdBy?: string; } - export const createProject = async (data: CreateProjectInput) => { try { - const { userId, thumbnail, sharedUsers, organization, projectUuid } = data; + const { thumbnail, sharedUsers, projectUuid, userId, organization } = data; const userExisting = await existingUser(userId, organization); if (!userExisting) { return { status: "user_not_found", }; - } + } const projectExisting = await existingProject( projectUuid, organization, @@ -93,13 +102,15 @@ export const createProject = async (data: CreateProjectInput) => { export const GetAllProjects = async (data: GetProjectsInterface) => { try { - const { userId, organization } = data; + const { userId, organization, role } = data; 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({ - isArchive: false, - }) + .find(filter) .select("_id projectName createdBy thumbnail createdAt projectUuid"); if (projectDatas) return { status: "Success", Datas: projectDatas }; } catch (error: unknown) { @@ -109,41 +120,42 @@ export const GetAllProjects = async (data: GetProjectsInterface) => { export const DeleteProject = async (data: ProjectInterface) => { try { - const { projectId, organization, userId } = data; + const { projectId, organization, userId, role } = data; const ExistingUser = await existingUser(userId, organization); if (!ExistingUser) return { status: "User not found" }; - const existingProject = await projectModel(organization).findOne({ - _id: projectId, - createdBy: userId, - 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 updateProject = await projectModel(organization).findOneAndUpdate( - { _id: projectId, isArchive: false }, + filter, { isArchive: true, DeletedAt: new Date() }, { new: true } ); - if (updateProject) return { status: "Success",project: updateProject }; + if (updateProject) return { status: "Success", project: updateProject }; } catch (error: unknown) { return { status: error }; } }; export const updateProject = async (data: updateProjectInput) => { try { - const { projectId, organization, userId, projectName, thumbnail } = data; + const { projectId, organization, userId, projectName, thumbnail, role } = + data; const ExistingUser = await existingUser(userId, organization); if (!ExistingUser) return { status: "User not found" }; - const existingProject = await projectModel(organization).findOne({ - _id: projectId, - createdBy: userId, - 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" }; if (projectName !== undefined) projectName; if (thumbnail !== undefined) thumbnail; const updateProject = await projectModel(organization) .findOneAndUpdate( - { _id: projectId, isArchive: false }, + filter, { projectName: projectName, thumbnail: thumbnail }, { new: true } ) @@ -156,18 +168,23 @@ export const updateProject = async (data: updateProjectInput) => { const maxLength: number = 6; export const viewProject = async (data: ProjectInterface) => { try { - const { projectId, organization, userId } = data; + const { projectId, organization, userId, role } = data; const userExisting = await existingUser(userId, organization); if (!userExisting) return { status: "User not found" }; - const existingProject = await projectModel(organization).findOne({ - _id: projectId, - createdBy: userId, + const RecentUserDoc = await UsersDataModel(organization).findOne({ + userId: userId, 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 = userExisting?.recentlyViewed || []; - if (userExisting?.recentlyViewed.length === 0) { + const newArr = RecentUserDoc?.recentlyViewed || []; + if (RecentUserDoc?.recentlyViewed.length === 0) { newArr.push(projectId); + await RecentUserDoc.save(); } else { const index = newArr.indexOf(projectId); if (index !== -1) { @@ -179,21 +196,13 @@ export const viewProject = async (data: ProjectInterface) => { newArr.pop(); } } - await userModel(organization).updateOne( + await UsersDataModel(organization).updateOne( { _id: userId }, { recentlyViewed: newArr }, { new: true } ); const projectData = await projectModel(organization) - .findOneAndUpdate( - { - _id: projectId, - createdBy: userId, - isArchive: false, - }, - { isViewed: Date.now() }, - { new: true } - ) + .findOneAndUpdate(filter, { isViewed: Date.now() }, { new: true }) .select("_id projectName createdBy thumbnail createdAt"); return { status: "Success", data: projectData }; } catch (error: unknown) { diff --git a/src/shared/services/trash/trashService.ts b/src/shared/services/trash/trashService.ts index 2976f95..ae833ff 100644 --- a/src/shared/services/trash/trashService.ts +++ b/src/shared/services/trash/trashService.ts @@ -1,19 +1,27 @@ import projectModel from "../../model/project/project-model.ts"; interface IOrg { organization: string; + role: string; + userId: string; } interface IRestore { projectId: string; organization: string; + role: string; + userId: string; +} +interface RoleFilter { + isArchive: boolean; + createdBy?: string; } export const TrashDatas = async (data: IOrg) => { try { - const { organization } = data; - - const TrashLists = await projectModel(organization).find({ - isArchive: true, - isDeleted: false, - }); + const { organization, role, userId } = data; + let filter = { isArchive: true, isDeleted: false } as RoleFilter; + if (role === "User") { + filter.createdBy = userId; + } + const TrashLists = await projectModel(organization).find(filter); if (!TrashLists) return { staus: "Trash is Empty" }; const TrashDocs: any[] = []; for (const Trash of TrashLists) { @@ -47,14 +55,15 @@ export const TrashDatas = async (data: IOrg) => { }; export const RestoreTrashData = async (data: IRestore) => { try { - const { projectId, organization } = data; - const findProject = await projectModel(organization).findOne({ - _id: projectId, - isArchive: true, - }); + const { projectId, organization, role, userId } = data; + 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( - { _id: projectId, isArchive: true }, + filter, { isArchive: false, DeletedAt: null }, { new: true } ); diff --git a/src/shared/services/version/versionService.ts b/src/shared/services/version/versionService.ts new file mode 100644 index 0000000..fbd0bb2 --- /dev/null +++ b/src/shared/services/version/versionService.ts @@ -0,0 +1,127 @@ +import projectModel from "../../model/project/project-model.ts"; +import assetModel from "../../V1Models/Builder/assetModel.ts"; +import versionModel from "../../model/version/versionModel.ts"; + +class VersionService { + async getCurrentVersion(db: string, projectId: string) { + const project = await projectModel(db).findById(projectId); + if (!project) throw new Error("Project not found"); + + return { + versionNumber: parseFloat(project.Present_version || "0.0"), + versionString: project.Present_version || "0.0", + }; + } + + async createNewVersion( + db: string, + projectId: string, + userId: string, + description?: string + ) { + const project = await projectModel(db).findById(projectId); + if (!project) throw new Error("Project not found"); + + const { versionNumber } = await this.getCurrentVersion(db, projectId); + const newVersion = parseFloat((versionNumber + 0.1).toFixed(1)); + const versionName = `Version ${newVersion.toFixed(1)}`; + + const version = await versionModel(db).create({ + versionName, + version: newVersion, + projectId: project._id, + createdBy: userId, + description, + }); + + await projectModel(db).findByIdAndUpdate(projectId, { + Present_version: newVersion.toFixed(1), + total_versions: newVersion.toFixed(1), + }); + + return version; + } + + async saveCurrentStateAsVersion( + db: string, + projectId: string, + userId: string, + description?: string + ) { + // Create new version + const newVersion = await this.createNewVersion( + db, + projectId, + userId, + description + ); + + // Get all assets from previous version + const previousVersion = parseFloat((newVersion.version - 0.1).toFixed(1)); + const previousVersionDoc = await versionModel(db).findOne({ + projectId, + version: previousVersion, + }); + console.log('previousVersionDoc: ', previousVersionDoc); + + let previousAssets = []; + if (previousVersionDoc) { + previousAssets = await assetModel(db).find({ + projectId, + versionId: previousVersionDoc._id, + isArchive: false, + }); + } + + // Copy assets to new version + const newAssets = await Promise.all( + previousAssets.map(async (asset) => { + console.log('previousAssets: ', previousAssets); + const newAsset = { ...asset.toObject(), versionId: newVersion._id }; + delete newAsset._id; + return await assetModel(db).create(newAsset); + }) + ); + + return { + version: newVersion, + assets: newAssets, + }; + } + + async getVersionHistory(db: string, projectId: string) { + const versions = await versionModel(db) + .find({ projectId, isArchive: false }) + .sort({ version: 1 }) + .populate("createdBy", "name email"); + + const versionHistory = await Promise.all( + versions.map(async (version) => { + const assets = await assetModel(db).find({ + projectId, + versionId: version._id, + isArchive: false, + }); + + const assetCounts = assets.reduce((acc, asset) => { + acc[asset.type] = (acc[asset.type] || 0) + 1; + return acc; + }, {}); + + return { + version: version.version.toFixed(1), + versionName: version.versionName, + createdAt: version.createdAt, + createdBy: version.createdBy, + description: version.description, + assets: assetCounts, + totalAssets: assets.length, + }; + }) + ); + + return versionHistory; + } +} + +export default new VersionService(); diff --git a/src/shared/security/Hasing.ts b/src/shared/utils/Hasing.ts similarity index 62% rename from src/shared/security/Hasing.ts rename to src/shared/utils/Hasing.ts index 7b52ee1..601228d 100644 --- a/src/shared/security/Hasing.ts +++ b/src/shared/utils/Hasing.ts @@ -1,24 +1,25 @@ -import bcrypt from 'bcryptjs'; - -const saltRounds = 10; -export const hashGenerate = async (Password:string) => { - try { - const salt = await bcrypt.genSalt(saltRounds); - const hash = await bcrypt.hash(Password, salt); - - return hash; - } catch (error) { - return error; - } -}; -export const hashValidator = async (password:string, hashedPassword:string) => { - - try { - const result = await bcrypt.compare(password, hashedPassword); - - return result; - } catch (error) { - return false; - } -}; -; +import bcrypt from "bcryptjs"; + +const saltRounds = 10; +export const hashGenerate = async (Password: string) => { + try { + const salt = await bcrypt.genSalt(saltRounds); + const hash = await bcrypt.hash(Password, salt); + + return hash; + } catch (error) { + return error; + } +}; +export const hashValidator = async ( + password: string, + hashedPassword: string +) => { + try { + const result = await bcrypt.compare(password, hashedPassword); + + return result; + } catch (error) { + return false; + } +}; diff --git a/src/shared/security/mongosecurity.ts b/src/shared/utils/mongosecurity.ts similarity index 97% rename from src/shared/security/mongosecurity.ts rename to src/shared/utils/mongosecurity.ts index 6cb1364..1e665b1 100644 --- a/src/shared/security/mongosecurity.ts +++ b/src/shared/utils/mongosecurity.ts @@ -1,34 +1,34 @@ -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(); - } - } - +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(); + } + } + // mongoAdminCreation \ No newline at end of file diff --git a/src/shared/utils/token.ts b/src/shared/utils/token.ts new file mode 100644 index 0000000..552b29b --- /dev/null +++ b/src/shared/utils/token.ts @@ -0,0 +1,143 @@ +import { Request, Response, NextFunction } from "express"; +import Jwt from "jsonwebtoken"; +import dotenv from "dotenv"; +import { extractOrg } from "../services/auth/authServices.ts"; +import AuthModel from "../V1Models/Auth/userAuthModel.ts"; +dotenv.config(); + +export interface AuthenticatedRequest extends Request { + user?: { + Email: string; + role: string; + userId: string; + organization: string; + }; +} +const jwt_secret = process.env.JWT_SECRET as string; +const refresh_jwt_secret = process.env.REFRESH_JWT_SECRET as string; +const tokenGenerator = ( + Email: string, + role: string, + userId: string, + organization: string +) => { + const token = Jwt.sign( + { Email: Email, role: role, userId, organization: organization }, + jwt_secret, + { + expiresIn: "3h", + } + ); + return token; +}; +const tokenRefreshGenerator = ( + Email: string, + role: string, + userId: string, + organization: string +) => { + const token = Jwt.sign( + { Email: Email, role: role, userId, organization: organization }, + refresh_jwt_secret, + { + expiresIn: "30d", + } + ); + return token; +}; +const tokenValidator = async ( + req: AuthenticatedRequest, + res: Response, + next: NextFunction +): Promise => { + const token: string | undefined = req.headers.token as string | undefined; + const refresh_token = req.headers["refresh_token"] as string | undefined; + if (!token) { + res.status(403).json({ + msg: "No token present", + }); + return; + } + + try { + const decoded = Jwt.verify(token, jwt_secret) as { + Email: string; + role: string; + userId: string; + organization: string; + }; + if (!decoded) { + res.status(403).json({ + success: false, + status: 403, + message: "Invalid Token", + }); + return; + } + req.user = decoded; + next(); + } catch (err) { + // res.status(401).json({ + // msg: "Invalid Token", + // }); + if (!refresh_token) { + res.status(403).json({ + success: false, + status: 403, + message: "No refresh token present", + }); + return; + } + try { + const decodedRefresh = Jwt.verify(refresh_token, refresh_jwt_secret) as { + Email: string; + role: string; + userId: string; + organization: string; + }; + if (!decodedRefresh) { + res.status(403).json({ + success: false, + status: 403, + message: "Invalid Token", + }); + return; + } + const newAccessToken = tokenGenerator( + decodedRefresh.Email, + decodedRefresh.role, + decodedRefresh.userId, + decodedRefresh.organization + ); + res.setHeader("x-access-token", newAccessToken); + req.user = decodedRefresh; + return next(); + } catch (err) { + const decodedAny = Jwt.decode(token || refresh_token) as { + Email?: string; + role: string; + userId: string; + organization: string; + }; + if (decodedAny?.Email) { + const organization = extractOrg(decodedAny?.Email); + const user = await AuthModel(organization).findOne({ + Email: decodedAny.Email, + isArchieve: false, + }); + if (user) { + user.visitorBrowserID = ""; + await user.save(); + } + } + res.status(403).json({ + success: false, + status: 403, + message: "Invalid Token", + }); + return; + } + } +}; + +export { tokenValidator, tokenGenerator, tokenRefreshGenerator }; From 089c6af1b6c06bc64ad4f1f6d372b6a5bfb67128 Mon Sep 17 00:00:00 2001 From: Nivetharamesh Date: Mon, 26 May 2025 12:24:06 +0530 Subject: [PATCH 5/6] V1 folder created For auth Data project, trash, home page based on the token and role based --- .../homeController/v1homeController.ts | 151 ++++++++++ .../projectController/v1projectController.ts | 270 ++++++++++++++++++ .../trashController/v1trashController.ts | 99 +++++++ src/api-server/V1/v1Routes/authRoutes.ts | 64 ----- src/api-server/V1/v1Routes/v1-homeRoutes.ts | 16 ++ .../V1/v1Routes/v1-projectRoutes.ts | 42 +++ src/api-server/V1/v1Routes/v1-trashRoutes.ts | 25 ++ src/api-server/app.ts | 10 +- .../controller/home/homeControllers.ts | 27 +- .../controller/project/projectController.ts | 78 ++--- .../controller/trash/trashcontrollers.ts | 26 +- .../services/helpers/ProjecthelperFn.ts | 3 +- .../services/helpers/v1projecthelperFns.ts | 90 ++++++ src/shared/services/home/homeService.ts | 21 +- .../services/project/project-Services.ts | 89 +++--- src/shared/services/trash/trashService.ts | 33 +-- .../services/v1Project/v1projectservice.ts | 208 ++++++++++++++ src/shared/services/v1home/v1homeservice.ts | 92 ++++++ src/shared/services/v1trash/v1trashservice.ts | 75 +++++ src/shared/services/version/versionService.ts | 10 +- 20 files changed, 1193 insertions(+), 236 deletions(-) create mode 100644 src/api-server/V1/v1Controllers/homeController/v1homeController.ts create mode 100644 src/api-server/V1/v1Controllers/projectController/v1projectController.ts create mode 100644 src/api-server/V1/v1Controllers/trashController/v1trashController.ts create mode 100644 src/api-server/V1/v1Routes/v1-homeRoutes.ts create mode 100644 src/api-server/V1/v1Routes/v1-projectRoutes.ts create mode 100644 src/api-server/V1/v1Routes/v1-trashRoutes.ts create mode 100644 src/shared/services/helpers/v1projecthelperFns.ts create mode 100644 src/shared/services/v1Project/v1projectservice.ts create mode 100644 src/shared/services/v1home/v1homeservice.ts create mode 100644 src/shared/services/v1trash/v1trashservice.ts diff --git a/src/api-server/V1/v1Controllers/homeController/v1homeController.ts b/src/api-server/V1/v1Controllers/homeController/v1homeController.ts new file mode 100644 index 0000000..6461f60 --- /dev/null +++ b/src/api-server/V1/v1Controllers/homeController/v1homeController.ts @@ -0,0 +1,151 @@ +import { Request, Response } from "express"; +import { + RecentlyAdded, + searchProject, + searchTrashProject, +} from "../../../../shared/services/v1home/v1homeservice.ts"; +import { AuthenticatedRequest } from "../../../../shared/utils/token.ts"; + +export const recentDataController = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { userId, organization, role } = req.user || {}; + if (!userId || !organization || !role) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await RecentlyAdded({ userId, organization, role }); + + switch (result.status) { + case "User not found": + res.status(404).json({ + message: "User not found", + }); + break; + case "Datas were empty": + res.status(200).json({ + RecentlyViewed: [], + }); + break; + case "Success": + res.status(200).json({ + RecentlyViewed: result.data, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "Unknown error", + }); + return; + } +}; +export const searchProjectController = async ( + req: Request, + res: Response +): Promise => { + try { + const { searchName, organization, userId } = req.query as { + organization: string; + searchName: string; + userId: string; + }; + if (!userId || !organization || !searchName) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await searchProject({ + searchName, + organization, + userId, + }); + switch (result?.status) { + case "Project not found": + res.status(200).json({ + message: "Project not found", + }); + break; + case "User not found": + res.status(404).json({ + message: "User not found", + }); + break; + case "Success": + res.status(200).json({ + projectData: result.data, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "Unknown error", + }); + return; + } +}; +export const searchTrashProjectController = async ( + req: Request, + res: Response +): Promise => { + try { + const { searchName, organization, userId } = req.query as { + organization: string; + searchName: string; + userId: string; + }; + if (!userId || !organization || !searchName) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await searchTrashProject({ + searchName, + organization, + userId, + }); + switch (result?.status) { + case "Project not found": + res.status(200).json({ + message: "Project not found", + }); + break; + case "User not found": + res.status(404).json({ + message: "User not found", + }); + break; + case "Success": + res.status(200).json({ + projectData: result.data, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "Unknown error", + }); + return; + } +}; diff --git a/src/api-server/V1/v1Controllers/projectController/v1projectController.ts b/src/api-server/V1/v1Controllers/projectController/v1projectController.ts new file mode 100644 index 0000000..659b186 --- /dev/null +++ b/src/api-server/V1/v1Controllers/projectController/v1projectController.ts @@ -0,0 +1,270 @@ +import { Request, Response } from "express"; +import { + createProject, + DeleteProject, + GetAllProjects, + updateProject, + viewProject, +} from "../../../../shared/services/v1Project/v1projectservice.ts"; +import { AuthenticatedRequest } from "../../../../shared/utils/token.ts"; + +export const createProjectController = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { userId, organization } = req.user || {}; + console.log("req.user: ", req.user); + const { projectUuid, thumbnail } = req.body; + if (!req.user || !req.user.userId || !req.user.organization) { + res.status(401).json({ message: "Unauthorized" }); + return; + } + if (!projectUuid || !thumbnail) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await createProject({ ...req.body, userId, organization }); + + switch (result.status) { + case "project_exists": + res.status(403).json({ + message: "Project already exists", + }); + break; + + case "user_not_found": + res.status(404).json({ + message: "User not found", + }); + break; + + case "Success": + res.status(201).json({ + message: "Project created Successfully", + projectId: result.project._id, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "Unknown error", + }); + return; + } +}; +export const GetProjects = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + 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", + }); + return; + } + const result = await GetAllProjects({ userId, organization, role }); + switch (result?.status) { + case "User not found": + res.status(404).json({ + message: "User not found", + }); + break; + + case "Success": + res.status(201).json({ + Projects: result?.Datas, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "Unknown error", + }); + return; + } +}; +export const RemoveProject = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { projectId } = req.params; + // const { organization, userId } = req.body; + const { organization, userId, role } = req.user || {}; + if ( + !req.user || + !req.user.userId || + !req.user.organization || + !req.user.role + ) { + res.status(401).json({ message: "Unauthorized" }); + return; + } + if (!projectId || !organization || !userId || !role) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await DeleteProject({ + projectId, + organization, + userId, + role, + }); + switch (result?.status) { + case "Project not found": + res.status(404).json({ + message: "Project not found", + }); + break; + case "User not found": + res.status(404).json({ + message: "User not found", + }); + break; + case "Success": + res.status(201).json({ + message: "Project Deleted Successfully", + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "Unknown error", + }); + return; + } +}; +export const updateProjectController = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { userId, organization, role } = req.user || {}; + const { projectId } = req.params; + const { projectName, thumbnail } = req.body; + if (!userId || !organization || !projectId || !role) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await updateProject({ + projectId, + organization, + userId, + projectName, + thumbnail, + role, + }); + switch (result?.status) { + case "Project not found": + res.status(404).json({ + message: "Project not found", + }); + break; + case "User not found": + res.status(404).json({ + message: "User not found", + }); + break; + case "Success": + res.status(200).json({ + message: "Project updated Successfully", + projectData: result.data, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "Unknown error", + }); + return; + } +}; +export const ViewData = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { organization, userId, role } = req.user || {}; + if ( + !req.user || + !req.user.userId || + !req.user.organization || + !req.user.role + ) { + res.status(401).json({ message: "Unauthorized" }); + return; + } + const { projectId } = req.params as { + projectId: string; + }; + if (!userId || !organization || !projectId || !role) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await viewProject({ + projectId, + organization, + userId, + role, + }); + switch (result?.status) { + case "Project not found": + res.status(404).json({ + message: "Project not found", + }); + break; + case "User not found": + res.status(404).json({ + message: "User not found", + }); + break; + case "Success": + res.status(200).json({ + projectData: result.data, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "Unknown error", + }); + return; + } +}; diff --git a/src/api-server/V1/v1Controllers/trashController/v1trashController.ts b/src/api-server/V1/v1Controllers/trashController/v1trashController.ts new file mode 100644 index 0000000..6350ff1 --- /dev/null +++ b/src/api-server/V1/v1Controllers/trashController/v1trashController.ts @@ -0,0 +1,99 @@ +import { Request, Response } from "express"; +import { + TrashDatas, + RestoreTrashData, +} from "../../../../shared/services/v1trash/v1trashservice.ts"; +import { AuthenticatedRequest } from "../../../../shared/utils/token.ts"; + +export const GetTrashList = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { organization, role, userId } = req.user || {}; + if (!organization || !role || !userId) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await TrashDatas({ organization, role, userId }); + + switch (result.status) { + case "Trash is Empty": + res.status(200).json({ + message: "Trash is Empty", + TrashDatas: [], + }); + break; + + case "Success": + res.status(200).json({ + TrashDatas: result.ListDatas, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + console.log("error: ", error); + res.status(500).json({ + message: "Unknown error", + }); + } +}; + +export const RestoreTrash = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { organization, role, userId } = req.user || {}; + const { projectId } = req.query as { + projectId: string; + }; + if (!organization || !projectId || !role || !userId) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await RestoreTrashData({ + organization, + projectId, + role, + userId, + }); + + switch (result.status) { + case "Project not found": + res.status(404).json({ + message: "Project not found", + }); + break; + case "Project Restore unsuccessfull": + res.status(200).json({ + message: "Project Restore unsuccessfull", + }); + break; + case "Project Restored successfully": + res.status(200).json({ + message: "Project Restored successfully", + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + console.log("error: ", error); + res.status(500).json({ + message: "Unknown error", + }); + } +}; diff --git a/src/api-server/V1/v1Routes/authRoutes.ts b/src/api-server/V1/v1Routes/authRoutes.ts index 34e5528..b95d384 100644 --- a/src/api-server/V1/v1Routes/authRoutes.ts +++ b/src/api-server/V1/v1Routes/authRoutes.ts @@ -7,20 +7,6 @@ import { SignupController, } from "../v1Controllers/authController/authControllers.ts"; import { versioncontroller } from "../v1Controllers/versionController/versioncontroller.ts"; -import { - createProjectController, - GetProjects, - RemoveProject, - updateProjectController, - ViewData, -} from "../../controller/project/projectController.ts"; -import { tokenValidator } from "../../../shared/utils/token.ts"; -import authorizedRoles from "../../../shared/middleware/rbacMiddleware.ts"; -import { recentDataController } from "../../controller/home/homeControllers.ts"; -import { - GetTrashList, - RestoreTrash, -} from "../../controller/trash/trashcontrollers.ts"; const Authrouter = express.Router(); Authrouter.post("/Auth/signup", SignupController); @@ -30,54 +16,4 @@ Authrouter.post("/Auth/forgetPassword", ForgetPasswordController); Authrouter.post("/Auth/reset-password/:resetToken", ResetPasswordController); Authrouter.post("/Auth/versionData", versioncontroller); -// project -Authrouter.post("/Auth/upsertProject", tokenValidator, createProjectController); -Authrouter.get( - "/Auth/Projects", - tokenValidator, - authorizedRoles("Admin", "User"), - GetProjects -); -Authrouter.patch( - "/Auth/Project/archive/:projectId", - tokenValidator, - authorizedRoles("Admin", "User"), - RemoveProject -); - -Authrouter.patch( - "/Auth/Project/modify", - tokenValidator, - authorizedRoles("Admin", "User"), - updateProjectController -); -Authrouter.get( - "/Auth/Project/view", - tokenValidator, - authorizedRoles("Admin", "User"), - ViewData -); - -//home-Page -Authrouter.get( - "/Auth/RecentlyViewed", - tokenValidator, - authorizedRoles("Admin", "User"), - recentDataController -); - -//trash -Authrouter.get( - "/Auth/Trash/Lists", - tokenValidator, - authorizedRoles("Admin", "User"), - GetTrashList -); - -Authrouter.patch( - "/Auth/restore", - tokenValidator, - authorizedRoles("Admin", "User"), - RestoreTrash -); export default Authrouter; diff --git a/src/api-server/V1/v1Routes/v1-homeRoutes.ts b/src/api-server/V1/v1Routes/v1-homeRoutes.ts new file mode 100644 index 0000000..6f32f0f --- /dev/null +++ b/src/api-server/V1/v1Routes/v1-homeRoutes.ts @@ -0,0 +1,16 @@ +import express from "express"; +import { tokenValidator } from "../../../shared/utils/token.ts"; +import authorizedRoles from "../../../shared/middleware/rbacMiddleware.ts"; +import { recentDataController } from "../../V1/v1Controllers/homeController/v1homeController.ts"; + +const v1homeRoutes = express.Router(); + +//home-Page +v1homeRoutes.get( + "/RecentlyViewed", + tokenValidator, + authorizedRoles("Admin", "User"), + recentDataController +); + +export default v1homeRoutes; diff --git a/src/api-server/V1/v1Routes/v1-projectRoutes.ts b/src/api-server/V1/v1Routes/v1-projectRoutes.ts new file mode 100644 index 0000000..2a7cd50 --- /dev/null +++ b/src/api-server/V1/v1Routes/v1-projectRoutes.ts @@ -0,0 +1,42 @@ +import express from "express"; +import { + createProjectController, + GetProjects, + RemoveProject, + updateProjectController, + 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("/upsertProject", tokenValidator, createProjectController); +v1projectRouter.get( + "/Projects", + tokenValidator, + authorizedRoles("Admin", "User"), + GetProjects +); +v1projectRouter.patch( + "/Project/archive/:projectId", + tokenValidator, + authorizedRoles("Admin", "User"), + RemoveProject +); + +v1projectRouter.patch( + "/Project/:projectId", + tokenValidator, + authorizedRoles("Admin", "User"), + updateProjectController +); +v1projectRouter.get( + "/Project/:projectId", + tokenValidator, + authorizedRoles("Admin", "User"), + ViewData +); + +export default v1projectRouter; diff --git a/src/api-server/V1/v1Routes/v1-trashRoutes.ts b/src/api-server/V1/v1Routes/v1-trashRoutes.ts new file mode 100644 index 0000000..d2603d1 --- /dev/null +++ b/src/api-server/V1/v1Routes/v1-trashRoutes.ts @@ -0,0 +1,25 @@ +import express from "express"; +import { tokenValidator } from "../../../shared/utils/token.ts"; +import authorizedRoles from "../../../shared/middleware/rbacMiddleware.ts"; +import { + GetTrashList, + RestoreTrash, +} 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 +); +export default v1TrashRoutes; diff --git a/src/api-server/app.ts b/src/api-server/app.ts index a3a8ae3..99ae949 100644 --- a/src/api-server/app.ts +++ b/src/api-server/app.ts @@ -22,6 +22,9 @@ import trashRouter from "./Routes/trashRoutes.ts"; import homePageRouter from "./Routes/homepageRoutes.ts"; import redis from "../shared/redis/redis.ts"; import Authrouter from "./V1/v1Routes/authRoutes.ts"; +import v1TrashRoutes from "./V1/v1Routes/v1-trashRoutes.ts"; +import v1homeRoutes from "./V1/v1Routes/v1-homeRoutes.ts"; +import v1projectRouter from "./V1/v1Routes/v1-projectRoutes.ts"; // import productFlowRoutes from "./Routes/productFlowRouts.ts"; redis; const app = express(); @@ -90,7 +93,10 @@ app.use("/api/v1", projectRouter); app.use("/api/v1", trashRouter); app.use("/api/v1", homePageRouter); -//New versions -app.use("/API/V1", Authrouter); +//New versions--based on the token and role based +app.use("/api", Authrouter); +app.use("/api/v2", v1projectRouter); +app.use("/api/v2", v1TrashRoutes); +app.use("/api/v2", v1homeRoutes); export default app; diff --git a/src/api-server/controller/home/homeControllers.ts b/src/api-server/controller/home/homeControllers.ts index 9907c9e..fd50cee 100644 --- a/src/api-server/controller/home/homeControllers.ts +++ b/src/api-server/controller/home/homeControllers.ts @@ -1,20 +1,23 @@ import { Request, Response } from "express"; -import { RecentlyAdded, searchProject, searchTrashProject } from "../../../shared/services/home/homeService.ts"; -import { AuthenticatedRequest } from "../../../shared/utils/token.ts"; +import { + RecentlyAdded, + searchProject, + searchTrashProject, +} from "../../../shared/services/home/homeService.ts"; export const recentDataController = async ( - req: AuthenticatedRequest, + req: Request, res: Response ): Promise => { try { - const { userId, organization,role } = req.user||{}; - if (!userId || !organization||!role) { + const { userId, organization } = req.params; + if (!userId || !organization) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await RecentlyAdded({ userId, organization,role }); + const result = await RecentlyAdded({ userId, organization }); switch (result.status) { case "User not found": @@ -45,7 +48,10 @@ export const recentDataController = async ( return; } }; -export const searchProjectController = async (req: Request, res: Response): Promise => { +export const searchProjectController = async ( + req: Request, + res: Response +): Promise => { try { const { searchName, organization, userId } = req.query as { organization: string; @@ -92,7 +98,10 @@ export const searchProjectController = async (req: Request, res: Response): Prom return; } }; -export const searchTrashProjectController = async (req: Request, res: Response): Promise => { +export const searchTrashProjectController = async ( + req: Request, + res: Response +): Promise => { try { const { searchName, organization, userId } = req.query as { organization: string; @@ -138,4 +147,4 @@ export const searchTrashProjectController = async (req: Request, res: Response): }); return; } -}; \ No newline at end of file +}; diff --git a/src/api-server/controller/project/projectController.ts b/src/api-server/controller/project/projectController.ts index c86a4ee..a061d11 100644 --- a/src/api-server/controller/project/projectController.ts +++ b/src/api-server/controller/project/projectController.ts @@ -6,27 +6,20 @@ import { updateProject, viewProject, } from "../../../shared/services/project/project-Services.ts"; -import { AuthenticatedRequest } from "../../../shared/utils/token.ts"; export const createProjectController = async ( - req: AuthenticatedRequest, + req: Request, res: Response ): Promise => { try { - const { userId, organization } = req.user || {}; - console.log("req.user: ", req.user); - const { projectUuid, thumbnail } = req.body; - if (!req.user || !req.user.userId || !req.user.organization) { - res.status(401).json({ message: "Unauthorized" }); - return; - } - if (!projectUuid || !thumbnail) { + const { projectUuid, userId, thumbnail, organization } = req.body; + if (!projectUuid || !userId || !thumbnail || !organization) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await createProject({ ...req.body, userId, organization }); + const result = await createProject(req.body); switch (result.status) { case "project_exists": @@ -61,19 +54,18 @@ export const createProjectController = async ( } }; export const GetProjects = async ( - req: AuthenticatedRequest, + req: Request, res: Response ): Promise => { try { - const { userId, organization, role } = req.user || {}; - // const { userId, organization } = req.params; - if (!userId || !organization || !role) { + const { userId, organization } = req.params; + if (!userId || !organization) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await GetAllProjects({ userId, organization, role }); + const result = await GetAllProjects({ userId, organization }); switch (result?.status) { case "User not found": res.status(404).json({ @@ -100,34 +92,19 @@ export const GetProjects = async ( } }; export const RemoveProject = async ( - req: AuthenticatedRequest, + req: Request, res: Response ): Promise => { try { const { projectId } = req.params; - // const { organization, userId } = req.body; - const { organization, userId, role } = req.user || {}; - if ( - !req.user || - !req.user.userId || - !req.user.organization || - !req.user.role - ) { - res.status(401).json({ message: "Unauthorized" }); - return; - } - if (!projectId || !organization || !userId || !role) { + const { organization, userId } = req.body; + if (!projectId || !organization || !userId) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await DeleteProject({ - projectId, - organization, - userId, - role, - }); + const result = await DeleteProject({ projectId, organization, userId }); switch (result?.status) { case "Project not found": res.status(404).json({ @@ -158,13 +135,13 @@ export const RemoveProject = async ( } }; export const updateProjectController = async ( - req: AuthenticatedRequest, + req: Request, res: Response ): Promise => { try { - const { userId, organization, role } = req.user || {}; - const { projectId, projectName, thumbnail } = req.body; - if (!userId || !organization || !projectId || !role) { + const { projectId, organization, projectName, thumbnail, userId } = + req.body; + if (!userId || !organization || !projectId) { res.status(400).json({ message: "All fields are required", }); @@ -176,7 +153,6 @@ export const updateProjectController = async ( userId, projectName, thumbnail, - role, }); switch (result?.status) { case "Project not found": @@ -208,25 +184,14 @@ export const updateProjectController = async ( return; } }; -export const ViewData = async ( - req: AuthenticatedRequest, - res: Response -): Promise => { +export const ViewData = async (req: Request, res: Response): Promise => { try { - const { organization, userId, role } = req.user || {}; - if ( - !req.user || - !req.user.userId || - !req.user.organization || - !req.user.role - ) { - res.status(401).json({ message: "Unauthorized" }); - return; - } - const { projectId } = req.query as { + const { projectId, organization, userId } = req.query as { + organization: string; projectId: string; + userId: string; }; - if (!userId || !organization || !projectId || !role) { + if (!userId || !organization || !projectId) { res.status(400).json({ message: "All fields are required", }); @@ -236,7 +201,6 @@ export const ViewData = async ( projectId, organization, userId, - role, }); switch (result?.status) { case "Project not found": diff --git a/src/api-server/controller/trash/trashcontrollers.ts b/src/api-server/controller/trash/trashcontrollers.ts index bfc54ee..7b02590 100644 --- a/src/api-server/controller/trash/trashcontrollers.ts +++ b/src/api-server/controller/trash/trashcontrollers.ts @@ -3,21 +3,20 @@ import { TrashDatas, RestoreTrashData, } from "../../../shared/services/trash/trashService.ts"; -import { AuthenticatedRequest } from "../../../shared/utils/token.ts"; export const GetTrashList = async ( - req: AuthenticatedRequest, + req: Request, res: Response ): Promise => { try { - const { organization, role, userId } = req.user || {}; - if (!organization || !role || !userId) { + const { organization } = req.query as { organization: string }; + if (!organization) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await TrashDatas({ organization, role, userId }); + const result = await TrashDatas({ organization }); switch (result.status) { case "Trash is Empty": @@ -29,6 +28,7 @@ export const GetTrashList = async ( case "Success": res.status(200).json({ + // message: "Project created Successfully", TrashDatas: result.ListDatas, }); break; @@ -47,26 +47,22 @@ export const GetTrashList = async ( }; export const RestoreTrash = async ( - req: AuthenticatedRequest, + req: Request, res: Response ): Promise => { try { - const { organization, role, userId } = req.user || {}; - const { projectId } = req.query as { + const { organization, projectId } = req.query as { + organization: string; projectId: string; }; - if (!organization || !projectId || !role || !userId) { + console.log("organization: ", organization); + if (!organization || !projectId) { res.status(400).json({ message: "All fields are required", }); return; } - const result = await RestoreTrashData({ - organization, - projectId, - role, - userId, - }); + const result = await RestoreTrashData({ organization, projectId }); switch (result.status) { case "Project not found": diff --git a/src/shared/services/helpers/ProjecthelperFn.ts b/src/shared/services/helpers/ProjecthelperFn.ts index 3ce8cc3..62ff0d2 100644 --- a/src/shared/services/helpers/ProjecthelperFn.ts +++ b/src/shared/services/helpers/ProjecthelperFn.ts @@ -2,7 +2,6 @@ import projectModel from "../../model/project/project-model.ts"; import userModel from "../../model/user-Model.ts"; import { Types } from "mongoose"; import versionModel from "../../model/version/versionModel.ts"; -import AuthModel from "../../V1Models/Auth/userAuthModel.ts"; export const existingProject = async ( projectUuid: string, organization: string, @@ -21,7 +20,7 @@ export const existingUser = async (userId: string, organization: string) => { console.log("Invalid ObjectId format"); return null; } - const userData = await AuthModel(organization).findOne({ + const userData = await userModel(organization).findOne({ _id: userId, }); return userData; diff --git a/src/shared/services/helpers/v1projecthelperFns.ts b/src/shared/services/helpers/v1projecthelperFns.ts new file mode 100644 index 0000000..0d4e0ac --- /dev/null +++ b/src/shared/services/helpers/v1projecthelperFns.ts @@ -0,0 +1,90 @@ +import projectModel from "../../V1Models/Project/project-model.ts"; +import { Types } from "mongoose"; +import versionModel from "../../V1Models/Version/versionModel.ts"; +import AuthModel from "../../V1Models/Auth/userAuthModel.ts"; +export const existingProject = async ( + projectUuid: string, + organization: string, + userId: string +) => { + const projectData = await projectModel(organization).findOne({ + projectUuid: projectUuid, + createdBy: userId, + isArchive: false, + }); + return projectData; +}; + +export const existingUser = async (userId: string, organization: string) => { + if (!Types.ObjectId.isValid(userId)) { + console.log("Invalid ObjectId format"); + return null; + } + const userData = await AuthModel(organization).findOne({ + _id: userId, + }); + return userData; +}; + +export const archiveProject = async ( + projectId: string, + organization: string +) => { + return await projectModel(organization).findByIdAndUpdate( + projectId, + { isArchive: true }, + { new: true } + ); +}; +export const previousVersion = async ( + projectId: string, + organization: string +) => { + const result = await versionModel(organization).findOne({ + projectId: projectId, + isArchive: false, + }); + // .sort({ version: -1 }); + return result; +}; +export const generateUntitledProjectName = async ( + organization: string, + userId: string +): Promise => { + const projects = await projectModel(organization) + .find({ + createdBy: userId, + isArchive: false, + projectName: { $regex: /^Untitled(?: \s?\d+)?$/, $options: "i" }, + }) + .select("projectName"); + + const usedNumbers = new Set(); + + for (const proj of projects) { + const match = proj.projectName.match(/^Untitled(?:\s?(\d+))?$/); + if (match) { + const num = match[1] ? parseInt(match[1], 10) : 0; + usedNumbers.add(num); + } + } + + let newNumber = 0; + while (usedNumbers.has(newNumber)) { + newNumber++; + } + + return newNumber === 0 ? "Untitled" : `Untitled ${newNumber}`; +}; +export const existingProjectById = async ( + projectId: string, + organization: string, + userId: string +) => { + const projectData = await projectModel(organization).findOne({ + _id: projectId, + createdBy: userId, + isArchive: false, + }); + return projectData; +}; diff --git a/src/shared/services/home/homeService.ts b/src/shared/services/home/homeService.ts index 758d174..4559d1c 100644 --- a/src/shared/services/home/homeService.ts +++ b/src/shared/services/home/homeService.ts @@ -1,12 +1,10 @@ import projectModel from "../../model/project/project-model.ts"; import userModel from "../../model/user-Model.ts"; -import UsersDataModel from "../../V1Models/Auth/user.ts"; import { existingUser } from "../helpers/ProjecthelperFn.ts"; interface IRecentData { organization: string; userId: string; - role: string; } interface IProject { _id: string; @@ -21,31 +19,26 @@ interface searchProjectInterface { userId: string; organization: string; } -interface RoleFilter { - isArchive: boolean; - createdBy?: string; -} export const RecentlyAdded = async (data: IRecentData) => { try { - const { userId, organization, role } = data; + const { userId, organization } = data; const userExisting = await existingUser(userId, organization); if (!userExisting) return { status: "User not found" }; - const userRecentData = await UsersDataModel(organization) - .findOne({ userId: userId, isArchive: false }) + const userRecentData = await userModel(organization) + .findOne({ _id: userId }) .populate({ path: "recentlyViewed", model: projectModel(organization), select: "_id", }); - let filter = { isArchive: false } as RoleFilter; - if (role === "User") { - filter.createdBy = userId; - } const populatedProjects = userRecentData.recentlyViewed as IProject[]; const RecentDatas = await Promise.all( populatedProjects.map(async (project) => { const projectExisting = await projectModel(organization) - .findOne(filter) + .findOne({ + _id: project._id, + isArchive: false, + }) .select("_id projectName createdBy thumbnail createdAt isViewed"); return projectExisting; }) diff --git a/src/shared/services/project/project-Services.ts b/src/shared/services/project/project-Services.ts index 17300cb..56c656d 100644 --- a/src/shared/services/project/project-Services.ts +++ b/src/shared/services/project/project-Services.ts @@ -1,8 +1,7 @@ -import { ObjectId } from "mongoose"; import projectModel from "../../model/project/project-model.ts"; import userModel from "../../model/user-Model.ts"; +import { Types } from "mongoose"; import versionModel from "../../model/version/versionModel.ts"; -import { AuthenticatedRequest } from "../../utils/token.ts"; import { existingProject, existingUser, @@ -10,7 +9,6 @@ import { previousVersion, generateUntitledProjectName, } from "../helpers/ProjecthelperFn.ts"; -import UsersDataModel from "../../V1Models/Auth/user.ts"; interface CreateProjectInput { projectName: string; projectUuid: string; @@ -26,26 +24,20 @@ interface updateProjectInput { thumbnail?: string; sharedUsers?: string[]; organization: string; - role: string; } interface GetProjectsInterface { userId: string; organization: string; - role: string; } interface ProjectInterface { projectId: string; userId: string; organization: string; - role: string; -} -interface RoleFilter { - isArchive: boolean; - createdBy?: string; } + export const createProject = async (data: CreateProjectInput) => { try { - const { thumbnail, sharedUsers, projectUuid, userId, organization } = data; + const { userId, thumbnail, sharedUsers, organization, projectUuid } = data; const userExisting = await existingUser(userId, organization); if (!userExisting) { return { @@ -102,16 +94,17 @@ export const createProject = async (data: CreateProjectInput) => { export const GetAllProjects = async (data: GetProjectsInterface) => { try { - const { userId, organization, role } = data; + const { userId, organization } = data; 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"); + .find({ + createdBy: userId, + isArchive: false, + }) + .select( + "_id projectName createdBy thumbnail createdAt projectUuid createdAt" + ); if (projectDatas) return { status: "Success", Datas: projectDatas }; } catch (error: unknown) { return { status: error }; @@ -120,17 +113,17 @@ export const GetAllProjects = async (data: GetProjectsInterface) => { export const DeleteProject = async (data: ProjectInterface) => { try { - const { projectId, organization, userId, role } = data; + const { projectId, organization, userId } = data; 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); + const existingProject = await projectModel(organization).findOne({ + _id: projectId, + createdBy: userId, + isArchive: false, + }); if (!existingProject) return { status: "Project not found" }; const updateProject = await projectModel(organization).findOneAndUpdate( - filter, + { _id: projectId, isArchive: false }, { isArchive: true, DeletedAt: new Date() }, { new: true } ); @@ -141,25 +134,24 @@ export const DeleteProject = async (data: ProjectInterface) => { }; export const updateProject = async (data: updateProjectInput) => { try { - const { projectId, organization, userId, projectName, thumbnail, role } = - data; + const { projectId, organization, userId, projectName, thumbnail } = data; 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); + const existingProject = await projectModel(organization).findOne({ + _id: projectId, + createdBy: userId, + isArchive: false, + }); if (!existingProject) return { status: "Project not found" }; if (projectName !== undefined) projectName; if (thumbnail !== undefined) thumbnail; const updateProject = await projectModel(organization) .findOneAndUpdate( - filter, + { _id: projectId, isArchive: false }, { projectName: projectName, thumbnail: thumbnail }, { new: true } ) - .select("_id projectName createdBy thumbnail createdAt"); + .select("_id projectName createdBy thumbnail createdAt projectUuid"); if (updateProject) return { status: "Success", data: updateProject }; } catch (error: unknown) { return { status: error }; @@ -168,23 +160,18 @@ export const updateProject = async (data: updateProjectInput) => { const maxLength: number = 6; export const viewProject = async (data: ProjectInterface) => { try { - const { projectId, organization, userId, role } = data; + const { projectId, organization, userId } = data; const userExisting = await existingUser(userId, organization); if (!userExisting) return { status: "User not found" }; - const RecentUserDoc = await UsersDataModel(organization).findOne({ - userId: userId, + const existingProject = await projectModel(organization).findOne({ + _id: projectId, + createdBy: userId, 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 || []; - if (RecentUserDoc?.recentlyViewed.length === 0) { + const newArr = userExisting?.recentlyViewed || []; + if (userExisting?.recentlyViewed.length === 0) { newArr.push(projectId); - await RecentUserDoc.save(); } else { const index = newArr.indexOf(projectId); if (index !== -1) { @@ -196,13 +183,21 @@ export const viewProject = async (data: ProjectInterface) => { newArr.pop(); } } - await UsersDataModel(organization).updateOne( + await userModel(organization).updateOne( { _id: userId }, { recentlyViewed: newArr }, { new: true } ); const projectData = await projectModel(organization) - .findOneAndUpdate(filter, { isViewed: Date.now() }, { new: true }) + .findOneAndUpdate( + { + _id: projectId, + createdBy: userId, + isArchive: false, + }, + { isViewed: Date.now() }, + { new: true } + ) .select("_id projectName createdBy thumbnail createdAt"); return { status: "Success", data: projectData }; } catch (error: unknown) { diff --git a/src/shared/services/trash/trashService.ts b/src/shared/services/trash/trashService.ts index ae833ff..2976f95 100644 --- a/src/shared/services/trash/trashService.ts +++ b/src/shared/services/trash/trashService.ts @@ -1,27 +1,19 @@ import projectModel from "../../model/project/project-model.ts"; interface IOrg { organization: string; - role: string; - userId: string; } interface IRestore { projectId: string; organization: string; - role: string; - userId: string; -} -interface RoleFilter { - isArchive: boolean; - createdBy?: string; } 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 TrashLists = await projectModel(organization).find(filter); + const { organization } = data; + + const TrashLists = await projectModel(organization).find({ + isArchive: true, + isDeleted: false, + }); if (!TrashLists) return { staus: "Trash is Empty" }; const TrashDocs: any[] = []; for (const Trash of TrashLists) { @@ -55,15 +47,14 @@ export const TrashDatas = async (data: IOrg) => { }; export const RestoreTrashData = async (data: IRestore) => { try { - const { projectId, organization, role, userId } = data; - let filter = { isArchive: true, _id: projectId } as RoleFilter; - if (role === "User") { - filter.createdBy = userId; - } - const findProject = await projectModel(organization).findOne(filter); + const { projectId, organization } = data; + const findProject = await projectModel(organization).findOne({ + _id: projectId, + isArchive: true, + }); if (!findProject) return { status: "Project not found" }; const restoreData = await projectModel(organization).findOneAndUpdate( - filter, + { _id: projectId, isArchive: true }, { isArchive: false, DeletedAt: null }, { new: true } ); diff --git a/src/shared/services/v1Project/v1projectservice.ts b/src/shared/services/v1Project/v1projectservice.ts new file mode 100644 index 0000000..c09a2b4 --- /dev/null +++ b/src/shared/services/v1Project/v1projectservice.ts @@ -0,0 +1,208 @@ +import projectModel from "../../V1Models/Project/project-model.ts"; +import versionModel from "../../V1Models/Version/versionModel.ts"; +import { + existingProject, + existingUser, + archiveProject, + previousVersion, + generateUntitledProjectName, +} from "../helpers/v1projecthelperFns.ts"; +import UsersDataModel from "../../V1Models/Auth/user.ts"; +interface CreateProjectInput { + projectName: string; + projectUuid: string; + userId: string; // user ID + thumbnail?: string; + sharedUsers?: string[]; + organization: string; +} +interface updateProjectInput { + projectName: string; + projectId: string; + userId: string; // user ID + thumbnail?: string; + sharedUsers?: string[]; + organization: string; + role: string; +} +interface GetProjectsInterface { + userId: string; + organization: string; + role: string; +} +interface ProjectInterface { + projectId: string; + userId: string; + organization: string; + role: string; +} +interface RoleFilter { + isArchive: boolean; + createdBy?: string; +} +export const createProject = async (data: CreateProjectInput) => { + try { + const { thumbnail, sharedUsers, projectUuid, userId, organization } = data; + const userExisting = await existingUser(userId, organization); + if (!userExisting) { + return { + status: "user_not_found", + }; + } + const projectExisting = await existingProject( + projectUuid, + organization, + userId + ); + + if (projectExisting) { + return { + status: "project_exists", + project: projectExisting, + }; + } + const newProjectName = await generateUntitledProjectName( + organization, + userId + ); + const project = await projectModel(organization).create({ + projectName: newProjectName, + projectUuid: projectUuid, + createdBy: userId, + thumbnail: thumbnail, + sharedUsers: sharedUsers || [], + isArchive: false, + }); + const versionData = await previousVersion(project._id, organization); + if (!versionData || versionData.length === 0) { + const newVersion = await versionModel(organization).create({ + projectId: project._id, + createdBy: userId, + version: 0.0, + }); + await projectModel(organization).findByIdAndUpdate( + { _id: project._id, isArchive: false }, + { total_versions: `v-${newVersion.version.toFixed(2)}` } + ); + } + return { + status: "Success", + project: project, + }; + } catch (error) { + console.log("error: ", error); + return { + status: error, + }; + } +}; + +export const GetAllProjects = async (data: GetProjectsInterface) => { + try { + const { userId, organization, role } = data; + 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"); + if (projectDatas) return { status: "Success", Datas: projectDatas }; + } catch (error: unknown) { + return { status: error }; + } +}; + +export const DeleteProject = async (data: ProjectInterface) => { + try { + const { projectId, organization, userId, role } = data; + 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" }; + const updateProject = await projectModel(organization).findOneAndUpdate( + filter, + { isArchive: true, DeletedAt: new Date() }, + { new: true } + ); + if (updateProject) return { status: "Success", project: updateProject }; + } catch (error: unknown) { + return { status: error }; + } +}; +export const updateProject = async (data: updateProjectInput) => { + try { + const { projectId, organization, userId, projectName, thumbnail, role } = + data; + 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; + if (thumbnail !== undefined) thumbnail; + const updateProject = await projectModel(organization) + .findOneAndUpdate( + filter, + { projectName: projectName, thumbnail: thumbnail }, + { new: true } + ) + .select("_id projectName createdBy thumbnail createdAt"); + if (updateProject) return { status: "Success", data: updateProject }; + } catch (error: unknown) { + return { status: error }; + } +}; +const maxLength: number = 6; +export const viewProject = async (data: ProjectInterface) => { + try { + const { projectId, organization, userId, role } = data; + const userExisting = await existingUser(userId, organization); + if (!userExisting) return { status: "User not found" }; + const RecentUserDoc = await UsersDataModel(organization).findOne({ + userId: userId, + 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 || []; + if (RecentUserDoc?.recentlyViewed.length === 0) { + newArr.push(projectId); + await RecentUserDoc.save(); + } else { + const index = newArr.indexOf(projectId); + if (index !== -1) { + newArr.splice(index, 1); + } + newArr.unshift(projectId); + + if (newArr.length > maxLength) { + newArr.pop(); + } + } + await UsersDataModel(organization).updateOne( + { _id: userId }, + { recentlyViewed: newArr }, + { new: true } + ); + const projectData = await projectModel(organization) + .findOneAndUpdate(filter, { isViewed: Date.now() }, { new: true }) + .select("_id projectName createdBy thumbnail createdAt"); + return { status: "Success", data: projectData }; + } catch (error: unknown) { + return { status: error }; + } +}; diff --git a/src/shared/services/v1home/v1homeservice.ts b/src/shared/services/v1home/v1homeservice.ts new file mode 100644 index 0000000..9ff155e --- /dev/null +++ b/src/shared/services/v1home/v1homeservice.ts @@ -0,0 +1,92 @@ +import projectModel from "../../V1Models/Project/project-model.ts"; +import userModel from "../../model/user-Model.ts"; +import UsersDataModel from "../../V1Models/Auth/user.ts"; +import { existingUser } from "../helpers/ProjecthelperFn.ts"; + +interface IRecentData { + organization: string; + userId: string; + role: string; +} +interface IProject { + _id: string; + projectName: string; + createdBy: string; + thumbnail?: string; + createdAt: Date; + isViewed?: number; +} +interface searchProjectInterface { + searchName: string; + userId: string; + organization: string; +} +interface RoleFilter { + isArchive: boolean; + createdBy?: string; +} +export const RecentlyAdded = async (data: IRecentData) => { + try { + const { userId, organization, role } = data; + const userExisting = await existingUser(userId, organization); + if (!userExisting) return { status: "User not found" }; + const userRecentData = await UsersDataModel(organization) + .findOne({ userId: userId, isArchive: false }) + .populate({ + path: "recentlyViewed", + model: projectModel(organization), + select: "_id", + }); + let filter = { isArchive: false } as RoleFilter; + if (role === "User") { + filter.createdBy = userId; + } + const populatedProjects = userRecentData.recentlyViewed as IProject[]; + const RecentDatas = await Promise.all( + populatedProjects.map(async (project) => { + const projectExisting = await projectModel(organization) + .findOne(filter) + .select("_id projectName createdBy thumbnail createdAt isViewed"); + return projectExisting; + }) + ); + + const filteredProjects = RecentDatas.filter(Boolean); + return { status: "Success", data: filteredProjects }; + } catch (error) { + return { status: error }; + } +}; +export const searchProject = async (data: searchProjectInterface) => { + try { + const { userId, organization, searchName } = data; + 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 + isArchive: false, + }); + if (!findprojectName || findprojectName.length === 0) + return { status: "Project not found" }; + return { status: "Success", data: findprojectName }; + } catch (error: unknown) { + return { status: error }; + } +}; +export const searchTrashProject = async (data: searchProjectInterface) => { + try { + const { userId, organization, searchName } = data; + const userExisting = await existingUser(userId, organization); + if (!userExisting) return { status: "User not found" }; + const findprojectName = await projectModel(organization).find({ + projectName: { $regex: `${searchName}`, $options: "i" }, + isArchive: true, + isDeleted: false, + }); + if (!findprojectName || findprojectName.length === 0) + return { status: "Project not found" }; + return { status: "Success", data: findprojectName }; + } catch (error: unknown) { + return { status: error }; + } +}; diff --git a/src/shared/services/v1trash/v1trashservice.ts b/src/shared/services/v1trash/v1trashservice.ts new file mode 100644 index 0000000..4e68fe7 --- /dev/null +++ b/src/shared/services/v1trash/v1trashservice.ts @@ -0,0 +1,75 @@ +import projectModel from "../../V1Models/Project/project-model.ts"; +interface IOrg { + organization: string; + role: string; + userId: string; +} +interface IRestore { + projectId: string; + organization: string; + role: string; + userId: string; +} +interface RoleFilter { + isArchive: boolean; + createdBy?: string; +} +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 TrashLists = await projectModel(organization).find(filter); + if (!TrashLists) return { staus: "Trash is Empty" }; + const TrashDocs: any[] = []; + for (const Trash of TrashLists) { + const now = new Date(); + const deletedPlus15 = new Date( + Trash.DeletedAt.getTime() + 15 * 24 * 60 * 60 * 1000 + ); + if (now > deletedPlus15) { + console.log("now > deletedPlus15: ", now > deletedPlus15); + await projectModel(organization).updateOne( + { _id: Trash._id }, + { $set: { isDeleted: true } } + ); + } else { + TrashDocs.push(Trash); + } + } + const ListDatas = TrashDocs.map((data) => { + return { + projectName: data.projectName, + thumbnail: data.thumbnail, + createdBy: data.createdBy, + _id: data._id, + }; + }); + + return { status: "Success", ListDatas }; + } catch (error) { + return { status: error }; + } +}; +export const RestoreTrashData = async (data: IRestore) => { + try { + const { projectId, organization, role, userId } = data; + 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( + filter, + { isArchive: false, DeletedAt: null }, + { new: true } + ); + if (!restoreData) return { status: "Project Restore unsuccessfull" }; + return { status: "Project Restored successfully" }; + } catch (error) { + return { status: error }; + } +}; diff --git a/src/shared/services/version/versionService.ts b/src/shared/services/version/versionService.ts index fbd0bb2..c8bef9c 100644 --- a/src/shared/services/version/versionService.ts +++ b/src/shared/services/version/versionService.ts @@ -59,10 +59,10 @@ class VersionService { // Get all assets from previous version const previousVersion = parseFloat((newVersion.version - 0.1).toFixed(1)); const previousVersionDoc = await versionModel(db).findOne({ - projectId, - version: previousVersion, + projectId, + version: previousVersion, }); - console.log('previousVersionDoc: ', previousVersionDoc); + console.log("previousVersionDoc: ", previousVersionDoc); let previousAssets = []; if (previousVersionDoc) { @@ -75,8 +75,8 @@ class VersionService { // Copy assets to new version const newAssets = await Promise.all( - previousAssets.map(async (asset) => { - console.log('previousAssets: ', previousAssets); + previousAssets.map(async (asset) => { + console.log("previousAssets: ", previousAssets); const newAsset = { ...asset.toObject(), versionId: newVersion._id }; delete newAsset._id; return await assetModel(db).create(newAsset); From fd578df59f476fa10dc9fba8d07e4eba996d80a4 Mon Sep 17 00:00:00 2001 From: Nivetharamesh Date: Mon, 26 May 2025 15:08:22 +0530 Subject: [PATCH 6/6] api/v2 routing added for the userDatas --- .../authController/authControllers.ts | 2 + .../builderController/v1cameraController.ts | 115 ++++++++++++++++++ src/api-server/app.ts | 2 +- src/shared/services/builder/cameraService.ts | 14 +-- 4 files changed, 125 insertions(+), 8 deletions(-) create mode 100644 src/api-server/V1/v1Controllers/builderController/v1cameraController.ts diff --git a/src/api-server/V1/v1Controllers/authController/authControllers.ts b/src/api-server/V1/v1Controllers/authController/authControllers.ts index 710b4d4..2a6bdb7 100644 --- a/src/api-server/V1/v1Controllers/authController/authControllers.ts +++ b/src/api-server/V1/v1Controllers/authController/authControllers.ts @@ -52,6 +52,7 @@ export const SignInController = async ( ): Promise => { try { const { Email, Password, fingerprint } = req.body; + console.log("req.body: ", req.body); if (!fingerprint || !Email || !Password) { res.status(400).json({ message: "All fields are required", @@ -74,6 +75,7 @@ export const SignInController = async ( case "Already LoggedIn on another browser....Please logout!!!": res.status(403).json({ message: "Already LoggedIn on another browser....Please logout!!!", + ForceLogoutData: result.data, }); break; diff --git a/src/api-server/V1/v1Controllers/builderController/v1cameraController.ts b/src/api-server/V1/v1Controllers/builderController/v1cameraController.ts new file mode 100644 index 0000000..272938b --- /dev/null +++ b/src/api-server/V1/v1Controllers/builderController/v1cameraController.ts @@ -0,0 +1,115 @@ +import { Request, Response } from "express"; + +import { AuthenticatedRequest } from "../../../../shared/utils/token.ts"; +import { + GetCamers, + SetCamera, +} from "../../../../shared/services/builder/cameraService.ts"; + +export const SetNewCamera = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { organization, role, userId } = req.user || {}; + const { position, target, rotation, projectId, versionId } = req.body; + if ( + !organization || + !role || + !userId || + !position || + !target || + !rotation || + !projectId || + !versionId + ) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const data = { + position, + target, + rotation, + projectId, + versionId, + organization, + role, + userId, + }; + const result = await SetCamera(data); + + switch (result.status) { + case "Project not found": + res.status(404).json({ + message: "Project not found", + TrashDatas: [], + }); + break; + + case "Update Success": + res.status(200).json({ + TrashDatas: result.data, + }); + break; + case "Success": + res.status(200).json({ + TrashDatas: result.data, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + console.log("error: ", error); + res.status(500).json({ + message: "Unknown error", + }); + } +}; +export const CameraList = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { organization, role, userId } = req.user || {}; + if (!organization || !role || !userId) { + res.status(400).json({ + message: "All fields are required", + }); + return; + } + const result = await GetCamers({ + organization, + role, + userId, + }); + + switch (result.status) { + case "Project not found": + res.status(404).json({ + message: "Project not found", + TrashDatas: [], + }); + break; + case "Success": + res.status(200).json({ + TrashDatas: result.data, + }); + break; + default: + res.status(500).json({ + message: "Internal server error", + }); + break; + } + } catch (error) { + res.status(500).json({ + message: "Unknown error", + }); + } +}; diff --git a/src/api-server/app.ts b/src/api-server/app.ts index 99ae949..eeaa666 100644 --- a/src/api-server/app.ts +++ b/src/api-server/app.ts @@ -94,7 +94,7 @@ app.use("/api/v1", trashRouter); app.use("/api/v1", homePageRouter); //New versions--based on the token and role based -app.use("/api", Authrouter); +app.use("/api/v2", Authrouter); app.use("/api/v2", v1projectRouter); app.use("/api/v2", v1TrashRoutes); app.use("/api/v2", v1homeRoutes); diff --git a/src/shared/services/builder/cameraService.ts b/src/shared/services/builder/cameraService.ts index 94c1d7c..4256e0b 100644 --- a/src/shared/services/builder/cameraService.ts +++ b/src/shared/services/builder/cameraService.ts @@ -1,11 +1,9 @@ -import projectModel from "../../model/project/project-model.ts"; -import userModel from "../../model/user-Model.ts"; -import versionModel from "../../model/version/versionModel.ts"; import UsersDataModel from "../../V1Models/Auth/user.ts"; import cameraModel from "../../V1Models/Builder/cameraModel.ts"; -import { existingProjectById } from "../helpers/ProjecthelperFn.ts"; +import { existingProjectById } from "../helpers/v1projecthelperFns.ts"; interface IcameraData { userId: string; + role: string; position: Object; target: Object; rotation: Object; @@ -16,6 +14,7 @@ interface IcameraData { interface IgetCameras { organization: string; userId?: string; + role: string; } export const SetCamera = async ( data: IcameraData @@ -23,6 +22,7 @@ export const SetCamera = async ( try { const { userId, + role, position, target, rotation, @@ -65,7 +65,7 @@ export const SetCamera = async ( }); return { - status: "Creation Success", + status: "Success", data: newCamera, }; } @@ -84,13 +84,13 @@ export const SetCamera = async ( export const GetCamers = async ( data: IgetCameras ): Promise<{ status: string; data?: Object }> => { - const { userId, organization } = data; + const { userId, organization, role } = data; try { const findCamera = await cameraModel(organization).findOne({ userId: userId, }); if (!findCamera) { - return { status: "user not found" }; + return { status: "Camera not found" }; } else { return { status: "Success", data: findCamera }; }