2025-07-15 03:14:41 +00:00
|
|
|
"use server";
|
|
|
|
|
|
|
|
|
|
import { isServiceError } from "@/lib/utils";
|
2025-09-24 04:30:00 +00:00
|
|
|
import { notAuthenticated, orgNotFound, ServiceError } from "@/lib/serviceError";
|
|
|
|
|
import { sew } from "@/sew";
|
2025-07-15 03:14:41 +00:00
|
|
|
import { addUserToOrganization } from "@/lib/authUtils";
|
|
|
|
|
import { prisma } from "@/prisma";
|
|
|
|
|
import { StatusCodes } from "http-status-codes";
|
|
|
|
|
import { ErrorCode } from "@/lib/errorCodes";
|
2025-09-24 04:30:00 +00:00
|
|
|
import { withOptionalAuthV2 } from "@/withAuthV2";
|
2025-07-15 03:14:41 +00:00
|
|
|
|
2025-08-22 18:48:29 +00:00
|
|
|
export const joinOrganization = async (orgId: number, inviteLinkId?: string) => sew(async () =>
|
2025-09-24 04:30:00 +00:00
|
|
|
withOptionalAuthV2(async ({ user }) => {
|
|
|
|
|
if (!user) {
|
|
|
|
|
return notAuthenticated();
|
|
|
|
|
}
|
|
|
|
|
|
2025-07-15 03:14:41 +00:00
|
|
|
const org = await prisma.org.findUnique({
|
|
|
|
|
where: {
|
|
|
|
|
id: orgId,
|
|
|
|
|
},
|
|
|
|
|
});
|
|
|
|
|
|
|
|
|
|
if (!org) {
|
|
|
|
|
return orgNotFound();
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// If member approval is required we must be using a valid invite link
|
|
|
|
|
if (org.memberApprovalRequired) {
|
|
|
|
|
if (!org.inviteLinkEnabled) {
|
|
|
|
|
return {
|
|
|
|
|
statusCode: StatusCodes.BAD_REQUEST,
|
|
|
|
|
errorCode: ErrorCode.INVITE_LINK_NOT_ENABLED,
|
|
|
|
|
message: "Invite link is not enabled.",
|
|
|
|
|
} satisfies ServiceError;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
if (org.inviteLinkId !== inviteLinkId) {
|
|
|
|
|
return {
|
|
|
|
|
statusCode: StatusCodes.BAD_REQUEST,
|
|
|
|
|
errorCode: ErrorCode.INVALID_INVITE_LINK,
|
|
|
|
|
message: "Invalid invite link.",
|
|
|
|
|
} satisfies ServiceError;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-24 04:30:00 +00:00
|
|
|
const addUserToOrgRes = await addUserToOrganization(user.id, org.id);
|
2025-07-15 03:14:41 +00:00
|
|
|
if (isServiceError(addUserToOrgRes)) {
|
|
|
|
|
return addUserToOrgRes;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return {
|
|
|
|
|
success: true,
|
|
|
|
|
}
|
|
|
|
|
})
|
|
|
|
|
)
|