(userId: string, orgId: number)
| 186 | } |
| 187 | |
| 188 | export const addUserToOrganization = async (userId: string, orgId: number): Promise<{ success: boolean } | ServiceError> => { |
| 189 | const user = await __unsafePrisma.user.findUnique({ |
| 190 | where: { |
| 191 | id: userId, |
| 192 | }, |
| 193 | }); |
| 194 | |
| 195 | if (!user) { |
| 196 | logger.error(`addUserToOrganization: user not found for id ${userId}`); |
| 197 | return userNotFound(); |
| 198 | } |
| 199 | |
| 200 | const org = await __unsafePrisma.org.findUnique({ |
| 201 | where: { |
| 202 | id: orgId, |
| 203 | }, |
| 204 | }); |
| 205 | |
| 206 | if (!org) { |
| 207 | logger.error(`addUserToOrganization: org not found for id ${orgId}`); |
| 208 | return orgNotFound(); |
| 209 | } |
| 210 | |
| 211 | const hasAvailability = await orgHasAvailability(org.id); |
| 212 | if (!hasAvailability) { |
| 213 | return { |
| 214 | statusCode: StatusCodes.BAD_REQUEST, |
| 215 | errorCode: ErrorCode.ORG_SEAT_COUNT_REACHED, |
| 216 | message: "Organization is at max capacity", |
| 217 | } satisfies ServiceError; |
| 218 | } |
| 219 | |
| 220 | const hasOrgManagement = await hasEntitlement('org-management'); |
| 221 | |
| 222 | await __unsafePrisma.$transaction(async (tx) => { |
| 223 | // Upsert rather than create: the user may already be a member from the |
| 224 | // self-serve auto-join in onCreateUser, in which case this call is |
| 225 | // just here to trigger the AccountRequest / Invite cleanup below. |
| 226 | await tx.userToOrg.upsert({ |
| 227 | where: { |
| 228 | orgId_userId: { |
| 229 | orgId: org.id, |
| 230 | userId: user.id, |
| 231 | }, |
| 232 | }, |
| 233 | create: { |
| 234 | userId: user.id, |
| 235 | orgId: org.id, |
| 236 | role: hasOrgManagement ? OrgRole.MEMBER : OrgRole.OWNER, |
| 237 | }, |
| 238 | update: {}, |
| 239 | }); |
| 240 | |
| 241 | // Delete the account request if it exists since we've added the user to the org |
| 242 | const accountRequest = await tx.accountRequest.findUnique({ |
| 243 | where: { |
| 244 | requestedById_orgId: { |
| 245 | requestedById: user.id, |
no test coverage detected