diff --git a/.env b/.env index ddea283..66ecf8a 100644 --- a/.env +++ b/.env @@ -9,7 +9,7 @@ JWT_SECRET="Schema_Studio" REFRESH_JWT_SECRET="Schema_Studio" REDIS_ENV= false -REDIS_LOCAL = 192.168.0.203 +REDIS_LOCAL = 192.168.0.204 REDIS_PORT=6379 EMAIL_USER=nivetha@hexrfactory.com diff --git a/src/api-server/controller/authController.ts b/src/api-server/controller/authController.ts index c9c5347..e04c3c5 100644 --- a/src/api-server/controller/authController.ts +++ b/src/api-server/controller/authController.ts @@ -11,9 +11,26 @@ export const signupController = async ( ): Promise => { try { const { userName, email, password } = req.body; - if (!userName || !email || !password) { + // if (!userName || !email || !password) { + // res.status(400).json({ + // message: "All fields are required", + // }); + // return; + // } + + const missing = Object.entries({ + userName, + email, + password, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } @@ -64,9 +81,25 @@ export const signinController = async ( ): Promise => { try { const { email, password } = req.body; - if (!email || !password) { + // if (!email || !password) { + // res.status(400).json({ + // message: "All fields are required", + // }); + // return; + // } + + const missing = Object.entries({ + email, + password, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } @@ -112,9 +145,24 @@ export const forgetPasswordController = async ( ): Promise => { try { const { email } = req.body; - if (!email) { + // if (!email) { + // res.status(400).json({ + // message: "All fields are required", + // }); + // return; + // } + + const missing = Object.entries({ + email, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } diff --git a/src/api-server/controller/collectionNodeController.ts b/src/api-server/controller/collectionNodeController.ts index c83d577..4c2e076 100644 --- a/src/api-server/controller/collectionNodeController.ts +++ b/src/api-server/controller/collectionNodeController.ts @@ -21,28 +21,34 @@ export const NodeCreationController = async ( try { const { organization, userId } = req.user || {}; const { projectId, position, collectionName, type } = req.body; - if ( - !organization || - !projectId || - !position || - !userId || - !collectionName - ) { + const missing = Object.entries({ + organization, + projectId, + position, + userId, + collectionName, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, position, type, collectionName, - userId, + userId: userId as string, }; const result = await Nodecreation(data); - console.log("result: ", result); + console.log("result:nodecreatge ", result); switch (result.status) { case "User not found": @@ -66,7 +72,8 @@ export const NodeCreationController = async ( case "Success": res.status(200).json({ message: "Node created successfully", - collectionNodeId: result.data, + // collectionNodeId: result.data, + data: result.data, }); break; case "Validation Error": @@ -85,15 +92,15 @@ export const NodeCreationController = async ( } }; +//casting error handled and missing fields handling updated for testing export const updateCollectionController = async ( req: AuthenticatedRequest, res: Response ): Promise => { try { const { organization, userId } = req.user || {}; - const { collectionNodeId } = req.params + const { collectionNodeId, projectId } = req.params; const { - projectId, collectionName, position, backgroundColor, @@ -106,22 +113,27 @@ export const updateCollectionController = async ( borderThickness, cornerRadius, } = req.body; - if ( - !organization || - !projectId || - !userId || - !collectionName || - !collectionNodeId - ) { + const missing = Object.entries({ + organization, + projectId, + userId, + collectionNodeId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - userId, + userId: userId as string, backgroundColor, borderColor, fontColor, @@ -136,7 +148,6 @@ export const updateCollectionController = async ( position, }; const result = await updatecollection(data); - switch (result.status) { case "User not found": res.status(404).json({ message: "User not found" }); @@ -146,6 +157,9 @@ export const updateCollectionController = async ( message: "project not found", }); break; + case "Invalid ID": + res.status(400).json({ message: result.data || "Invalid ID provided" }); + break; case "Collection not found": res.status(200).json({ message: "Collection not found", @@ -176,16 +190,27 @@ export const CollectionDatas = async ( try { const { organization, userId } = req.user || {}; const { projectId, collectionNodeId } = req.params; - if (!organization || !projectId || !collectionNodeId || !userId) { + const missing = Object.entries({ + organization, + projectId, + userId, + collectionNodeId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - userId, + userId: userId as string, collectionNodeId, }; const result = await GetcollectionNode(data); @@ -227,16 +252,27 @@ export const graphicDatas = async ( try { const { organization, userId } = req.user || {}; const { projectId, collectionNodeId } = req.params; - if (!organization || !projectId || !collectionNodeId || !userId) { + const missing = Object.entries({ + organization, + projectId, + userId, + collectionNodeId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - userId, + userId: userId as string, collectionNodeId, }; const result = await GetcollectionGraphicData(data); @@ -278,16 +314,27 @@ export const DeleteCollectionsController = async ( try { const { organization, userId } = req.user || {}; const { projectId, collectionNodeId } = req.params; - if (!organization || !projectId || !collectionNodeId || !userId) { + const missing = Object.entries({ + organization, + projectId, + userId, + collectionNodeId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - userId, + userId: userId as string, collectionNodeId, }; const result = await delCollection(data); @@ -329,16 +376,27 @@ export const DuplicateNodeCollectionController = async ( const { organization, userId } = req.user || {}; const { collectionNodeId } = req.params; const { projectId, collectionName, position, attributes } = req.body; - if (!organization || !projectId || !collectionNodeId || !userId) { + const missing = Object.entries({ + organization, + projectId, + userId, + collectionNodeId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - userId, + userId: organization as string, collectionName, position, attributes, @@ -382,19 +440,28 @@ export const NodesCollectionsBasedOnproject = async ( try { const { organization, userId } = req.user || {}; const { projectId } = req.params; - if (!organization || !projectId || !userId) { + const missing = Object.entries({ + organization, + projectId, + userId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - userId, + userId: userId as string, }; const result = await GetNodesInProject(data); - console.log("resultdssa: ", result); switch (result.status) { case "User not found": @@ -435,27 +502,33 @@ export const AddAttributesController = async ( const { organization, userId } = req.user || {}; // const { collectionNodeId } = req.params; const { projectId, attributes, collectionNodeId } = req.body; - if ( - !organization || - !projectId || - !attributes || - !userId || - !collectionNodeId - ) { + const missing = Object.entries({ + organization, + projectId, + userId, + attributes, + collectionNodeId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - userId, + userId: userId as string, collectionNodeId, attributes, }; const result = await addAttributes(data); - console.log("result: ", result); + console.log("result:addattri ", result); switch (result.status) { case "User not found": res.status(404).json({ message: "User not found" }); @@ -470,6 +543,9 @@ export const AddAttributesController = async ( message: "Subcollection already added for the object data", }); break; + case "Invalid ObjectId": + res.status(400).json({ message: "Invalid Id" }); + break; case "Collection not found": res.status(200).json({ message: "Collection not found", @@ -478,6 +554,7 @@ export const AddAttributesController = async ( case "Success": res.status(200).json({ message: "collection Attributes Added", + fieldId: result.data, }); break; default: @@ -499,45 +576,34 @@ export const updateAttributesCollections = async ( ): Promise => { try { const { organization, userId } = req.user || {}; - const { collectionNodeId, attributeId } = req.params; - const { + const { collectionNodeId } = req.params; + const { projectId, attributes } = req.body; + const missing = Object.entries({ + organization, projectId, - required, - primary, - defaultValue, - unique, - index, - key, - type, - } = req.body; - if ( - !organization || - !userId || - !projectId || - !collectionNodeId || - !attributeId - ) { + userId, + collectionNodeId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - primary, - userId, + userId: userId as string, collectionNodeId, - attributeId, - required, - defaultValue, - unique, - index, - key, - type, + attributes, }; const result = await UpdateAttributes(data); - console.log("result: ", result); + console.log("result:d ", result); switch (result.status) { case "User not found": @@ -576,27 +642,34 @@ export const delAttributesCollections = async ( try { const { organization, userId } = req.user || {}; const { collectionNodeId } = req.params; - const { projectId, AttributeId } = req.body; - if ( - !organization || - !projectId || - !collectionNodeId || - !AttributeId || - !userId - ) { + const { projectId, fieldId } = req.body; + const missing = Object.entries({ + organization, + projectId, + userId, + collectionNodeId, + fieldId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, - userId, + organization: organization as string, + userId: userId as string, projectId, collectionNodeId, - AttributeId, + fieldId, }; const result = await DelAttributes(data); + console.log("result:delatt ", result); switch (result.status) { case "User not found": res.status(404).json({ message: "User not found" }); @@ -607,9 +680,13 @@ export const delAttributesCollections = async ( }); break; case "Collection not found": - res.status(200).json({ + res.status(404).json({ message: "Collection not found", - Collections: result.data, + }); + break; + case "Attribute not found": + res.status(200).json({ + message: "field not found", }); break; case "Success": @@ -635,27 +712,45 @@ export const duplicateAttributesCollections = async ( try { const { organization, userId } = req.user || {}; const { projectId, attrKey, collectionNodeId } = req.body; - if ( - !organization || - !projectId || - !collectionNodeId || - !attrKey || - !userId - ) { + // if ( + // !organization || + // !projectId || + // !collectionNodeId || + // !attrKey || + // !userId + // ) { + // res.status(400).json({ + // message: "All fields are required", + // }); + // return; + // } + const missing = Object.entries({ + organization, + projectId, + userId, + collectionNodeId, + attrKey, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, - userId, + organization: organization as string, + userId: userId as string, projectId, collectionNodeId, attrKey, }; const result = await DuplicateAttributes(data); - console.log("result: ", result); + console.log("result:duplicateatt ", result); switch (result.status) { case "User not found": res.status(404).json({ message: "User not found" }); @@ -701,16 +796,27 @@ export const collectionListsController = async ( try { const { organization, userId } = req.user || {}; const { projectId } = req.params; - if (!organization || !projectId || !userId) { + + const missing = Object.entries({ + organization, + projectId, + userId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - userId, + userId: userId as string, }; const result = await GetcollectionLists(data); diff --git a/src/api-server/controller/dummyController.ts b/src/api-server/controller/dummyController.ts index f3ba3d1..7155235 100644 --- a/src/api-server/controller/dummyController.ts +++ b/src/api-server/controller/dummyController.ts @@ -445,7 +445,7 @@ export const AddAttributesControllerdummy = async ( // ): Promise => { // try { // const { organization, userId } = req.user || {}; -// const { collectionNodeId, attributeId } = req.params; +// const { collectionNodeId, fieldId } = req.params; // const { projectId, required, defaultValue, unique, index, key, type } = // req.body; // if ( @@ -453,7 +453,7 @@ export const AddAttributesControllerdummy = async ( // !userId || // !projectId || // !collectionNodeId || -// !attributeId +// !fieldId // ) { // res.status(400).json({ // message: "All fields are required", @@ -465,7 +465,7 @@ export const AddAttributesControllerdummy = async ( // projectId, // userId, // collectionNodeId, -// attributeId, +// fieldId, // required, // defaultValue, // unique, @@ -508,12 +508,12 @@ export const AddAttributesControllerdummy = async ( // try { // const { organization, userId } = req.user || {}; // const { collectionNodeId } = req.params; -// const { projectId, AttributeId } = req.body; +// const { projectId, fieldId } = req.body; // if ( // !organization || // !projectId || // !collectionNodeId || -// !AttributeId || +// !fieldId || // !userId // ) { // res.status(400).json({ @@ -526,7 +526,7 @@ export const AddAttributesControllerdummy = async ( // userId, // projectId, // collectionNodeId, -// AttributeId, +// fieldId, // }; // const result = await DelAttributes(data); // switch (result.status) { diff --git a/src/api-server/controller/edgeController.ts b/src/api-server/controller/edgeController.ts index 3de2970..9bd507b 100644 --- a/src/api-server/controller/edgeController.ts +++ b/src/api-server/controller/edgeController.ts @@ -1,4 +1,4 @@ -import { Request, Response } from "express"; +import { Response } from "express"; import { Alledges, deleteEdge, @@ -12,19 +12,31 @@ export const edgeCreationController = async ( try { const { organization, userId } = req.user || {}; const { projectId, from, to, cardinality } = req.body; - if (!organization || !projectId || !from || !to || !userId) { + const missing = Object.entries({ + organization, + projectId, + userId, + from, + to, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, from, to, cardinality, - userId, + userId: userId as string, }; const result = await edgecreation(data); @@ -52,6 +64,9 @@ export const edgeCreationController = async ( message: "Field already exists", }); break; + case "Validation Error": + res.status(400).json({ message: result.data || "Validation Error" }); + break; case "Success": res.status(200).json({ message: "Edge created successfully", @@ -77,16 +92,26 @@ export const allEdgesController = async ( try { const { organization, userId } = req.user || {}; const { projectId } = req.params; - if (!organization || !projectId || !userId) { + const missing = Object.entries({ + organization, + projectId, + userId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - userId, + userId: userId as string, }; const result = await Alledges(data); @@ -129,17 +154,28 @@ export const deleteEdgesController = async ( try { const { organization, userId } = req.user || {}; const { projectId, edgeId } = req.params; - if (!organization || !projectId || !edgeId || !userId) { + const missing = Object.entries({ + organization, + projectId, + userId, + edgeId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, edgeId, - userId, + userId: userId as string, }; const result = await deleteEdge(data); diff --git a/src/api-server/controller/groupController.ts b/src/api-server/controller/groupController.ts new file mode 100644 index 0000000..d669229 --- /dev/null +++ b/src/api-server/controller/groupController.ts @@ -0,0 +1,82 @@ +import { Request, Response } from "express"; +import { AuthenticatedRequest } from "../../shared/utils/token"; +import { groupcreation } from "../../shared/services/groupService"; + +export const addGroupController = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { organization, userId } = req.user || {}; + const { projectId, position, groupName, type, collections } = req.body; + const missing = Object.entries({ + organization, + projectId, + position, + userId, + groupName, + type, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { + res.status(400).json({ + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, + }); + return; + } + const data = { + organization: organization as string, + projectId, + position, + type, + groupName, + collections, + userId: userId as string, + }; + const result = await groupcreation(data); + console.log("result:groupcretate ", result); + + switch (result.status) { + case "User not found": + res.status(404).json({ message: "User not found" }); + break; + case "project not found": + res.status(404).json({ + message: "project not found", + }); + break; + case "Collections already exist in this group": + res.status(200).json({ + message: "Collections already exist in this group", + }); + break; + case "Collections added to existing group": + res.status(200).json({ + message: "Collections added to existing group", + }); + break; + case "Success": + res.status(200).json({ + message: "Group created successfully", + groupId: result.data, + }); + break; + case "Validation Error": + res.status(400).json({ message: result.data || "Validation Error" }); + 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/controller/homePageController.ts b/src/api-server/controller/homePageController.ts index a25b549..7b4e802 100644 --- a/src/api-server/controller/homePageController.ts +++ b/src/api-server/controller/homePageController.ts @@ -11,15 +11,24 @@ export const homePageRecentlyViewedController = async ( ): Promise => { try { const { organization, userId } = req.user || {}; - if (!organization || !userId) { + const missing = Object.entries({ + organization, + userId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, - userId, + organization: organization as string, + userId: userId as string, }; const result = await recentlyViewedServices(data); @@ -53,15 +62,24 @@ export const homePageUserDataController = async ( ): Promise => { try { const { organization, userId } = req.user || {}; - if (!organization || !userId) { + const missing = Object.entries({ + organization, + userId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, - userId, + organization: organization as string, + userId: userId as string, }; const result = await homeuserProfileServices(data); diff --git a/src/api-server/controller/projectController.ts b/src/api-server/controller/projectController.ts index 65405ee..0074ef3 100644 --- a/src/api-server/controller/projectController.ts +++ b/src/api-server/controller/projectController.ts @@ -2,6 +2,7 @@ import { Request, Response } from "express"; import { DeleteProject, GetNodesInProject, + projectClear, projectCreationService, projectDatas, projectModification, @@ -23,32 +24,37 @@ export const projectCreationController = async ( architecture, description, } = req.body; - if ( - !organization || - !language || - !projectName || - !userId || - !apiProtocol || - !architecture || - !application - ) { + const missing = Object.entries({ + organization, + language, + userId, + projectName, + apiProtocol, + architecture, + application, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectName, language, description, application, - userId, + userId: userId as string, apiProtocol, architecture, }; const result = await projectCreationService(data); - console.log("result:projectcreate ", result); switch (result.status) { case "Project Already Exists": @@ -97,17 +103,26 @@ export const getProjects = async ( try { const { organization, userId } = req.user || {}; const { skip, limit } = req.params; - if (!organization || !userId) { + const missing = Object.entries({ + organization, + userId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const skipdata = parseInt(skip); const limitdata = parseInt(limit); const result = await projectDatas({ - organization, - userId, + organization: organization as string, + userId: userId as string, skipdata, limitdata, }); @@ -139,16 +154,26 @@ export const NodesCollectionsBasedOnproject = async ( try { const { organization, userId } = req.user || {}; const { projectId } = req.params; - if (!organization || !projectId || !userId) { + const missing = Object.entries({ + organization, + projectId, + userId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const data = { - organization, + organization: organization as string, projectId, - userId, + userId: userId as string, }; const result = await GetNodesInProject(data); switch (result.status) { @@ -191,15 +216,25 @@ export const accessAproject = async ( try { const { organization, userId } = req.user || {}; const { projectId } = req.params; - if (!organization || !userId || !projectId) { + const missing = Object.entries({ + organization, + projectId, + userId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const result = await ViewProjectService({ - organization, - userId, + organization: organization as string, + userId: userId as string, projectId, }); @@ -235,15 +270,25 @@ export const deleteProjectController = async ( try { const { organization, userId } = req.user || {}; const { projectId } = req.params; - if (!organization || !userId || !projectId) { + const missing = Object.entries({ + organization, + projectId, + userId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const result = await DeleteProject({ - organization, - userId, + organization: organization as string, + userId: userId as string, projectId, }); @@ -294,16 +339,26 @@ export const updateProjectController = async ( language, architecture, } = req.body; - if (!organization || !userId || !projectId) { + const missing = Object.entries({ + organization, + projectId, + userId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { res.status(400).json({ - message: "All fields are required", + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, }); return; } const result = await projectModification({ projectId, - organization, - userId, + organization: organization as string, + userId: userId as string, projectName, application, description, @@ -343,3 +398,64 @@ export const updateProjectController = async ( }); } }; + +export const projectClearController = async ( + req: AuthenticatedRequest, + res: Response +): Promise => { + try { + const { organization, userId } = req.user || {}; + const { projectId } = req.params; + const missing = Object.entries({ + organization, + userId, + projectId, + }) + .filter(([_, v]) => !v) + .map(([k]) => k); + + if (missing.length) { + res.status(400).json({ + message: `Missing field${missing.length > 1 ? "s" : ""}: ${missing.join( + ", " + )}`, + }); + return; + } + const data = { + organization: organization as string, + projectId, + userId: userId as string, + }; + const result = await projectClear(data); + console.log("result:clear ", result); + + switch (result.status) { + case "User not found": + res.status(404).json({ message: "User not found" }); + break; + case "project not found": + res.status(404).json({ + message: "project not found", + }); + break; + case "Success": + res.status(200).json({ + message: "Datas cleared successfully", + }); + break; + case "Validation Error": + res.status(400).json({ message: result.data || "Validation Error" }); + 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/routes/collectionRoutes.ts b/src/api-server/routes/collectionRoutes.ts index c84bace..c56783f 100644 --- a/src/api-server/routes/collectionRoutes.ts +++ b/src/api-server/routes/collectionRoutes.ts @@ -17,6 +17,7 @@ import { tokenValidator } from "../../shared/utils/token"; import authorizedRoles from "../../shared/middleware/rbacMiddleware"; const collectionNodeRoutes = express.Router(); + //Node creation collectionNodeRoutes.post( "/node/save", @@ -24,13 +25,15 @@ collectionNodeRoutes.post( authorizedRoles("Admin", "Editor", "Viewer"), NodeCreationController ); + //collection update collectionNodeRoutes.patch( - "/nodes/:collectionNodeId", + "/nodes/update/:projectId/:collectionNodeId", tokenValidator, authorizedRoles("Admin", "Editor", "Viewer"), updateCollectionController ); + //duplicate collection collectionNodeRoutes.post( "/nodes/:collectionNodeId/duplicate", @@ -46,6 +49,7 @@ collectionNodeRoutes.get( authorizedRoles("Admin", "Editor", "Viewer"), CollectionDatas ); + //delete collection collectionNodeRoutes.patch( "/nodes/:projectId/:collectionNodeId", @@ -72,7 +76,7 @@ collectionNodeRoutes.get( //update fields collectionNodeRoutes.patch( - "/nodes/:collectionNodeId/attributes/:attributeId", + "/nodesfield/attribute/:collectionNodeId", tokenValidator, authorizedRoles("Admin", "Editor", "Viewer"), updateAttributesCollections @@ -80,7 +84,7 @@ collectionNodeRoutes.patch( //delete fields collectionNodeRoutes.patch( - "/nodes/:collectionNodeId/attributes/softDelete", + "/nodes/:collectionNodeId/attributes/softdelete", tokenValidator, authorizedRoles("Admin", "Editor", "Viewer"), delAttributesCollections @@ -102,11 +106,11 @@ collectionNodeRoutes.get( ); //graphic Data - collectionNodeRoutes.get( "/collections/:projectId/:collectionNodeId", tokenValidator, authorizedRoles("Admin", "Editor", "Viewer"), graphicDatas ); + export default collectionNodeRoutes; diff --git a/src/api-server/routes/dummyRoutes.ts b/src/api-server/routes/dummyRoutes.ts index 8b8dc44..9a19808 100644 --- a/src/api-server/routes/dummyRoutes.ts +++ b/src/api-server/routes/dummyRoutes.ts @@ -70,7 +70,7 @@ dummyRoutes.patch( // ); // //update fields // dummyRoutes.patch( -// "/nodes/:collectionNodeId/attributes/:attributeId", +// "/nodes/:collectionNodeId/attributes/:fieldId", // tokenValidator, // authorizedRoles("Admin", "Editor", "Viewer"), // updateAttributesCollections diff --git a/src/api-server/routes/projectRoutes.ts b/src/api-server/routes/projectRoutes.ts index be17c3d..ec2b9bf 100644 --- a/src/api-server/routes/projectRoutes.ts +++ b/src/api-server/routes/projectRoutes.ts @@ -5,6 +5,7 @@ import { deleteProjectController, getProjects, NodesCollectionsBasedOnproject, + projectClearController, projectCreationController, updateProjectController, } from "../controller/projectController"; @@ -59,4 +60,13 @@ projectRoutes.patch( authorizedRoles("Admin", "Editor", "Viewer"), updateProjectController ); + +//clear Project +projectRoutes.patch( + "/project/:projectId/clearAll", + tokenValidator, + authorizedRoles("Admin", "Editor", "Viewer"), + projectClearController +); + export default projectRoutes; diff --git a/src/shared/model/collectionModel.ts b/src/shared/model/collectionModel.ts index 918b0eb..e2694f8 100644 --- a/src/shared/model/collectionModel.ts +++ b/src/shared/model/collectionModel.ts @@ -5,7 +5,7 @@ type IattributeTypes = | "string" | "any" | "Array" - | "Date" + | "date" | "Enum" | "Undefined" | "Object" @@ -19,6 +19,7 @@ type IattributeTypes = interface IAttributes { isArchive: boolean; + isIdentifier: boolean; primary?: boolean; key: string; type: IattributeTypes; @@ -61,7 +62,7 @@ const attributeSchema = new Schema({ "string", "Number", "Boolean", - "Date", + "date", "ObjectId", "Array", "Enum", @@ -81,6 +82,7 @@ const attributeSchema = new Schema({ primary: { type: Boolean }, index: { type: Boolean }, isArchive: { type: Boolean, default: false }, + isIdentifier: { type: Boolean, default: false }, }); interface ColorHex { type: "HEX"; @@ -128,6 +130,7 @@ const collectionSchema: Schema = new Schema( cornerRadius: { type: Number }, fontSize: { type: Number }, isArchive: { type: Boolean, default: false }, + // isIdentifier: { type: Boolean, default: false }, isSubCollection: { type: Boolean, default: false }, attributes: [attributeSchema], }, diff --git a/src/shared/model/edgeModel.ts b/src/shared/model/edgeModel.ts index efa93f6..02ddfd2 100644 --- a/src/shared/model/edgeModel.ts +++ b/src/shared/model/edgeModel.ts @@ -21,7 +21,7 @@ const EdgeSchema = new Schema({ cardinality: { type: String, enum: ["one-to-one", "one-to-many", "many-to-many"], - required: true, + // required: true, }, isArchive: { type: Boolean, default: false }, createdAt: { type: Number, default: Date.now }, diff --git a/src/shared/model/groupModel.ts b/src/shared/model/groupModel.ts new file mode 100644 index 0000000..ce03a9e --- /dev/null +++ b/src/shared/model/groupModel.ts @@ -0,0 +1,36 @@ +import { Schema, Document } from "mongoose"; +import MainModel from "../connection/connection"; +import { IProject } from "./projectmodel"; +import { ICollectionNode } from "./collectionModel"; +import { IUser } from "./userModel"; +export interface IgroupModel extends Document { + type: string; + groupName: string; + position: { + x: number; + y: number; + }; + projectId: IProject["_id"]; + collections: ICollectionNode["_id"][]; + isArchive: boolean; + createdBy: IUser["_id"]; +} +const GroupSchema = new Schema( + { + type: { type: String }, + groupName: { type: String, required: true }, + position: { + x: { type: Number }, + y: { type: Number }, + }, + projectId: { type: Schema.Types.ObjectId, ref: "Project", required: true }, + collections: [{ type: Schema.Types.ObjectId, ref: "Collection" }], + isArchive: { type: Boolean, default: false }, + createdBy: { type: Schema.Types.ObjectId, ref: "User" }, + }, + { timestamps: true } +); +const groupModel = (db: any) => { + return MainModel(db, "group", GroupSchema, "group"); +}; +export default groupModel; diff --git a/src/shared/services/collectionService.ts b/src/shared/services/collectionService.ts index 17d59b0..a92a6fb 100644 --- a/src/shared/services/collectionService.ts +++ b/src/shared/services/collectionService.ts @@ -24,17 +24,17 @@ interface IcollectionNodeName { userId: string; organization: string; collectionNodeId: string; - collectionName: string; - backgroundColor: string; - borderColor: string; - lineColor: string; - fontColor: string; - lineThickness: number; - fontName: string; - lineType: string; - borderThickness: number; - cornerRadius: number; - position: [number]; + collectionName?: string; + backgroundColor?: string; + borderColor?: string; + lineColor?: string; + fontColor?: string; + lineThickness?: number; + fontName?: string; + lineType?: string; + borderThickness?: number; + cornerRadius?: number; + position?: [number]; } interface IcollectionAttributes { projectId: string; @@ -64,21 +64,50 @@ interface IAttributesEdit { userId: string; organization: string; collectionNodeId: string; - attributeId: string; + fieldId: string; key?: string; type?: string; - primary:boolean + primary: boolean; required?: boolean; defaultValue?: any; unique?: boolean; index?: boolean; + isIdentifier?: boolean; +} + +interface IupdateChange { + fieldId: string; + key?: string; + type?: string; + primary: boolean; + required?: boolean; + defaultValue?: any; + unique?: boolean; + index?: boolean; + isIdentifier?: boolean; +} +interface IAttributesUpdate { + projectId: string; + userId: string; + organization: string; + collectionNodeId: string; + attributes: IupdateChange[]; + // fieldId: string; + // key?: string; + // type?: string; + // primary: boolean; + // required?: boolean; + // defaultValue?: any; + // unique?: boolean; + // index?: boolean; + // isIdentifier?: boolean; } interface IAttributesDel { projectId: string; userId: string; organization: string; collectionNodeId: string; - AttributeId: string; + fieldId: string; } interface ICollectionDelete { projectId: string; @@ -153,7 +182,14 @@ export const Nodecreation = async ( }); if (!newCollectionnode) return { status: "Collection node creation unsuccessfull" }; - else return { status: "Success", data: newCollectionnode._id }; + else { + const finalResult = { + collectionNodeId: newCollectionnode._id, + fieldId: (newCollectionnode.attributes[0] as any)._id, + }; + + return { status: "Success", data: finalResult }; + } } } catch (error: unknown) { if (error instanceof mongoose.Error.ValidationError) { @@ -231,15 +267,19 @@ export const updatecollection = async ( }, { new: true } ); - if(collectionNameupdate){ - + if (collectionNameupdate) { return { status: "Success" }; - } - else{ - return {status:"Update unsuccessfull"} + } else { + return { status: "Update unsuccessfull" }; } } } catch (error: unknown) { + if (error instanceof mongoose.Error.CastError) { + return { + status: "Invalid ID", + data: `Invalid value for ${error.path}: ${error.value}`, + }; + } if (error instanceof Error) { return { status: error.message, @@ -252,108 +292,127 @@ export const updatecollection = async ( } }; -export const addAttributes = async ( - data: IcollectionAttributes -): Promise => { - const { organization, projectId, userId, collectionNodeId, attributes } = - data; - try { - const ExistingUser = await userModel(organization).findOne({ - _id: userId, - isArchive: false, - }); +// export const addAttributes = async ( +// data: IcollectionAttributes +// ): Promise => { +// const { organization, projectId, userId, collectionNodeId, attributes } = +// data; +// console.log('data: ', data); +// try { +// const ExistingUser = await userModel(organization).findOne({ +// _id: userId, +// isArchive: false, +// }); - if (!ExistingUser) return { status: "User not found" }; - const existingProject = await ProjectType(organization).findOne({ - _id: projectId, - isArchive: false, - }); - if (!existingProject) { - return { status: "project not found" }; - } else { - const existingCollection = await collectionsModel(organization).findOne({ - projectId: projectId, - isArchive: false, - _id: collectionNodeId, - }); - if (!existingCollection) { - return { status: "Collection not found" }; - } - const existingAttributes = existingCollection.attributes || []; - const newAttributes = attributes; - const updatedAttributesMap = new Map(); +// if (!ExistingUser) return { status: "User not found" }; +// const existingProject = await ProjectType(organization).findOne({ +// _id: projectId, +// isArchive: false, +// }); +// if (!existingProject) { +// return { status: "project not found" }; +// } else { +// const existingCollection = await collectionsModel(organization).findOne({ +// projectId: projectId, +// isArchive: false, +// _id: collectionNodeId, +// }); +// if (!existingCollection) { +// return { status: "Collection not found" }; +// } +// const existingAttributes = existingCollection.attributes || []; +// const newAttributes = attributes; +// const updatedAttributesMap = new Map(); - for (const attr of existingAttributes) { - updatedAttributesMap.set(attr.key, attr); - } +// for (const attr of existingAttributes) { +// updatedAttributesMap.set(attr.key, attr); +// } - for (const attr of newAttributes) { - if (!updatedAttributesMap.has(attr.key)) { - updatedAttributesMap.set(attr.key, attr); - } - } +// for (const attr of newAttributes) { +// if (!updatedAttributesMap.has(attr.key)) { +// updatedAttributesMap.set(attr.key, attr); +// } +// } - const updatedAttributes = Array.from(updatedAttributesMap.values()); - const AttributesAdded = await collectionsModel( - organization - ).findOneAndUpdate( - { - projectId: projectId, - isArchive: false, - _id: collectionNodeId, - }, - { attributes: updatedAttributes }, - { new: true } - ); - if (AttributesAdded) { - for (const attr of AttributesAdded.attributes) { - if (attr.type === "Object") { - const existingsubcollection = await collectionsModel( - organization - ).findOne({ - projectId: projectId, - parentCollectionNodeId: collectionNodeId, - attributeparentId: (attr as any)._id, - isArchive: false, - }); - if (!existingsubcollection) { - const newCollection = await collectionsModel(organization).create( - { - type: "objectNode", - isArchive: false, - projectId: projectId, - collectionName: attr.key, - parentCollectionNodeId: collectionNodeId, - attributeparentId: (attr as any)._id, - attributes: [], - // position: [0, 0, 0], - } - ); - AttributesAdded.isSubCollection = true; - await AttributesAdded.save(); - } else { - return { - status: "Subcollection already added for the object data", - }; - } - } - } - await AttributesAdded.save(); - } - return { status: "Success" }; - } - } catch (error: unknown) { - if (error instanceof Error) { - return { - status: error.message, - }; - } else { - return { - status: "An unexpected error occurred", - }; - } - } -}; +// const updatedAttributes = Array.from(updatedAttributesMap.values()); +// const AttributesAdded = await collectionsModel( +// organization +// ).findOneAndUpdate( +// { +// projectId: projectId, +// isArchive: false, +// _id: collectionNodeId, +// }, +// { attributes: updatedAttributes }, +// { new: true } +// ); +// if (AttributesAdded) { +// for (const attr of AttributesAdded.attributes) { +// console.log('attr: ', attr); +// if (attr.type === "Object") { + +// const existingsubcollection = await collectionsModel( +// organization +// ).findOne({ +// projectId: projectId, +// parentCollectionNodeId: collectionNodeId, +// attributeparentId: (attr as any)._id, +// isArchive: false, +// }); +// console.log("existingsubcollection: ", existingsubcollection); +// if (!existingsubcollection) { +// const newCollection = await collectionsModel(organization).create( +// { +// type: "objectNode", +// isArchive: false, +// projectId: projectId, +// collectionName: attr.key, +// parentCollectionNodeId: collectionNodeId, +// attributeparentId: (attr as any)._id, +// attributes: [], +// // position: [0, 0, 0], +// } +// ); +// AttributesAdded.isSubCollection = true; +// await AttributesAdded.save(); +// } else { +// return { +// status: "Subcollection already added for the object data", +// }; +// } +// } +// } +// await AttributesAdded.save(); +// } +// const newlyAddedAttributes = updatedAttributes.filter( +// (attr) => !existingAttributes.some((exAttr) => exAttr.key === attr.key) +// ); +// const addedFieldIds = newlyAddedAttributes.map((attr) => attr._id); +// console.log("addedFieldIds: ", addedFieldIds); +// //how to send the added fieldId in response +// return { status: "Success" }; +// } +// } catch (error: unknown) { +// if (error instanceof mongoose.Error.CastError) { +// return { +// status: "Invalid ObjectId", +// data: error.message, +// }; +// } +// if (error instanceof mongoose.Error.ValidationError) { +// return { status: "Validation Error", data: error.message }; +// } +// if (error instanceof Error) { +// return { +// status: error.message, +// }; +// } else { +// return { +// status: "An unexpected error occurred", +// }; +// } +// } +// }; //both collections and edges in projects export const GetNodesInProject = async ( @@ -418,7 +477,7 @@ export const GetNodesInProject = async ( ); const formattedCollections = collectionNodes.map((collection: any) => { const baseData = { - collectionId: collection._id, + id: collection._id, position: collection.position, type: collection.type, data: { @@ -432,7 +491,19 @@ export const GetNodesInProject = async ( const { isArchive, refKey, ...rest } = attr.toObject ? attr.toObject() : attr; - return { ...rest }; + if (refKey) { + return { + ...rest, + sourceFieldRef: { + collectionNodeId: refKey.collection_id.toString(), + fieldId: refKey.fieldId + ? refKey.fieldId.toString() + : rest._id.toString(), + }, + }; + } + + return rest; }), }, }; @@ -466,183 +537,11 @@ export const GetNodesInProject = async ( } }; -// export const GetNodesInProject = async ( -// data: IcollectionNodes -// ): Promise => { -// const { organization, userId, projectId } = data; -// try { -// const existingProject = await ProjectType(organization).findOne({ -// _id: projectId, -// isArchive: false, -// }); -// if (!existingProject) { -// return { status: "project not found" }; -// } else { -// const collectionNodes = await collectionsModel(organization) -// .find({ projectId: projectId, isArchive: false }) -// .select("collectionName attributes position -_id isSubCollection"); -// if (!collectionNodes) -// return { status: "No collection Nodes present", data: [] }; -// else { -// const fetchNestedAttributes = async ( -// parentCollectionNodeId: string, -// attributeId: string -// ): Promise => { -// const subCollection = await collectionsModel(organization) -// .findOne({ -// parentCollectionNodeId, -// attributeparentId: attributeId, -// isArchive: false, -// }) -// .select("collectionName attributes"); - -// if (!subCollection) { -// return {}; // If no sub-collection exists, return empty object -// } - -// const nestedAttributes: Record = {}; -// for (const attr of subCollection.attributes) { -// if (attr.type === "object") { -// nestedAttributes[attr.key] = { -// type: "object", -// attributes: await fetchNestedAttributes( -// subCollection._id as string, -// (attr as any)._id -// ), -// }; -// } else { -// nestedAttributes[attr.key] = attr.type; -// } -// } - -// return nestedAttributes; -// }; - -// // Format the main collections -// const formattedCollections = await Promise.all( -// collectionNodes.map(async (collection) => { -// const formattedAttributes: Record = {}; - -// for (const attr of collection.attributes) { -// if (attr.type === "object") { -// formattedAttributes[attr.key] = { -// type: "object", -// attributes: await fetchNestedAttributes( -// collection._id as string, -// (attr as any)._id -// ), -// }; -// } else { -// formattedAttributes[attr.key] = attr.type; -// } -// } - -// return { -// position: collection.position, -// collectionName: collection.collectionName, -// attributes: formattedAttributes, -// }; -// }) -// ); - -// return { -// status: "Success", -// data: formattedCollections, -// }; -// } -// } -// // } -// } catch (error: unknown) { -// if (error instanceof Error) { -// return { -// status: error.message, -// }; -// } else { -// return { -// status: "An unexpected error occurred", -// }; -// } -// } -// }; - export const UpdateAttributes = async ( - data: IAttributesEdit + // data: IAttributesEdit + data: IAttributesUpdate ): Promise => { - const { - organization, - userId, - projectId, - collectionNodeId, - attributeId, - required, - defaultValue, - unique, - index, - key, - type, - } = data; - try { - const ExistingUser = await userModel(organization).findOne({ - _id: userId, - isArchive: false, - }); - - if (!ExistingUser) return { status: "User not found" }; - const existingProject = await ProjectType(organization).findOne({ - _id: projectId, - isArchive: false, - }); - if (!existingProject) { - return { status: "project not found" }; - } else { - const existingCollection = await collectionsModel(organization).findOne({ - projectId: projectId, - _id: collectionNodeId, - isArchive: false, - }); - if (!existingCollection) return { status: "Collection not found" }; - - const editCollection = await collectionsModel( - organization - ).findOneAndUpdate( - { - projectId: projectId, - isArchive: false, - attributes: { - $elemMatch: { _id: new mongoose.Types.ObjectId(attributeId) }, - }, - }, - { - $set: { - "attributes.$.required": required, - "attributes.$.default": defaultValue, - "attributes.$.index": index, - "attributes.$.unique": unique, - "attributes.$.key": key, - "attributes.$.type": type, - }, - }, - { new: true } - ); - return { status: "Success" }; - } - } catch (error: unknown) { - if (error instanceof Error) { - return { - status: error.message, - }; - } else { - return { - status: "An unexpected error occurred", - }; - } - } -}; - -export const DelAttributes = async ( - data: IAttributesDel -): Promise => { - const { organization, userId, projectId, collectionNodeId, AttributeId } = + const { organization, userId, projectId, collectionNodeId, attributes } = data; try { const ExistingUser = await userModel(organization).findOne({ @@ -665,26 +564,74 @@ export const DelAttributes = async ( }); if (!existingCollection) return { status: "Collection not found" }; - const softDeleteAttribute = await collectionsModel( - organization - ).findOneAndUpdate( - { - projectId: projectId, - isArchive: false, - attributes: { - $elemMatch: { - _id: new mongoose.Types.ObjectId(AttributeId), + for (const attr of attributes) { + const fieldId = attr.fieldId; + if (attr.type === "Object") { + const existingsubcollection = await collectionsModel( + organization + ).findOne({ + projectId: projectId, + parentCollectionNodeId: collectionNodeId, + attributeparentId: fieldId, + isArchive: false, + }); + console.log("existingsubcollection: ", existingsubcollection); + if (!existingsubcollection) { + const fieldnamefind = await collectionsModel(organization).findOne( + { + projectId: projectId, + isArchive: false, + _id: collectionNodeId, + "attributes._id": new mongoose.Types.ObjectId(fieldId), + }, + { + "attributes.$": 1, + } + ); + + const newCollection = await collectionsModel(organization).create({ + type: "objectNode", isArchive: false, + projectId: projectId, + collectionName: fieldnamefind?.attributes[0].key, + parentCollectionNodeId: collectionNodeId, + attributeparentId: fieldId, + attributes: [], + // position: [0, 0, 0], + }); + existingCollection.isSubCollection = true; + await existingCollection.save(); + } else { + return { + status: "Subcollection already added for the object data", + }; + } + } + const editCollection = await collectionsModel( + organization + ).findOneAndUpdate( + { + projectId: projectId, + isArchive: false, + _id: collectionNodeId, + attributes: { + $elemMatch: { _id: new mongoose.Types.ObjectId(fieldId) }, }, }, - }, - { - $set: { - "attributes.$.isArchive": true, + { + $set: { + "attributes.$.required": attr.required, + "attributes.$.default": attr.defaultValue, + "attributes.$.index": attr.index, + "attributes.$.unique": attr.unique, + "attributes.$.key": attr.key, + "attributes.$.type": attr.type, + "attributes.$.isIdentifier": attr.isIdentifier, + }, }, - }, - { new: true } - ); + { new: true } + ); + } return { status: "Success" }; } } catch (error: unknown) { @@ -700,6 +647,267 @@ export const DelAttributes = async ( } }; +// export const DelAttributes = async ( +// data: IAttributesDel +// ): Promise => { +// const { organization, userId, projectId, collectionNodeId, fieldId } = data; +// try { +// const ExistingUser = await userModel(organization).findOne({ +// _id: userId, +// isArchive: false, +// }); + +// if (!ExistingUser) return { status: "User not found" }; +// const existingProject = await ProjectType(organization).findOne({ +// _id: projectId, +// isArchive: false, +// }); +// if (!existingProject) { +// return { status: "project not found" }; +// } else { +// const existingCollection = await collectionsModel(organization).findOne({ +// projectId: projectId, +// _id: collectionNodeId, +// isArchive: false, +// }); +// if (!existingCollection) return { status: "Collection not found" }; + +// const softDeleteAttribute = await collectionsModel(organization).findOne( +// { +// projectId: projectId, +// isArchive: false, +// attributes: { +// $elemMatch: { +// _id: new mongoose.Types.ObjectId(fieldId), +// isArchive: false, +// }, +// }, +// }, +// { +// "attributes.$": 1, +// } +// ); +// if (softDeleteAttribute?.attributes[0].type === "Object") { +// console.log("object type "); +// const mainCollectionNode = await collectionsModel( +// organization +// ).findOneAndUpdate( +// { +// projectId: projectId, +// isArchive: false, +// attributes: { +// $elemMatch: { +// _id: new mongoose.Types.ObjectId(fieldId), +// isArchive: false, +// }, +// }, +// }, +// { +// $set: { +// "attributes.$.isArchive": true, +// }, +// }, +// { new: true } +// ); + +// if (mainCollectionNode) { +// const objectNodeCollection = await collectionsModel( +// organization +// ).findOneAndUpdate( +// { +// projectId, +// parentCollectionNodeId: collectionNodeId, +// attributeparentId: fieldId, +// isArchive: false, +// }, +// { isArchive: true } +// ); +// } + +// const fieldnamefind = await collectionsModel(organization).findOne( +// { +// projectId: projectId, +// isArchive: false, +// _id: collectionNodeId, +// "attributes._id": new mongoose.Types.ObjectId(fieldId), +// }, +// { +// "attributes.$": 1, +// } +// ); +// const matchingEdgeData = await edgeModel(organization).findOne({ +// "from.collection_id": softDeleteAttribute?._id, +// "from.field": fieldnamefind?.attributes[0].key, +// projectId, +// isArchive: false, +// }); +// if (matchingEdgeData) { +// const deleteEdge = await edgeModel(organization).findOneAndUpdate( +// { +// "from.collection_id": softDeleteAttribute?._id, +// "from.field": fieldnamefind?.attributes[0].key, +// projectId, +// isArchive: false, +// }, +// { isArchive: true }, +// { new: true } +// ); +// if (deleteEdge?.to?.collection_id) { +// await collectionsModel(organization).updateOne( +// { +// _id: deleteEdge.to.collection_id, +// projectId, +// isArchive: false, +// }, +// { +// $pull: { +// attributes: { +// "refKey.fieldId": new mongoose.Types.ObjectId(fieldId), +// }, +// }, +// } +// ); +// } +// } +// } else if (softDeleteAttribute?.attributes[0].type !== "Object") { +// console.log("string format "); +// const mainCollectionNode = await collectionsModel( +// organization +// ).findOneAndUpdate( +// { +// projectId: projectId, +// isArchive: false, +// attributes: { +// $elemMatch: { +// _id: new mongoose.Types.ObjectId(fieldId), +// isArchive: false, +// }, +// }, +// }, +// { +// $set: { +// "attributes.$.isArchive": true, +// }, +// }, +// { new: true } +// ); + +// const fieldnamefind = await collectionsModel(organization).findOne( +// { +// projectId: projectId, +// isArchive: false, +// _id: collectionNodeId, +// "attributes._id": new mongoose.Types.ObjectId(fieldId), +// }, +// { +// "attributes.$": 1, +// } +// ); +// const matchingEdgeData = await edgeModel(organization).findOne({ +// "from.collection_id": softDeleteAttribute?._id, +// "from.field": fieldnamefind?.attributes[0].key, +// projectId, +// isArchive: false, +// }); +// if (matchingEdgeData) { +// const deleteEdge = await edgeModel(organization).findOneAndUpdate( +// { +// "from.collection_id": softDeleteAttribute?._id, +// "from.field": fieldnamefind?.attributes[0].key, +// projectId, +// isArchive: false, +// }, +// { isArchive: true }, +// { new: true } +// ); +// if (deleteEdge?.to?.collection_id) { +// await collectionsModel(organization).updateOne( +// { +// _id: deleteEdge.to.collection_id, +// projectId, +// isArchive: false, +// }, +// { +// $pull: { +// attributes: { +// "refKey.fieldId": new mongoose.Types.ObjectId(fieldId), +// }, +// }, +// } +// ); +// } +// } +// } + +// // === +// else { +// console.log("edge"); +// const fieldnamefind = await collectionsModel(organization).findOne( +// { +// projectId: projectId, +// isArchive: false, +// _id: collectionNodeId, +// "attributes._id": new mongoose.Types.ObjectId(fieldId), +// }, +// { +// "attributes.$": 1, +// } +// ); +// const matchingEdgeData = await edgeModel(organization).findOneAndUpdate( +// { +// from: { +// collection_id: softDeleteAttribute?._id, +// field: fieldnamefind?.attributes[0].key, +// }, +// projectId, +// isArchive: false, +// }, +// { isArchive: true }, +// { new: true } +// ); +// if (matchingEdgeData?.to?.collection_id) { +// await collectionsModel(organization).updateOne( +// { +// _id: matchingEdgeData.to.collection_id, +// projectId, +// isArchive: false, +// }, +// { +// $pull: { +// attributes: { +// "refKey.fieldId": new mongoose.Types.ObjectId(fieldId), +// }, +// }, +// } +// ); +// } +// } +// // ====== +// // if (connectionField) { +// // if ( +// // connectionField.attributes.includes(refkey.collection_id) === +// // softDeleteAttribute?._id && +// // connectionField.attributes.refkey.fieldId === fieldId +// // ) { +// // connectionField.attributes.refkey(delete) +// // } +// // } + +// return { status: "Success" }; +// } +// } catch (error: unknown) { +// if (error instanceof Error) { +// return { +// status: error.message, +// }; +// } else { +// return { +// status: "An unexpected error occurred", +// }; +// } +// } +// }; + export const delCollection = async ( data: ICollectionDelete ): Promise => { @@ -1004,11 +1212,11 @@ export const DuplicateAttributes = async ( } console.log("existingAttr.type: ", existingAttr.type); - existingCollection.attributes.push({ - key: newKey, - type: existingAttr.type, - isArchive: false, - }); + // existingCollection.attributes.push({ + // key: newKey, + // type: existingAttr.type, + // isArchive: false, + // }); } else { return { status: "Attribute doesnot match" }; } @@ -1075,3 +1283,305 @@ export const GetcollectionLists = async ( } } }; + +// export const addAttributes = async ( +// data: IcollectionAttributes +// ): Promise => { +// const { organization, projectId, userId, collectionNodeId, attributes } = +// data; +// try { +// const ExistingUser = await userModel(organization).findOne({ +// _id: userId, +// isArchive: false, +// }); +// if (!ExistingUser) return { status: "User not found" }; + +// const existingProject = await ProjectType(organization).findOne({ +// _id: projectId, +// isArchive: false, +// }); +// if (!existingProject) return { status: "project not found" }; + +// const existingCollection = await collectionsModel(organization).findOne({ +// projectId, +// isArchive: false, +// _id: collectionNodeId, +// }); +// if (!existingCollection) return { status: "Collection not found" }; + +// const existingAttributes = existingCollection.attributes || []; +// const updatedAttributesMap = new Map(); + +// // Keep old attributes +// // for (const attr of existingAttributes) { +// // updatedAttributesMap.set(attr.key, attr); +// // console.log('updatedAttributesMap: old', updatedAttributesMap); +// // } +// for (const attr of existingAttributes) { +// if (!attr.isArchive) { +// updatedAttributesMap.set(attr.key, attr); +// } +// } +// // Add new attributes +// for (const attr of attributes) { +// if (!updatedAttributesMap.has(attr.key)) { +// updatedAttributesMap.set(attr.key, attr); +// console.log("updatedAttributesMap: ", updatedAttributesMap); +// } +// } + +// const updatedAttributes = Array.from(updatedAttributesMap.values()); + +// // Update collection with new attributes +// const AttributesAdded = await collectionsModel( +// organization +// ).findOneAndUpdate( +// { projectId, isArchive: false, _id: collectionNodeId }, +// { attributes: updatedAttributes }, +// { new: true } +// ); + +// if (!AttributesAdded) return { status: "Failed to add attributes" }; + +// // Create subcollections for Object type attributes if not already +// for (const attr of AttributesAdded.attributes) { +// if (attr.type === "Object") { +// const existingsubcollection = await collectionsModel( +// organization +// ).findOne({ +// projectId, +// parentCollectionNodeId: collectionNodeId, +// attributeparentId: (attr as any)._id, +// isArchive: false, +// }); + +// if (!existingsubcollection) { +// await collectionsModel(organization).create({ +// type: "objectNode", +// isArchive: false, +// projectId, +// collectionName: attr.key, +// parentCollectionNodeId: collectionNodeId, +// attributeparentId: (attr as any)._id, +// attributes: [], +// }); +// AttributesAdded.isSubCollection = true; +// } +// } +// } + +// await AttributesAdded.save(); + +// const newlyAddedAttributes = AttributesAdded.attributes.filter( +// (attr) => !existingAttributes.some((exAttr) => exAttr.key === attr.key) +// ); + +// const addedFieldIds = newlyAddedAttributes.map((attr) => (attr as any)._id); + +// // const addedFieldIds = newlyAddedAttributes +// // .map((attr) => (attr as any)._id.toString()) +// // .join(","); +// console.log("addedFieldIds: ", addedFieldIds); + +// return { +// status: "Success", +// data: addedFieldIds, +// }; +// } catch (error: unknown) { +// if (error instanceof mongoose.Error.CastError) +// return { status: "Invalid ObjectId", data: error.message }; +// if (error instanceof mongoose.Error.ValidationError) +// return { status: "Validation Error", data: error.message }; +// if (error instanceof Error) return { status: error.message }; +// return { status: "An unexpected error occurred" }; +// } +// }; + +export const DelAttributes = async ( + data: IAttributesDel +): Promise => { + const { organization, userId, projectId, collectionNodeId, fieldId } = data; + + try { + const existingUser = await userModel(organization).findOne({ + _id: userId, + isArchive: false, + }); + if (!existingUser) return { status: "User not found" }; + + const existingProject = await ProjectType(organization).findOne({ + _id: projectId, + isArchive: false, + }); + if (!existingProject) return { status: "Project not found" }; + + const existingCollection = await collectionsModel(organization).findOne({ + _id: collectionNodeId, + projectId, + isArchive: false, + "attributes._id": new mongoose.Types.ObjectId(fieldId), + }); + if (!existingCollection) return { status: "Collection not found" }; + + const attribute = existingCollection.attributes.find( + (attr) => (attr as any)._id.toString() === fieldId + ); + if (!attribute) return { status: "Attribute not found" }; + + await collectionsModel(organization).updateOne( + { _id: collectionNodeId, "attributes._id": fieldId }, + { $set: { "attributes.$.isArchive": true } } + ); + + if (attribute.type === "Object") { + await collectionsModel(organization).updateMany( + { + parentCollectionNodeId: collectionNodeId, + attributeparentId: fieldId, + isArchive: false, + }, + { $set: { isArchive: true } } + ); + } + + const matchingEdge = await edgeModel(organization).findOneAndUpdate( + { + "from.collection_id": collectionNodeId, + "from.field": attribute.key, + projectId, + isArchive: false, + }, + { $set: { isArchive: true } }, + { new: true } + ); + + if (matchingEdge?.to?.collection_id) { + await collectionsModel(organization).updateOne( + { + _id: matchingEdge.to.collection_id, + projectId, + isArchive: false, + }, + { + $pull: { + attributes: { + "refKey.fieldId": new mongoose.Types.ObjectId(fieldId), + }, + }, + } + ); + } + + return { status: "Success" }; + } catch (error: unknown) { + if (error instanceof Error) return { status: error.message }; + return { status: "An unexpected error occurred" }; + } +}; + +export const addAttributes = async ( + data: IcollectionAttributes +): Promise => { + const { organization, projectId, userId, collectionNodeId, attributes } = + data; + console.log("data: ", data); + + try { + // 1️⃣ Validate User + const existingUser = await userModel(organization).findOne({ + _id: userId, + isArchive: false, + }); + if (!existingUser) return { status: "User not found" }; + + // 2️⃣ Validate Project + const existingProject = await ProjectType(organization).findOne({ + _id: projectId, + isArchive: false, + }); + if (!existingProject) return { status: "Project not found" }; + + // 3️⃣ Validate Collection + const existingCollection = await collectionsModel(organization).findOne({ + projectId, + _id: collectionNodeId, + isArchive: false, + }); + if (!existingCollection) return { status: "Collection not found" }; + + const existingAttributes = existingCollection.attributes || []; + + // 4️⃣ Check for duplicates with isArchive: false + for (const attr of attributes) { + const duplicate = existingAttributes.find( + (exAttr) => exAttr.key === attr.key && !exAttr.isArchive + ); + console.log("duplicate: ", duplicate); + if (duplicate) { + return { status: `Attribute "${attr.key}" already exists` }; + } + } + + // 5️⃣ Merge new attributes + const updatedAttributes = [...existingAttributes, ...attributes]; + + // 6️⃣ Update collection + const attributesAdded = await collectionsModel( + organization + ).findOneAndUpdate( + { projectId, _id: collectionNodeId, isArchive: false }, + { attributes: updatedAttributes }, + { new: true } + ); + + if (!attributesAdded) return { status: "Failed to add attributes" }; + + // 7️⃣ Create subcollections for Object type attributes + for (const attr of attributes) { + if (attr.type === "Object") { + const existingSubCollection = await collectionsModel( + organization + ).findOne({ + projectId, + parentCollectionNodeId: collectionNodeId, + attributeparentId: (attr as any)._id, + isArchive: false, + }); + + if (!existingSubCollection) { + await collectionsModel(organization).create({ + type: "objectNode", + isArchive: false, + projectId, + collectionName: attr.key, + parentCollectionNodeId: collectionNodeId, + attributeparentId: (attr as any)._id, + attributes: [], + }); + attributesAdded.isSubCollection = true; + } + } + } + + await attributesAdded.save(); + + // 8️⃣ Return newly added attribute IDs + const newlyAddedAttributes = attributesAdded.attributes.filter((attr) => + attributes.some((newAttr) => newAttr.key === attr.key) + ); + const addedFieldIds = newlyAddedAttributes.map((attr) => (attr as any)._id); + console.log("addedFieldIds: ", addedFieldIds); + + return { + status: "Success", + data: addedFieldIds, + }; + } catch (error: unknown) { + if (error instanceof mongoose.Error.CastError) + return { status: "Invalid ObjectId", data: error.message }; + if (error instanceof mongoose.Error.ValidationError) + return { status: "Validation Error", data: error.message }; + if (error instanceof Error) return { status: error.message }; + return { status: "An unexpected error occurred" }; + } +}; diff --git a/src/shared/services/dummyService.ts b/src/shared/services/dummyService.ts index 42abc35..043bcd3 100644 --- a/src/shared/services/dummyService.ts +++ b/src/shared/services/dummyService.ts @@ -56,7 +56,7 @@ interface IAttributesEdit { userId: string; organization: string; collectionNodeId: string; - attributeId: string; + fieldId: string; key?: string; type?: string; required?: boolean; @@ -69,7 +69,7 @@ interface IAttributesDel { userId: string; organization: string; collectionNodeId: string; - AttributeId: string; + fieldId: string; } interface ICollectionDelete { projectId: string; @@ -308,7 +308,7 @@ export const addAttributesdummy = async ( // userId, // projectId, // collectionNodeId, -// attributeId, +// fieldId, // required, // defaultValue, // unique, @@ -338,7 +338,7 @@ export const addAttributesdummy = async ( // projectId: projectId, // isArchive: false, // attributes: { -// $elemMatch: { _id: new mongoose.Types.ObjectId(attributeId) }, +// $elemMatch: { _id: new mongoose.Types.ObjectId(fieldId) }, // }, // }, // { @@ -371,7 +371,7 @@ export const addAttributesdummy = async ( // export const DelAttributes = async ( // data: IAttributesDel // ): Promise => { -// const { organization, userId, projectId, collectionNodeId, AttributeId } = +// const { organization, userId, projectId, collectionNodeId, fieldId } = // data; // try { // const existingProject = await ProjectType(organization).findOne({ @@ -396,7 +396,7 @@ export const addAttributesdummy = async ( // isArchive: false, // attributes: { // $elemMatch: { -// _id: new mongoose.Types.ObjectId(AttributeId), +// _id: new mongoose.Types.ObjectId(fieldId), // isArchive: false, // }, // }, diff --git a/src/shared/services/edgeService.ts b/src/shared/services/edgeService.ts index 5725cbe..f02576d 100644 --- a/src/shared/services/edgeService.ts +++ b/src/shared/services/edgeService.ts @@ -1,3 +1,4 @@ +import mongoose from "mongoose"; import ProjectType from "../../shared/model/projectmodel"; import collectionsModel from "../model/collectionModel"; import edgeModel from "../model/edgeModel"; @@ -115,9 +116,9 @@ export const edgecreation = async (data: IEdge): Promise => { await existingToCollection.save(); - console.log( - `Field ${newFieldKey} (type: ${fieldType}) added to TO collection with reference to ${existingFromCollection._id}` - ); + // console.log( + // `Field ${newFieldKey} (type: ${fieldType}) added to TO collection with reference to ${existingFromCollection._id}` + // ); const newEdge = { projectId, from: { collection_id: existingFromCollection._id, field: from.field }, @@ -138,7 +139,9 @@ export const edgecreation = async (data: IEdge): Promise => { }; } } catch (error: unknown) { - console.log("error: ", error); + if (error instanceof mongoose.Error.ValidationError) { + return { status: "Validation Error", data: error.message }; + } if (error instanceof Error) { return { status: error.message, diff --git a/src/shared/services/groupService.ts b/src/shared/services/groupService.ts new file mode 100644 index 0000000..7934874 --- /dev/null +++ b/src/shared/services/groupService.ts @@ -0,0 +1,202 @@ +import mongoose from "mongoose"; +import ProjectType from "../../shared/model/projectmodel"; +import collectionsModel from "../model/collectionModel"; +import userModel from "../model/userModel"; +import groupModel from "../model/groupModel"; +interface Iresponse { + status: string; + data?: any; +} + +interface IcollectionsNode { + collectionNodeId: string; +} + +interface IgroupNode { + projectId: string; + userId: string; + collections: IcollectionsNode[]; + groupName: string; + type: string; + organization: string; + position: { + x: number; + y: number; + }; +} + +interface IgroupNodeupdate { + projectId: string; + userId: string; + groupName: string; + type: string; + organization: string; + position: { + x: number; + y: number; + }; +} + +export const groupcreation = async (data: IgroupNode): Promise => { + const { + organization, + projectId, + position, + userId, + groupName, + type, + collections, + } = data; + try { + const ExistingUser = await userModel(organization).findOne({ + _id: userId, + isArchive: false, + }); + + if (!ExistingUser) return { status: "User not found" }; + const existingProject = await ProjectType(organization).findOne({ + _id: projectId, + isArchive: false, + }); + if (!existingProject) { + return { status: "project not found" }; + } else { + const existingGroup = await groupModel(organization).findOne({ + projectId: projectId, + isArchive: false, + groupName: groupName, + }); + // if (existingGroup) return { status: "Group already exists" }; + // else { + // if (collections.length > 0) { + // const newcoln = collections; + // const updatedCollectionsMap = new Map(); + + // for (const coln of collections) { + // updatedCollectionsMap.set(coln, 0); + // } + + // for (const coln of collections) { + // if (!updatedCollectionsMap.has(coln)) { + // updatedCollectionsMap.set(coln); + // } + // } + + // const updatedCollections = Array.from(updatedCollectionsMap.values()); + // const newGroup = await groupModel(organization).create({ + // groupName, + // projectId, + // position, + // createdBy: userId, + // collections: updatedCollections, + // }); + // // } + // if (newGroup) + // return { + // status: "NewGroup Created Successfully", + // data: newGroup._id, + // }; + // else { + // return { + // status: "Creation Unsuccessfull", + // }; + // } + // } + // } + // } + + const collectionIds = collections.map( + (c) => new mongoose.Types.ObjectId(c.collectionNodeId) + ); + + if (existingGroup) { + const existingIds = existingGroup.collections.map((id) => + (id as any).toString() + ); + const newIds = collectionIds.filter( + (id) => !existingIds.includes(id.toString()) + ); + + if (newIds.length === 0) + return { status: "Collections already exist in this group" }; + + existingGroup.collections.push(...newIds); + await existingGroup.save(); + return { + status: "Collections added to existing group", + data: existingGroup._id, + }; + } else { + const newGroup = await groupModel(organization).create({ + groupName, + type, + position, + projectId, + createdBy: userId, + collections: [ + ...new Set(collectionIds.map((id) => id.toString())), + ].map((id) => new mongoose.Types.ObjectId(id)), + }); + return { status: "Success", data: newGroup._id }; + } + } + } catch (error: unknown) { + if (error instanceof mongoose.Error.ValidationError) { + return { status: "Validation Error", data: error.message }; + } else if (error instanceof Error) { + return { status: error.message }; + } else { + return { status: "An unexpected error occurred" }; + } + } +}; + +// export const addNodesToGroup = async (data: IgroupNode): Promise => { +// const { organization, projectId, position, userId, groupId, groups } = data; +// try { +// const ExistingUser = await userModel(organization).findOne({ +// _id: userId, +// isArchive: false, +// }); +// if (!ExistingUser) return { status: "User not found" }; +// const existingProject = await ProjectType(organization).findOne({ +// _id: projectId, +// isArchive: false, +// }); +// if (!existingProject) { +// return { status: "project not found" }; +// } else { +// const existingGroup = await groupModel(organization).findOne({ +// projectId: projectId, +// isArchive: false, +// groupId: groupId, +// }); +// if (existingGroup) { +// const existingGroup = await groupModel(organization).findOneAndUpdate( +// { +// projectId: projectId, +// isArchive: false, +// groupId: groupId, +// }, +// { +// groups: groups, +// }, +// { new: true } +// ); +// if (existingGroup) { +// return { status: "Group updated successfully" }; +// } else { +// return { status: "Group update Unsuccessfully" }; +// } +// } +// } +// } catch (error: unknown) { +// if (error instanceof mongoose.Error.ValidationError) { +// return { status: "Validation Error", data: error.message }; +// } else if (error instanceof Error) { +// return { status: error.message }; +// } else { +// return { status: "An unexpected error occurred" }; +// } +// } +// }; diff --git a/src/shared/services/projectService.ts b/src/shared/services/projectService.ts index 843ef0a..df72276 100644 --- a/src/shared/services/projectService.ts +++ b/src/shared/services/projectService.ts @@ -7,6 +7,7 @@ import shareModel from "../model/shareModel"; import userDataModel from "../model/userDataModel"; import userModel from "../model/userModel"; import versionModel from "../model/versionModel"; +import groupModel from "../model/groupModel"; interface Iresponse { status: string; data?: any; @@ -478,3 +479,41 @@ export const projectModification = async ( } } }; + +export const projectClear = async (data: IProjectView): Promise => { + try { + const { projectId, organization, userId } = data; + const ExistingUser = await userModel(organization).findOne({ + _id: userId, + isArchive: false, + }); + + if (!ExistingUser) return { status: "User not found" }; + let query: any = { + _id: projectId, + isArchive: false, + }; + const existingProject = await ProjectType(organization).findOne(query); + if (!existingProject) return { status: "Project not found" }; + + const models = [collectionsModel, edgeModel, groupModel]; + for (const model of models) { + await model(organization).updateMany( + { projectId, isArchive: false }, + { isArchive: true } + ); + } + // } + return { status: "Success" }; + } catch (error: unknown) { + if (error instanceof Error) { + return { + status: error.message, + }; + } else { + return { + status: "An unexpected error occurred", + }; + } + } +}; diff --git a/src/socket-server/controllers/collectionNodeController.ts b/src/socket-server/controllers/collectionNodeController.ts index 3346149..69bbc7e 100644 --- a/src/socket-server/controllers/collectionNodeController.ts +++ b/src/socket-server/controllers/collectionNodeController.ts @@ -1,450 +1,441 @@ import { Socket, Server } from "socket.io"; import { EVENTS } from "../events/events"; -import { ErrorResponse, FinalResponse, validateFields } from "../utils/socketfunctionHelpers"; +import { + ErrorResponse, + FinalResponse, + validateFields, +} from "../utils/socketfunctionHelpers"; import { emitToSenderAndAdmins } from "../utils/emitEventResponse"; import { deleteEdge, edgecreation } from "../../shared/services/edgeService"; -import { addAttributes, DelAttributes, delCollection, DuplicateCollection, Nodecreation, SetCollectionName, UpdateAttributes } from "../../shared/services/collectionService"; - - +import { + addAttributes, + DelAttributes, + delCollection, + DuplicateCollection, + Nodecreation, + SetCollectionName, + UpdateAttributes, +} from "../../shared/services/collectionService"; export const CollectionHandleEvent = async ( - event: string, - socket: Socket, - io: Server, - data: any, - connectedUsersByOrg: { - [org: string]: { socketId: string; userId: string; role: string }[]; - } + event: string, + socket: Socket, + io: Server, + data: any, + connectedUsersByOrg: { + [org: string]: { socketId: string; userId: string; role: string }[]; + } ) => { - if (event !== EVENTS.collectionCreate || !data?.organization) return; - const requiredFields = [ - "position", - "projectId", - "organization", - ]; - const missingFields = validateFields(data, requiredFields); - - if (missingFields.length > 0) { - emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionCreateResponse, - ErrorResponse(missingFields, socket, data.organization), - connectedUsersByOrg - ); - return; - } - const result = await Nodecreation(data); - console.log('result: ', result); - const status = typeof result?.status === "string" ? result.status : "unknown"; - - const messages: Record = { - Success: { message: "Node created successfully" }, - "Collection node creation unsuccessfull": { message: "Collection node creation unsuccessfull" }, - "Project not found": { message: "Project not found" }, - }; - - const msg = messages[status] || { message: "Internal server error" }; - const result_Datas = - status === "Success" && result?.data ? result.data : undefined; - console.log('result_Datas: ', result_Datas); - - const response = FinalResponse( - status, - socket, - data.organization, - messages, - result_Datas - ); - console.log('response: ', response); + if (event !== EVENTS.collectionCreate || !data?.organization) return; + const requiredFields = ["position", "projectId", "organization"]; + const missingFields = validateFields(data, requiredFields); + if (missingFields.length > 0) { emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionCreateResponse, - response, - connectedUsersByOrg + io, + socket, + data.organization, + EVENTS.collectionCreateResponse, + ErrorResponse(missingFields, socket, data.organization), + connectedUsersByOrg ); + return; + } + const result = await Nodecreation(data); + console.log("result: ", result); + const status = typeof result?.status === "string" ? result.status : "unknown"; + + const messages: Record = { + Success: { message: "Node created successfully" }, + "Collection node creation unsuccessfull": { + message: "Collection node creation unsuccessfull", + }, + "Project not found": { message: "Project not found" }, + }; + + const msg = messages[status] || { message: "Internal server error" }; + const result_Datas = + status === "Success" && result?.data ? result.data : undefined; + console.log("result_Datas: ", result_Datas); + + const response = FinalResponse( + status, + socket, + data.organization, + messages, + result_Datas + ); + console.log("response: ", response); + + emitToSenderAndAdmins( + io, + socket, + data.organization, + EVENTS.collectionCreateResponse, + response, + connectedUsersByOrg + ); }; export const CollectioNamenHandleEvent = async ( - event: string, - socket: Socket, - io: Server, - data: any, - connectedUsersByOrg: { - [org: string]: { socketId: string; userId: string; role: string }[]; - } + event: string, + socket: Socket, + io: Server, + data: any, + connectedUsersByOrg: { + [org: string]: { socketId: string; userId: string; role: string }[]; + } ) => { - if (event !== EVENTS.collectionNameSet || !data?.organization) return; - const requiredFields = [ - "collectionName", - "collectionNodeId", - "projectId", - "organization", - ]; - const missingFields = validateFields(data, requiredFields); - - if (missingFields.length > 0) { - emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionNameSetResponse, - ErrorResponse(missingFields, socket, data.organization), - connectedUsersByOrg - ); - return; - } - const result = await SetCollectionName(data); - console.log('result: ', result); - const status = typeof result?.status === "string" ? result.status : "unknown"; - - const messages: Record = { - Success: { message: "collection name updated" }, - "Collection not found": { message: "Collection not found" }, - "Project not found": { message: "Project not found" }, - - }; - - const msg = messages[status] || { message: "Internal server error" }; - const result_Datas = - status === "Success" && result?.data ? result.data : undefined; - console.log('result_Datas: ', result_Datas); - - const response = FinalResponse( - status, - socket, - data.organization, - messages, - result_Datas - ); - console.log('response: ', response); + if (event !== EVENTS.collectionNameSet || !data?.organization) return; + const requiredFields = [ + "collectionName", + "collectionNodeId", + "projectId", + "organization", + ]; + const missingFields = validateFields(data, requiredFields); + if (missingFields.length > 0) { emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionNameSetResponse, - response, - connectedUsersByOrg + io, + socket, + data.organization, + EVENTS.collectionNameSetResponse, + ErrorResponse(missingFields, socket, data.organization), + connectedUsersByOrg ); + return; + } + const result = await SetCollectionName(data); + console.log("result: ", result); + const status = typeof result?.status === "string" ? result.status : "unknown"; + + const messages: Record = { + Success: { message: "collection name updated" }, + "Collection not found": { message: "Collection not found" }, + "Project not found": { message: "Project not found" }, + }; + + const msg = messages[status] || { message: "Internal server error" }; + const result_Datas = + status === "Success" && result?.data ? result.data : undefined; + console.log("result_Datas: ", result_Datas); + + const response = FinalResponse( + status, + socket, + data.organization, + messages, + result_Datas + ); + console.log("response: ", response); + + emitToSenderAndAdmins( + io, + socket, + data.organization, + EVENTS.collectionNameSetResponse, + response, + connectedUsersByOrg + ); }; export const CollectioDeleteHandleEvent = async ( - event: string, - socket: Socket, - io: Server, - data: any, - connectedUsersByOrg: { - [org: string]: { socketId: string; userId: string; role: string }[]; - } + event: string, + socket: Socket, + io: Server, + data: any, + connectedUsersByOrg: { + [org: string]: { socketId: string; userId: string; role: string }[]; + } ) => { - if (event !== EVENTS.collectionDelete || !data?.organization) return; - const requiredFields = [ - "collectionNodeId", - "projectId", - "organization", - ]; - const missingFields = validateFields(data, requiredFields); - - if (missingFields.length > 0) { - emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionDeleteResponse, - ErrorResponse(missingFields, socket, data.organization), - connectedUsersByOrg - ); - return; - } - const result = await delCollection(data); - console.log('result: ', result); - const status = typeof result?.status === "string" ? result.status : "unknown"; - - const messages: Record = { - Success: { message: "Collection deleted successfully" }, - "Project not found": { message: "Project not found" }, - "Collection not found": { message: "Collection not found" }, - - }; - - const msg = messages[status] || { message: "Internal server error" }; - const result_Datas = - status === "Success" && result?.data ? result.data : undefined; - console.log('result_Datas: ', result_Datas); - - const response = FinalResponse( - status, - socket, - data.organization, - messages, - result_Datas - ); - console.log('response: ', response); + if (event !== EVENTS.collectionDelete || !data?.organization) return; + const requiredFields = ["collectionNodeId", "projectId", "organization"]; + const missingFields = validateFields(data, requiredFields); + if (missingFields.length > 0) { emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionDeleteResponse, - response, - connectedUsersByOrg + io, + socket, + data.organization, + EVENTS.collectionDeleteResponse, + ErrorResponse(missingFields, socket, data.organization), + connectedUsersByOrg ); + return; + } + const result = await delCollection(data); + console.log("result: ", result); + const status = typeof result?.status === "string" ? result.status : "unknown"; + + const messages: Record = { + Success: { message: "Collection deleted successfully" }, + "Project not found": { message: "Project not found" }, + "Collection not found": { message: "Collection not found" }, + }; + + const msg = messages[status] || { message: "Internal server error" }; + const result_Datas = + status === "Success" && result?.data ? result.data : undefined; + console.log("result_Datas: ", result_Datas); + + const response = FinalResponse( + status, + socket, + data.organization, + messages, + result_Datas + ); + console.log("response: ", response); + + emitToSenderAndAdmins( + io, + socket, + data.organization, + EVENTS.collectionDeleteResponse, + response, + connectedUsersByOrg + ); }; export const CollectioDuplicateHandleEvent = async ( - event: string, - socket: Socket, - io: Server, - data: any, - connectedUsersByOrg: { - [org: string]: { socketId: string; userId: string; role: string }[]; - } + event: string, + socket: Socket, + io: Server, + data: any, + connectedUsersByOrg: { + [org: string]: { socketId: string; userId: string; role: string }[]; + } ) => { - if (event !== EVENTS.collectionDuplicate || !data?.organization) return; - const requiredFields = [ - "collectionNodeId", - "projectId", - "organization", - ]; - const missingFields = validateFields(data, requiredFields); - - if (missingFields.length > 0) { - emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionDeleteResponse, - ErrorResponse(missingFields, socket, data.organization), - connectedUsersByOrg - ); - return; - } - const result = await DuplicateCollection(data); - console.log('result: ', result); - const status = typeof result?.status === "string" ? result.status : "unknown"; - - const messages: Record = { - Success: { message: "Collection deleted successfully" }, - "Project not found": { message: "Project not found" }, - "Collection not found": { message: "Collection not found" }, - "Duplication unsuccessfull": { message: "Duplication unsuccessfull" }, - - }; - - const msg = messages[status] || { message: "Internal server error" }; - const result_Datas = - status === "Success" && result?.data ? result.data : undefined; - console.log('result_Datas: ', result_Datas); - - const response = FinalResponse( - status, - socket, - data.organization, - messages, - result_Datas - ); - console.log('response: ', response); + if (event !== EVENTS.collectionDuplicate || !data?.organization) return; + const requiredFields = ["collectionNodeId", "projectId", "organization"]; + const missingFields = validateFields(data, requiredFields); + if (missingFields.length > 0) { emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionDuplicateResponse, - response, - connectedUsersByOrg + io, + socket, + data.organization, + EVENTS.collectionDeleteResponse, + ErrorResponse(missingFields, socket, data.organization), + connectedUsersByOrg ); + return; + } + const result = await DuplicateCollection(data); + console.log("result: ", result); + const status = typeof result?.status === "string" ? result.status : "unknown"; + + const messages: Record = { + Success: { message: "Collection deleted successfully" }, + "Project not found": { message: "Project not found" }, + "Collection not found": { message: "Collection not found" }, + "Duplication unsuccessfull": { message: "Duplication unsuccessfull" }, + }; + + const msg = messages[status] || { message: "Internal server error" }; + const result_Datas = + status === "Success" && result?.data ? result.data : undefined; + console.log("result_Datas: ", result_Datas); + + const response = FinalResponse( + status, + socket, + data.organization, + messages, + result_Datas + ); + console.log("response: ", response); + + emitToSenderAndAdmins( + io, + socket, + data.organization, + EVENTS.collectionDuplicateResponse, + response, + connectedUsersByOrg + ); }; export const setAttributesHandleEvent = async ( - event: string, - socket: Socket, - io: Server, - data: any, - connectedUsersByOrg: { - [org: string]: { socketId: string; userId: string; role: string }[]; - } + event: string, + socket: Socket, + io: Server, + data: any, + connectedUsersByOrg: { + [org: string]: { socketId: string; userId: string; role: string }[]; + } ) => { - if (event !== EVENTS.collectionAttributeSet || !data?.organization) return; - const requiredFields = [ - "attributes", - "collectionNodeId", - "projectId", - "organization", - ]; - const missingFields = validateFields(data, requiredFields); - - if (missingFields.length > 0) { - emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionAttributeSetResponse, - ErrorResponse(missingFields, socket, data.organization), - connectedUsersByOrg - ); - return; - } - const result = await addAttributes(data); - console.log('result: ', result); - const status = typeof result?.status === "string" ? result.status : "unknown"; - - const messages: Record = { - Success: { message: "Collection Attributes Added" }, - "Project not found": { message: "Project not found" }, - "Collection not found": { message: "Collection not found" }, - - - }; - - const msg = messages[status] || { message: "Internal server error" }; - const result_Datas = - status === "Success" && result?.data ? result.data : undefined; - console.log('result_Datas: ', result_Datas); - - const response = FinalResponse( - status, - socket, - data.organization, - messages, - result_Datas - ); - console.log('response: ', response); + if (event !== EVENTS.collectionAttributeSet || !data?.organization) return; + const requiredFields = [ + "attributes", + "collectionNodeId", + "projectId", + "organization", + ]; + const missingFields = validateFields(data, requiredFields); + if (missingFields.length > 0) { emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionAttributeSetResponse, - response, - connectedUsersByOrg + io, + socket, + data.organization, + EVENTS.collectionAttributeSetResponse, + ErrorResponse(missingFields, socket, data.organization), + connectedUsersByOrg ); + return; + } + const result = await addAttributes(data); + console.log("result: ", result); + const status = typeof result?.status === "string" ? result.status : "unknown"; + + const messages: Record = { + Success: { message: "Collection Attributes Added" }, + "Project not found": { message: "Project not found" }, + "Collection not found": { message: "Collection not found" }, + }; + + const msg = messages[status] || { message: "Internal server error" }; + const result_Datas = + status === "Success" && result?.data ? result.data : undefined; + console.log("result_Datas: ", result_Datas); + + const response = FinalResponse( + status, + socket, + data.organization, + messages, + result_Datas + ); + console.log("response: ", response); + + emitToSenderAndAdmins( + io, + socket, + data.organization, + EVENTS.collectionAttributeSetResponse, + response, + connectedUsersByOrg + ); }; export const AttributesDeleteHandleEvent = async ( - event: string, - socket: Socket, - io: Server, - data: any, - connectedUsersByOrg: { - [org: string]: { socketId: string; userId: string; role: string }[]; - } + event: string, + socket: Socket, + io: Server, + data: any, + connectedUsersByOrg: { + [org: string]: { socketId: string; userId: string; role: string }[]; + } ) => { - if (event !== EVENTS.collectionAttributeDelete || !data?.organization) return; - const requiredFields = [ - "attributeId", - "collectionNodeId", - "projectId", - "organization", - ]; - const missingFields = validateFields(data, requiredFields); - - if (missingFields.length > 0) { - emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionAttributeDeleteResponse, - ErrorResponse(missingFields, socket, data.organization), - connectedUsersByOrg - ); - return; - } - const result = await DelAttributes(data); - console.log('result: ', result); - const status = typeof result?.status === "string" ? result.status : "unknown"; - - const messages: Record = { - Success: { message: "Field deleted successfully" }, - "Project not found": { message: "Project not found" }, - "Collection not found": { message: "Collection not found" }, - - - }; - - const msg = messages[status] || { message: "Internal server error" }; - const result_Datas = - status === "Success" && result?.data ? result.data : undefined; - console.log('result_Datas: ', result_Datas); - - const response = FinalResponse( - status, - socket, - data.organization, - messages, - result_Datas - ); - console.log('response: ', response); + if (event !== EVENTS.collectionAttributeDelete || !data?.organization) return; + const requiredFields = [ + "fieldId", + "collectionNodeId", + "projectId", + "organization", + ]; + const missingFields = validateFields(data, requiredFields); + if (missingFields.length > 0) { emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionAttributeDeleteResponse, - response, - connectedUsersByOrg + io, + socket, + data.organization, + EVENTS.collectionAttributeDeleteResponse, + ErrorResponse(missingFields, socket, data.organization), + connectedUsersByOrg ); + return; + } + const result = await DelAttributes(data); + console.log("result: ", result); + const status = typeof result?.status === "string" ? result.status : "unknown"; + + const messages: Record = { + Success: { message: "Field deleted successfully" }, + "Project not found": { message: "Project not found" }, + "Collection not found": { message: "Collection not found" }, + }; + + const msg = messages[status] || { message: "Internal server error" }; + const result_Datas = + status === "Success" && result?.data ? result.data : undefined; + console.log("result_Datas: ", result_Datas); + + const response = FinalResponse( + status, + socket, + data.organization, + messages, + result_Datas + ); + console.log("response: ", response); + + emitToSenderAndAdmins( + io, + socket, + data.organization, + EVENTS.collectionAttributeDeleteResponse, + response, + connectedUsersByOrg + ); }; export const AttributesUpdateHandleEvent = async ( - event: string, - socket: Socket, - io: Server, - data: any, - connectedUsersByOrg: { - [org: string]: { socketId: string; userId: string; role: string }[]; - } + event: string, + socket: Socket, + io: Server, + data: any, + connectedUsersByOrg: { + [org: string]: { socketId: string; userId: string; role: string }[]; + } ) => { - if (event !== EVENTS.collectionAttributeUpdate || !data?.organization) return; - const requiredFields = [ - "attributeId", - "collectionNodeId", - "projectId", - "organization", - ]; - const missingFields = validateFields(data, requiredFields); - - if (missingFields.length > 0) { - emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionAttributeUpdateResponse, - ErrorResponse(missingFields, socket, data.organization), - connectedUsersByOrg - ); - return; - } - const result = await UpdateAttributes(data); - console.log('result: ', result); - const status = typeof result?.status === "string" ? result.status : "unknown"; - - const messages: Record = { - Success: { message: "Field updated successfully" }, - "Project not found": { message: "Project not found" }, - "Collection not found": { message: "Collection not found" }, - - - }; - - const msg = messages[status] || { message: "Internal server error" }; - const result_Datas = - status === "Success" && result?.data ? result.data : undefined; - console.log('result_Datas: ', result_Datas); - - const response = FinalResponse( - status, - socket, - data.organization, - messages, - result_Datas - ); - console.log('response: ', response); + if (event !== EVENTS.collectionAttributeUpdate || !data?.organization) return; + const requiredFields = [ + "fieldId", + "collectionNodeId", + "projectId", + "organization", + ]; + const missingFields = validateFields(data, requiredFields); + if (missingFields.length > 0) { emitToSenderAndAdmins( - io, - socket, - data.organization, - EVENTS.collectionAttributeUpdateResponse, - response, - connectedUsersByOrg + io, + socket, + data.organization, + EVENTS.collectionAttributeUpdateResponse, + ErrorResponse(missingFields, socket, data.organization), + connectedUsersByOrg ); -}; \ No newline at end of file + return; + } + const result = await UpdateAttributes(data); + console.log("result: ", result); + const status = typeof result?.status === "string" ? result.status : "unknown"; + + const messages: Record = { + Success: { message: "Field updated successfully" }, + "Project not found": { message: "Project not found" }, + "Collection not found": { message: "Collection not found" }, + }; + + const msg = messages[status] || { message: "Internal server error" }; + const result_Datas = + status === "Success" && result?.data ? result.data : undefined; + console.log("result_Datas: ", result_Datas); + + const response = FinalResponse( + status, + socket, + data.organization, + messages, + result_Datas + ); + console.log("response: ", response); + + emitToSenderAndAdmins( + io, + socket, + data.organization, + EVENTS.collectionAttributeUpdateResponse, + response, + connectedUsersByOrg + ); +};