-
- {shareBrainList.map((b) => (
-
- ))}
-
- {hasMoreBrains && !isAtBottom &&
}
+
+ {shareBrainList.map((b) => (
+
+ ))}
)}
>
diff --git a/nextjs/src/hooks/brains/useLeaveBrain.ts b/nextjs/src/hooks/brains/useLeaveBrain.ts
new file mode 100644
index 00000000..4851730a
--- /dev/null
+++ b/nextjs/src/hooks/brains/useLeaveBrain.ts
@@ -0,0 +1,62 @@
+import { useState } from "react";
+import Toast from "@/utils/toast";
+import { leaveBrainAction } from "@/actions/brains";
+
+export const useLeaveBrain = ({
+ onLeaveSuccess,
+}: { onLeaveSuccess?: (brainId: string) => void } = {}) => {
+ const [isLeaving, setIsLeaving] = useState(false);
+ const [leftBrains, setLeftBrains] = useState
(() => {
+ if (typeof window !== "undefined") {
+ return JSON.parse(sessionStorage.getItem("leftBrains") || "[]");
+ }
+ return [];
+ });
+
+ const leaveBrain = async (brainId: string) => {
+ setIsLeaving(true);
+ try {
+ const result = await leaveBrainAction(brainId);
+
+ if (result?.status === 200) {
+ Toast(result.message);
+
+ const updatedLeftBrains = [...leftBrains, brainId];
+ setLeftBrains(updatedLeftBrains);
+
+ if (typeof window !== "undefined") {
+ sessionStorage.setItem(
+ "leftBrains",
+ JSON.stringify(updatedLeftBrains)
+ );
+ }
+
+ onLeaveSuccess?.(brainId);
+
+ setTimeout(() => {
+ window.location.href = "/";
+ }, 1000);
+ } else {
+ throw new Error(result?.message);
+ }
+ } catch (error: any) {
+ Toast(error?.message);
+ } finally {
+ setIsLeaving(false);
+ }
+ };
+
+ const isBrainLeft = (brainId: string) => leftBrains.includes(brainId);
+
+ const resetLeftBrain = (brainId: string) => {
+ const updatedLeftBrains = leftBrains.filter((id) => id !== brainId);
+ setLeftBrains(updatedLeftBrains);
+ if (typeof window !== "undefined") {
+ sessionStorage.setItem("leftBrains", JSON.stringify(updatedLeftBrains));
+ }
+ };
+
+ return { leaveBrain, isLeaving, isBrainLeft, resetLeftBrain, leftBrains };
+};
+
+export default useLeaveBrain;
diff --git a/nextjs/src/utils/constant.ts b/nextjs/src/utils/constant.ts
index 1bccfdf9..252f5940 100644
--- a/nextjs/src/utils/constant.ts
+++ b/nextjs/src/utils/constant.ts
@@ -84,6 +84,7 @@ export const MODULE_ACTIONS = {
EXPORT: 'export',
SIGNUP: 'register',
SEND_MAIL: 'sendMail',
+ LEAVE: 'leave',
FORGOT_PASSWORD: 'forgotPassword',
RESET_PASSWORD: 'resetPassword',
SEND_MAIL_NOTIFICATION: 'sendMailNotification',
@@ -181,7 +182,12 @@ export const PASSWORD_REGEX_MESSAGE = 'Your password must contain at least one u
export const EMAIL_REGEX_MESSAGE = 'Please enter your email address.';
export const ALREADY_PRESENT_EMAIL_MESSAGE = 'Email already exist';
export const STORAGE_INCREASE_REQUEST = 'Storage request received. Admin will contact you soon.';
-export const BRAIN_MEMBER_ADDED = 'Member has been successfully added to the brain';
+export const BRAIN_MEMBER_ADDED = 'Member has been successfully added to the brain';
+export const BRAIN_ID_REQUIRED = 'Brain ID is required';
+export const LEAVE_BRAIN_SUCCESS = 'You have successfully left the brain';
+export const LEAVE_BRAIN_ERROR = 'Unable to leave the brain. Please try again';
+export const CONVERT_TO_SHARED_SUCCESS = 'Brain converted to shared successfully';
+export const CONVERT_TO_SHARED_ERROR = 'Unable to convert brain to shared. Please try again';
export const FILE_SIZE_MESSAGE = 'Please upload less than 5 MB file';
export const PROFILE_IMG_SIZE_MESSAGE = 'Please upload less than 500 KB file';
export const API_KEY_MESSAGE = 'API key is required';
diff --git a/nodejs/resources/lang/en/common.json b/nodejs/resources/lang/en/common.json
index 437fb6db..ee59970d 100644
--- a/nodejs/resources/lang/en/common.json
+++ b/nodejs/resources/lang/en/common.json
@@ -43,7 +43,10 @@
"unfavorite": "{module} removed from Favourites",
"unfavoriteError": "Error occured while unfavoriting {module}",
"credit_expired": "Your credit limit has been reached. Please contact your administrator to increase your credit limit.",
- "trial_expired": "Your trial period has expired. Please upgrade to a paid plan to continue using our services."
+ "trial_expired": "Your trial period has expired. Please upgrade to a paid plan to continue using our services.",
+ "leave": "You have left the {module} successfully",
+ "leaveError": "Error occurred while leaving the {module}"
+
},
"import": {
"not_found": "Import chat not found",
diff --git a/nodejs/src/controller/web/brainController.js b/nodejs/src/controller/web/brainController.js
index 40cae32b..c83d2f43 100644
--- a/nodejs/src/controller/web/brainController.js
+++ b/nodejs/src/controller/web/brainController.js
@@ -121,13 +121,13 @@ const workspaceWiseList = catchAsync(async (req, res) => {
return util.recordNotFound(null, res);
})
-const convertToShared = catchAsync(async (req, res) => {
- const result = await brainService.convertToShared(req);
+const leaveBrain = catchAsync(async (req, res) => {
+ const result = await brainService.leaveBrain(req);
if (result) {
- res.message = _localize('module.convertToShared', req, BRAIN);
+ res.message = _localize('module.leave', req, BRAIN);
return util.successResponse(result, res);
}
- return util.failureResponse(_localize('module.convertToSharedError', req, BRAIN), res);
+ return util.failureResponse(_localize('module.leaveError', req, BRAIN), res);
})
module.exports = {
@@ -144,6 +144,6 @@ module.exports = {
restoreBrain,
deleteAllBrain,
workspaceWiseList,
- convertToShared
+ leaveBrain
}
diff --git a/nodejs/src/routes/web/brains.js b/nodejs/src/routes/web/brains.js
index cc95a8ca..f2ac9b30 100644
--- a/nodejs/src/routes/web/brains.js
+++ b/nodejs/src/routes/web/brains.js
@@ -18,6 +18,6 @@ router.post('/share-doc', validate(shareDocKeys), authentication, brainControlle
router.post('/share/list', authentication, checkPromptLimit, brainController.shareList);
router.post('/restore/:id', authentication, brainController.restoreBrain);
router.post('/list-all', authentication, checkPromptLimit, brainController.workspaceWiseList);
-router.put('/convert-to-shared/:id', validate(convertToSharedKeys), authentication, checkPromptLimit, brainController.convertToShared);
+router.post('/:id/leave', authentication, brainController.leaveBrain);
module.exports = router;
\ No newline at end of file
diff --git a/nodejs/src/services/brain.js b/nodejs/src/services/brain.js
index 9d2bf841..76d44af2 100644
--- a/nodejs/src/services/brain.js
+++ b/nodejs/src/services/brain.js
@@ -554,75 +554,45 @@ async function getBrainStatus(brains) {
}
}
-const convertToShared = async (req) => {
+const leaveBrain = async (req) => {
try {
- const { isPrivateBrainVisible } = req.user;
- const brainId = req.params.id;
- const { shareWith = [], teams = [], customInstruction } = req.body;
+ const { id: brainId } = req.params;
+ const userId = req.user.id;
- if (!isPrivateBrainVisible) {
- throw new Error(_localize('module.unAuthorized', req, 'Brain'));
- }
-
- // Find the private brain and ensure ownership
- const existingBrain = await Brain.findOne({
- _id: brainId,
- 'user.id': req.userId,
- isShare: false
- });
-
- if (!existingBrain) {
+ const brain = await Brain.findById(brainId);
+ if (!brain) {
throw new Error(_localize('module.notFound', req, 'Brain'));
}
- // Check workspace access
- const accessOfWorkspace = await accessOfWorkspaceToUser({
- workspaceId: existingBrain.workspaceId,
- userId: req.user.id
- });
-
- if (!accessOfWorkspace) {
- throw new Error(_localize('module.unAuthorized', req, 'Brain'));
+ if (brain.user.id.toString() === userId) {
+ throw new Error(_localize('brain.creatorCannotLeave', req));
}
- // Convert to shared brain
- const updateData = {
- isShare: true,
- ...(customInstruction !== undefined && { customInstruction })
- };
-
- const updatedBrain = await Brain.findOneAndUpdate(
- { _id: brainId },
- updateData,
- { new: true }
- );
-
- // Handle owner's share record - ensure owner has access
- await shareBrainFormat(req, updatedBrain);
+ const shareBrain = await ShareBrain.findOne({
+ 'brain.id': brainId,
+ 'user.id': userId
+ });
- // Add members if provided
- if (shareWith.length > 0) {
- await Promise.all([
- shareBrainWithUser(shareWith, updatedBrain, req),
- addWorkSpaceUsers(shareWith, { _id: updatedBrain.workspaceId }, req.user)
- ]);
+ if (!shareBrain) {
+ throw new Error(_localize('brain.notMember', req));
}
- // Add teams if provided
- if (teams.length > 0) {
- const workspace = await Workspace.findById(updatedBrain.workspaceId);
- await Promise.all([
- addWorkSpaceTeam(teams, workspace, req.user),
- addShareBrainTeam(teams, updatedBrain, req.user),
- addBrainChatMember(updatedBrain, teams, req.user.id, true)
- ]);
- }
+ await ShareBrain.deleteOne({
+ 'brain.id': brainId,
+ 'user.id': userId
+ });
- return updatedBrain;
+ await removeBrainChatMember(brainId, userId);
+
+ return {
+ status: 200,
+ message: _localize('module.leave', req, 'Brain'),
+ data: {}
+ };
} catch (error) {
- handleError(error, 'Error - convertToShared');
+ handleError(error, 'Error - leaveBrain');
}
-};
+}
module.exports = {
createBrain,
@@ -646,6 +616,6 @@ module.exports = {
getBrainStatus,
getGeneralBrain,
defaultGeneralBrainMember,
- convertToShared,
+ leaveBrain
}
\ No newline at end of file