chore: import upstream snapshot with attribution
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
CI / Migrate Dev DB (push) Has been skipped
CI / Detect Version (push) Has been cancelled
CI / Migrate DB (push) Has been cancelled
CI / Build Dev ECR (./docker/app.Dockerfile, ECR_APP) (push) Has been cancelled
CI / Build Dev ECR (./docker/db.Dockerfile, ECR_MIGRATIONS) (push) Has been cancelled
CI / Build Dev ECR (./docker/pii.Dockerfile, ECR_PII) (push) Has been cancelled
CI / Build Dev ECR (./docker/realtime.Dockerfile, ECR_REALTIME) (push) Has been cancelled
CI / Deploy Trigger.dev (Dev) (push) Has been cancelled
CI / Build AMD64 (./docker/app.Dockerfile, ECR_APP, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build AMD64 (./docker/db.Dockerfile, ECR_MIGRATIONS, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build AMD64 (./docker/pii.Dockerfile, ECR_PII, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build AMD64 (./docker/realtime.Dockerfile, ECR_REALTIME, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/app.Dockerfile, ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/db.Dockerfile, ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/pii.Dockerfile, ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Build ARM64 (GHCR Only) (./docker/realtime.Dockerfile, ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/migrations) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/pii) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/realtime) (push) Has been cancelled
CI / Create GHCR Manifests (ghcr.io/simstudioai/simstudio) (push) Has been cancelled
CI / Check Docs Changes (push) Has been cancelled
CI / Process Docs (push) Has been cancelled
CI / Create GitHub Release (push) Has been cancelled
CI / Test and Build (push) Has been cancelled
Publish CLI Package / publish-npm (push) Has been cancelled
Publish Python SDK / publish-pypi (push) Has been cancelled
Publish TypeScript SDK / publish-npm (push) Has been cancelled
This commit is contained in:
@@ -0,0 +1,205 @@
|
||||
/**
|
||||
* GET /api/v1/admin/organizations/[id]/billing
|
||||
*
|
||||
* Get organization billing summary including usage, seats, and member data.
|
||||
*
|
||||
* Response: AdminSingleResponse<AdminOrganizationBillingSummary>
|
||||
*
|
||||
* PATCH /api/v1/admin/organizations/[id]/billing
|
||||
*
|
||||
* Update organization billing settings.
|
||||
*
|
||||
* Body:
|
||||
* - orgUsageLimit?: number - New usage limit (null to clear)
|
||||
*
|
||||
* Response: AdminSingleResponse<{ success: true, orgUsageLimit: string | null }>
|
||||
*/
|
||||
|
||||
import { db, dbReplica } from '@sim/db'
|
||||
import { member, organization } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { count, eq } from 'drizzle-orm'
|
||||
import {
|
||||
adminV1GetOrganizationBillingContract,
|
||||
adminV1UpdateOrganizationBillingContract,
|
||||
} from '@/lib/api/contracts/v1/admin'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { getOrganizationBillingData } from '@/lib/billing/core/organization'
|
||||
import { isBillingEnabled } from '@/lib/core/config/env-flags'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { withAdminAuthParams } from '@/app/api/v1/admin/middleware'
|
||||
import {
|
||||
adminValidationErrorResponse,
|
||||
badRequestResponse,
|
||||
internalErrorResponse,
|
||||
notFoundResponse,
|
||||
singleResponse,
|
||||
} from '@/app/api/v1/admin/responses'
|
||||
import type { AdminOrganizationBillingSummary } from '@/app/api/v1/admin/types'
|
||||
|
||||
const logger = createLogger('AdminOrganizationBillingAPI')
|
||||
|
||||
interface RouteParams {
|
||||
id: string
|
||||
}
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1GetOrganizationBillingContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: organizationId } = parsed.data.params
|
||||
|
||||
try {
|
||||
if (!isBillingEnabled) {
|
||||
const [[orgData], [memberCount]] = await Promise.all([
|
||||
db
|
||||
.select({ id: organization.id, name: organization.name })
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1),
|
||||
db
|
||||
.select({ count: count() })
|
||||
.from(member)
|
||||
.where(eq(member.organizationId, organizationId)),
|
||||
])
|
||||
|
||||
if (!orgData) {
|
||||
return notFoundResponse('Organization')
|
||||
}
|
||||
|
||||
const data: AdminOrganizationBillingSummary = {
|
||||
organizationId: orgData.id,
|
||||
organizationName: orgData.name,
|
||||
subscriptionPlan: 'none',
|
||||
subscriptionStatus: 'none',
|
||||
totalSeats: Number.MAX_SAFE_INTEGER,
|
||||
usedSeats: memberCount?.count || 0,
|
||||
availableSeats: Number.MAX_SAFE_INTEGER,
|
||||
totalCurrentUsage: 0,
|
||||
totalUsageLimit: Number.MAX_SAFE_INTEGER,
|
||||
minimumBillingAmount: 0,
|
||||
averageUsagePerMember: 0,
|
||||
usagePercentage: 0,
|
||||
billingPeriodStart: null,
|
||||
billingPeriodEnd: null,
|
||||
membersOverLimit: 0,
|
||||
membersNearLimit: 0,
|
||||
}
|
||||
|
||||
logger.info(
|
||||
`Admin API: Retrieved billing summary for organization ${organizationId} (billing disabled)`
|
||||
)
|
||||
|
||||
return singleResponse(data)
|
||||
}
|
||||
|
||||
const billingData = await getOrganizationBillingData(organizationId, dbReplica)
|
||||
|
||||
if (!billingData) {
|
||||
return notFoundResponse('Organization or subscription')
|
||||
}
|
||||
|
||||
const membersOverLimit = billingData.members.filter((m) => m.isOverLimit).length
|
||||
const membersNearLimit = billingData.members.filter(
|
||||
(m) => !m.isOverLimit && m.percentUsed >= 80
|
||||
).length
|
||||
const usagePercentage =
|
||||
billingData.totalUsageLimit > 0
|
||||
? Math.round((billingData.totalCurrentUsage / billingData.totalUsageLimit) * 10000) / 100
|
||||
: 0
|
||||
|
||||
const data: AdminOrganizationBillingSummary = {
|
||||
organizationId: billingData.organizationId,
|
||||
organizationName: billingData.organizationName,
|
||||
subscriptionPlan: billingData.subscriptionPlan,
|
||||
subscriptionStatus: billingData.subscriptionStatus,
|
||||
totalSeats: billingData.totalSeats,
|
||||
usedSeats: billingData.usedSeats,
|
||||
availableSeats: billingData.totalSeats - billingData.usedSeats,
|
||||
totalCurrentUsage: billingData.totalCurrentUsage,
|
||||
totalUsageLimit: billingData.totalUsageLimit,
|
||||
minimumBillingAmount: billingData.minimumBillingAmount,
|
||||
averageUsagePerMember: billingData.averageUsagePerMember,
|
||||
usagePercentage,
|
||||
billingPeriodStart: billingData.billingPeriodStart?.toISOString() ?? null,
|
||||
billingPeriodEnd: billingData.billingPeriodEnd?.toISOString() ?? null,
|
||||
membersOverLimit,
|
||||
membersNearLimit,
|
||||
}
|
||||
|
||||
logger.info(`Admin API: Retrieved billing summary for organization ${organizationId}`)
|
||||
|
||||
return singleResponse(data)
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to get organization billing', { error, organizationId })
|
||||
return internalErrorResponse('Failed to get organization billing')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
export const PATCH = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const routeParams = await context.params
|
||||
const { id: organizationId } = routeParams
|
||||
|
||||
try {
|
||||
const parsed = await parseRequest(
|
||||
adminV1UpdateOrganizationBillingContract,
|
||||
request,
|
||||
{ params: routeParams },
|
||||
{
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
invalidJson: 'throw',
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const [orgData] = await db
|
||||
.select()
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1)
|
||||
|
||||
if (!orgData) {
|
||||
return notFoundResponse('Organization')
|
||||
}
|
||||
|
||||
const { orgUsageLimit } = parsed.data.body
|
||||
|
||||
if (orgUsageLimit !== undefined) {
|
||||
let newLimit: string | null = null
|
||||
|
||||
if (orgUsageLimit === null) {
|
||||
newLimit = null
|
||||
} else {
|
||||
newLimit = orgUsageLimit.toFixed(2)
|
||||
}
|
||||
|
||||
await db
|
||||
.update(organization)
|
||||
.set({
|
||||
orgUsageLimit: newLimit,
|
||||
updatedAt: new Date(),
|
||||
})
|
||||
.where(eq(organization.id, organizationId))
|
||||
|
||||
logger.info(`Admin API: Updated usage limit for organization ${organizationId}`, {
|
||||
newLimit,
|
||||
})
|
||||
|
||||
return singleResponse({
|
||||
success: true,
|
||||
orgUsageLimit: newLimit,
|
||||
})
|
||||
}
|
||||
|
||||
return badRequestResponse('No valid fields to update')
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to update organization billing', { error, organizationId })
|
||||
return internalErrorResponse('Failed to update organization billing')
|
||||
}
|
||||
})
|
||||
)
|
||||
@@ -0,0 +1,322 @@
|
||||
/**
|
||||
* GET /api/v1/admin/organizations/[id]/members/[memberId]
|
||||
*
|
||||
* Get member details.
|
||||
*
|
||||
* Response: AdminSingleResponse<AdminMemberDetail>
|
||||
*
|
||||
* PATCH /api/v1/admin/organizations/[id]/members/[memberId]
|
||||
*
|
||||
* Update member role.
|
||||
*
|
||||
* Body:
|
||||
* - role: string - New role ('admin' | 'member')
|
||||
*
|
||||
* Response: AdminSingleResponse<AdminMember>
|
||||
*
|
||||
* DELETE /api/v1/admin/organizations/[id]/members/[memberId]
|
||||
*
|
||||
* Remove member from organization with full billing logic.
|
||||
* Handles departed usage capture and Pro restoration like the regular flow.
|
||||
*
|
||||
* Query Parameters:
|
||||
* - skipBillingLogic: boolean - Skip billing logic (default: false)
|
||||
*
|
||||
* Response: { success: true, memberId: string, billingActions: {...} }
|
||||
*/
|
||||
|
||||
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
|
||||
import { db } from '@sim/db'
|
||||
import { member, organization, user, userStats } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { and, eq } from 'drizzle-orm'
|
||||
import {
|
||||
adminV1GetOrganizationMemberContract,
|
||||
adminV1RemoveOrganizationMemberContract,
|
||||
adminV1UpdateOrganizationMemberContract,
|
||||
} from '@/lib/api/contracts/v1/admin'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { getOrgMemberLedgerByUser } from '@/lib/billing/core/organization'
|
||||
import {
|
||||
removeUserFromOrganization,
|
||||
WORKSPACE_BILLING_ACCOUNT_REMOVAL_ERROR,
|
||||
} from '@/lib/billing/organizations/membership'
|
||||
import { isBillingEnabled } from '@/lib/core/config/env-flags'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { withAdminAuthParams } from '@/app/api/v1/admin/middleware'
|
||||
import {
|
||||
adminValidationErrorResponse,
|
||||
badRequestResponse,
|
||||
internalErrorResponse,
|
||||
notFoundResponse,
|
||||
singleResponse,
|
||||
} from '@/app/api/v1/admin/responses'
|
||||
import type { AdminMember, AdminMemberDetail } from '@/app/api/v1/admin/types'
|
||||
|
||||
const logger = createLogger('AdminOrganizationMemberDetailAPI')
|
||||
|
||||
interface RouteParams {
|
||||
id: string
|
||||
memberId: string
|
||||
}
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1GetOrganizationMemberContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: organizationId, memberId } = parsed.data.params
|
||||
|
||||
try {
|
||||
const [orgData] = await db
|
||||
.select({ id: organization.id })
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1)
|
||||
|
||||
if (!orgData) {
|
||||
return notFoundResponse('Organization')
|
||||
}
|
||||
|
||||
const [memberData] = await db
|
||||
.select({
|
||||
id: member.id,
|
||||
userId: member.userId,
|
||||
organizationId: member.organizationId,
|
||||
role: member.role,
|
||||
createdAt: member.createdAt,
|
||||
userName: user.name,
|
||||
userEmail: user.email,
|
||||
currentPeriodCost: userStats.currentPeriodCost,
|
||||
currentUsageLimit: userStats.currentUsageLimit,
|
||||
billingBlocked: userStats.billingBlocked,
|
||||
})
|
||||
.from(member)
|
||||
.innerJoin(user, eq(member.userId, user.id))
|
||||
.leftJoin(userStats, eq(member.userId, userStats.userId))
|
||||
.where(and(eq(member.id, memberId), eq(member.organizationId, organizationId)))
|
||||
.limit(1)
|
||||
|
||||
if (!memberData) {
|
||||
return notFoundResponse('Member')
|
||||
}
|
||||
|
||||
// currentPeriodCost is only a baseline; add this member's attributed
|
||||
// usage_log for the org's period so admin shows real current usage.
|
||||
const ledgerByUser = await getOrgMemberLedgerByUser(organizationId)
|
||||
|
||||
const data: AdminMemberDetail = {
|
||||
id: memberData.id,
|
||||
userId: memberData.userId,
|
||||
organizationId: memberData.organizationId,
|
||||
role: memberData.role,
|
||||
createdAt: memberData.createdAt.toISOString(),
|
||||
userName: memberData.userName,
|
||||
userEmail: memberData.userEmail,
|
||||
currentPeriodCost: (
|
||||
Number(memberData.currentPeriodCost ?? 0) + (ledgerByUser.get(memberData.userId) ?? 0)
|
||||
).toString(),
|
||||
currentUsageLimit: memberData.currentUsageLimit,
|
||||
billingBlocked: memberData.billingBlocked ?? false,
|
||||
}
|
||||
|
||||
logger.info(`Admin API: Retrieved member ${memberId} from organization ${organizationId}`)
|
||||
|
||||
return singleResponse(data)
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to get member', { error, organizationId, memberId })
|
||||
return internalErrorResponse('Failed to get member')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
export const PATCH = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const routeParams = await context.params
|
||||
const { id: organizationId, memberId } = routeParams
|
||||
|
||||
try {
|
||||
const parsed = await parseRequest(
|
||||
adminV1UpdateOrganizationMemberContract,
|
||||
request,
|
||||
{ params: routeParams },
|
||||
{
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
invalidJson: 'throw',
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { role } = parsed.data.body
|
||||
|
||||
const [orgData] = await db
|
||||
.select({ id: organization.id })
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1)
|
||||
|
||||
if (!orgData) {
|
||||
return notFoundResponse('Organization')
|
||||
}
|
||||
|
||||
const [existingMember] = await db
|
||||
.select({
|
||||
id: member.id,
|
||||
userId: member.userId,
|
||||
role: member.role,
|
||||
})
|
||||
.from(member)
|
||||
.where(and(eq(member.id, memberId), eq(member.organizationId, organizationId)))
|
||||
.limit(1)
|
||||
|
||||
if (!existingMember) {
|
||||
return notFoundResponse('Member')
|
||||
}
|
||||
|
||||
if (existingMember.role === 'owner') {
|
||||
return badRequestResponse('Cannot change owner role')
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(member)
|
||||
.set({ role })
|
||||
.where(eq(member.id, memberId))
|
||||
.returning()
|
||||
|
||||
const [userData] = await db
|
||||
.select({ name: user.name, email: user.email })
|
||||
.from(user)
|
||||
.where(eq(user.id, updated.userId))
|
||||
.limit(1)
|
||||
|
||||
const data: AdminMember = {
|
||||
id: updated.id,
|
||||
userId: updated.userId,
|
||||
organizationId: updated.organizationId,
|
||||
role: updated.role,
|
||||
createdAt: updated.createdAt.toISOString(),
|
||||
userName: userData?.name ?? '',
|
||||
userEmail: userData?.email ?? '',
|
||||
}
|
||||
|
||||
logger.info(`Admin API: Updated member ${memberId} role to ${role}`, {
|
||||
organizationId,
|
||||
previousRole: existingMember.role,
|
||||
})
|
||||
|
||||
recordAudit({
|
||||
workspaceId: null,
|
||||
actorId: 'admin-api',
|
||||
action: AuditAction.ORG_MEMBER_ROLE_CHANGED,
|
||||
resourceType: AuditResourceType.ORGANIZATION,
|
||||
resourceId: organizationId,
|
||||
description: `Admin API changed organization member role to ${role}`,
|
||||
metadata: {
|
||||
memberId,
|
||||
targetUserId: existingMember.userId,
|
||||
previousRole: existingMember.role,
|
||||
role,
|
||||
},
|
||||
request,
|
||||
})
|
||||
|
||||
return singleResponse(data)
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to update member', { error, organizationId, memberId })
|
||||
return internalErrorResponse('Failed to update member')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
export const DELETE = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1RemoveOrganizationMemberContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: organizationId, memberId } = parsed.data.params
|
||||
const skipBillingLogic = !isBillingEnabled || parsed.data.query.skipBillingLogic
|
||||
|
||||
try {
|
||||
const [orgData] = await db
|
||||
.select({ id: organization.id })
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1)
|
||||
|
||||
if (!orgData) {
|
||||
return notFoundResponse('Organization')
|
||||
}
|
||||
|
||||
const [existingMember] = await db
|
||||
.select({
|
||||
id: member.id,
|
||||
userId: member.userId,
|
||||
role: member.role,
|
||||
})
|
||||
.from(member)
|
||||
.where(and(eq(member.id, memberId), eq(member.organizationId, organizationId)))
|
||||
.limit(1)
|
||||
|
||||
if (!existingMember) {
|
||||
return notFoundResponse('Member')
|
||||
}
|
||||
|
||||
const userId = existingMember.userId
|
||||
|
||||
const result = await removeUserFromOrganization({
|
||||
userId,
|
||||
organizationId,
|
||||
memberId,
|
||||
skipBillingLogic,
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
if (result.error === 'Cannot remove organization owner') {
|
||||
return badRequestResponse(result.error)
|
||||
}
|
||||
if (result.error === 'Member not found') {
|
||||
return notFoundResponse('Member')
|
||||
}
|
||||
if (result.error === WORKSPACE_BILLING_ACCOUNT_REMOVAL_ERROR) {
|
||||
return badRequestResponse(result.error)
|
||||
}
|
||||
return internalErrorResponse(result.error || 'Failed to remove member')
|
||||
}
|
||||
|
||||
logger.info(`Admin API: Removed member ${memberId} from organization ${organizationId}`, {
|
||||
userId,
|
||||
billingActions: result.billingActions,
|
||||
})
|
||||
|
||||
recordAudit({
|
||||
workspaceId: null,
|
||||
actorId: 'admin-api',
|
||||
action: AuditAction.ORG_MEMBER_REMOVED,
|
||||
resourceType: AuditResourceType.ORGANIZATION,
|
||||
resourceId: organizationId,
|
||||
description: 'Admin API removed member from organization',
|
||||
metadata: { memberId, targetUserId: userId },
|
||||
request,
|
||||
})
|
||||
|
||||
return singleResponse({
|
||||
success: true,
|
||||
memberId,
|
||||
userId,
|
||||
billingActions: {
|
||||
usageCaptured: result.billingActions.usageCaptured,
|
||||
proRestored: result.billingActions.proRestored,
|
||||
usageRestored: result.billingActions.usageRestored,
|
||||
skipBillingLogic,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to remove member', { error, organizationId, memberId })
|
||||
return internalErrorResponse('Failed to remove member')
|
||||
}
|
||||
})
|
||||
)
|
||||
@@ -0,0 +1,307 @@
|
||||
/**
|
||||
* GET /api/v1/admin/organizations/[id]/members
|
||||
*
|
||||
* List all members of an organization with their billing info.
|
||||
*
|
||||
* Query Parameters:
|
||||
* - limit: number (default: 50, max: 250)
|
||||
* - offset: number (default: 0)
|
||||
*
|
||||
* Response: AdminListResponse<AdminMemberDetail>
|
||||
*
|
||||
* POST /api/v1/admin/organizations/[id]/members
|
||||
*
|
||||
* Add a user to an organization with full billing logic.
|
||||
* Validates seat availability before adding (uses same logic as invitation flow):
|
||||
* - Team plans: checks seats column
|
||||
* - Enterprise plans: checks metadata.seats
|
||||
* Handles Pro usage snapshot and subscription cancellation like the invitation flow.
|
||||
* If user is already a member, updates their role if different.
|
||||
*
|
||||
* Body:
|
||||
* - userId: string - User ID to add
|
||||
* - role: string - Role ('admin' | 'member')
|
||||
*
|
||||
* Response: AdminSingleResponse<AdminMember & {
|
||||
* action: 'created' | 'updated' | 'already_member',
|
||||
* billingActions: { proUsageSnapshotted, proCancelledAtPeriodEnd }
|
||||
* }>
|
||||
*/
|
||||
|
||||
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
|
||||
import { db } from '@sim/db'
|
||||
import { member, organization, user, userStats } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { count, eq } from 'drizzle-orm'
|
||||
import {
|
||||
adminV1AddOrganizationMemberContract,
|
||||
adminV1ListOrganizationMembersContract,
|
||||
} from '@/lib/api/contracts/v1/admin'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { getOrgMemberLedgerByUser } from '@/lib/billing/core/organization'
|
||||
import { addUserToOrganization } from '@/lib/billing/organizations/membership'
|
||||
import { isBillingEnabled } from '@/lib/core/config/env-flags'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { withAdminAuthParams } from '@/app/api/v1/admin/middleware'
|
||||
import {
|
||||
adminInvalidJsonResponse,
|
||||
adminValidationErrorResponse,
|
||||
badRequestResponse,
|
||||
internalErrorResponse,
|
||||
listResponse,
|
||||
notFoundResponse,
|
||||
singleResponse,
|
||||
} from '@/app/api/v1/admin/responses'
|
||||
import {
|
||||
type AdminMember,
|
||||
type AdminMemberDetail,
|
||||
createPaginationMeta,
|
||||
} from '@/app/api/v1/admin/types'
|
||||
|
||||
const logger = createLogger('AdminOrganizationMembersAPI')
|
||||
|
||||
interface RouteParams {
|
||||
id: string
|
||||
}
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1ListOrganizationMembersContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: organizationId } = parsed.data.params
|
||||
const { limit, offset } = parsed.data.query
|
||||
|
||||
try {
|
||||
const [orgData] = await db
|
||||
.select({ id: organization.id })
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1)
|
||||
|
||||
if (!orgData) {
|
||||
return notFoundResponse('Organization')
|
||||
}
|
||||
|
||||
const [countResult, membersData] = await Promise.all([
|
||||
db.select({ count: count() }).from(member).where(eq(member.organizationId, organizationId)),
|
||||
db
|
||||
.select({
|
||||
id: member.id,
|
||||
userId: member.userId,
|
||||
organizationId: member.organizationId,
|
||||
role: member.role,
|
||||
createdAt: member.createdAt,
|
||||
userName: user.name,
|
||||
userEmail: user.email,
|
||||
currentPeriodCost: userStats.currentPeriodCost,
|
||||
currentUsageLimit: userStats.currentUsageLimit,
|
||||
billingBlocked: userStats.billingBlocked,
|
||||
})
|
||||
.from(member)
|
||||
.innerJoin(user, eq(member.userId, user.id))
|
||||
.leftJoin(userStats, eq(member.userId, userStats.userId))
|
||||
.where(eq(member.organizationId, organizationId))
|
||||
.orderBy(member.createdAt)
|
||||
.limit(limit)
|
||||
.offset(offset),
|
||||
])
|
||||
|
||||
const total = countResult[0].count
|
||||
|
||||
// currentPeriodCost is only a baseline; add each member's attributed
|
||||
// usage_log for the org's period so admin shows real current usage.
|
||||
const usageByUser = await getOrgMemberLedgerByUser(organizationId)
|
||||
|
||||
const data: AdminMemberDetail[] = membersData.map((m) => ({
|
||||
id: m.id,
|
||||
userId: m.userId,
|
||||
organizationId: m.organizationId,
|
||||
role: m.role,
|
||||
createdAt: m.createdAt.toISOString(),
|
||||
userName: m.userName,
|
||||
userEmail: m.userEmail,
|
||||
currentPeriodCost: (
|
||||
Number(m.currentPeriodCost ?? 0) + (usageByUser.get(m.userId) ?? 0)
|
||||
).toString(),
|
||||
currentUsageLimit: m.currentUsageLimit,
|
||||
billingBlocked: m.billingBlocked ?? false,
|
||||
}))
|
||||
|
||||
const pagination = createPaginationMeta(total, limit, offset)
|
||||
|
||||
logger.info(`Admin API: Listed ${data.length} members for organization ${organizationId}`)
|
||||
|
||||
return listResponse(data, pagination)
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to list organization members', { error, organizationId })
|
||||
return internalErrorResponse('Failed to list organization members')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
export const POST = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1AddOrganizationMemberContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
invalidJsonResponse: adminInvalidJsonResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: organizationId } = parsed.data.params
|
||||
|
||||
try {
|
||||
const { userId, role } = parsed.data.body
|
||||
|
||||
const [orgData] = await db
|
||||
.select({ id: organization.id, name: organization.name })
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1)
|
||||
|
||||
if (!orgData) {
|
||||
return notFoundResponse('Organization')
|
||||
}
|
||||
|
||||
const [userData] = await db
|
||||
.select({ id: user.id, name: user.name, email: user.email })
|
||||
.from(user)
|
||||
.where(eq(user.id, userId))
|
||||
.limit(1)
|
||||
|
||||
if (!userData) {
|
||||
return notFoundResponse('User')
|
||||
}
|
||||
|
||||
const [existingMember] = await db
|
||||
.select({
|
||||
id: member.id,
|
||||
role: member.role,
|
||||
createdAt: member.createdAt,
|
||||
organizationId: member.organizationId,
|
||||
})
|
||||
.from(member)
|
||||
.where(eq(member.userId, userId))
|
||||
.limit(1)
|
||||
|
||||
if (existingMember) {
|
||||
if (existingMember.organizationId === organizationId) {
|
||||
if (existingMember.role === 'owner') {
|
||||
return badRequestResponse(
|
||||
'Cannot change the owner role via this endpoint. Use POST /api/v1/admin/organizations/[id]/transfer-ownership instead.'
|
||||
)
|
||||
}
|
||||
|
||||
if (existingMember.role !== role) {
|
||||
await db.update(member).set({ role }).where(eq(member.id, existingMember.id))
|
||||
|
||||
logger.info(
|
||||
`Admin API: Updated user ${userId} role in organization ${organizationId}`,
|
||||
{
|
||||
previousRole: existingMember.role,
|
||||
newRole: role,
|
||||
}
|
||||
)
|
||||
|
||||
recordAudit({
|
||||
workspaceId: null,
|
||||
actorId: 'admin-api',
|
||||
action: AuditAction.ORG_MEMBER_ROLE_CHANGED,
|
||||
resourceType: AuditResourceType.ORGANIZATION,
|
||||
resourceId: organizationId,
|
||||
description: `Admin API changed organization member role to ${role}`,
|
||||
metadata: { targetUserId: userId, previousRole: existingMember.role, role },
|
||||
request,
|
||||
})
|
||||
|
||||
return singleResponse({
|
||||
id: existingMember.id,
|
||||
userId,
|
||||
organizationId,
|
||||
role,
|
||||
createdAt: existingMember.createdAt.toISOString(),
|
||||
userName: userData.name,
|
||||
userEmail: userData.email,
|
||||
action: 'updated' as const,
|
||||
billingActions: {
|
||||
proUsageSnapshotted: false,
|
||||
proCancelledAtPeriodEnd: false,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return singleResponse({
|
||||
id: existingMember.id,
|
||||
userId,
|
||||
organizationId,
|
||||
role: existingMember.role,
|
||||
createdAt: existingMember.createdAt.toISOString(),
|
||||
userName: userData.name,
|
||||
userEmail: userData.email,
|
||||
action: 'already_member' as const,
|
||||
billingActions: {
|
||||
proUsageSnapshotted: false,
|
||||
proCancelledAtPeriodEnd: false,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return badRequestResponse(
|
||||
`User is already a member of another organization. Users can only belong to one organization at a time.`
|
||||
)
|
||||
}
|
||||
|
||||
const result = await addUserToOrganization({
|
||||
userId,
|
||||
organizationId,
|
||||
role,
|
||||
skipBillingLogic: !isBillingEnabled,
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
return badRequestResponse(result.error || 'Failed to add member')
|
||||
}
|
||||
|
||||
const data: AdminMember = {
|
||||
id: result.memberId!,
|
||||
userId,
|
||||
organizationId,
|
||||
role,
|
||||
createdAt: new Date().toISOString(),
|
||||
userName: userData.name,
|
||||
userEmail: userData.email,
|
||||
}
|
||||
|
||||
logger.info(`Admin API: Added user ${userId} to organization ${organizationId}`, {
|
||||
role,
|
||||
memberId: result.memberId,
|
||||
billingActions: result.billingActions,
|
||||
})
|
||||
|
||||
recordAudit({
|
||||
workspaceId: null,
|
||||
actorId: 'admin-api',
|
||||
action: AuditAction.ORG_MEMBER_ADDED,
|
||||
resourceType: AuditResourceType.ORGANIZATION,
|
||||
resourceId: organizationId,
|
||||
description: `Admin API added member to organization as ${role}`,
|
||||
metadata: { targetUserId: userId, role, memberId: result.memberId },
|
||||
request,
|
||||
})
|
||||
|
||||
return singleResponse({
|
||||
...data,
|
||||
action: 'created' as const,
|
||||
billingActions: {
|
||||
proUsageSnapshotted: result.billingActions.proUsageSnapshotted,
|
||||
proCancelledAtPeriodEnd: result.billingActions.proCancelledAtPeriodEnd,
|
||||
},
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to add organization member', { error, organizationId })
|
||||
return internalErrorResponse('Failed to add organization member')
|
||||
}
|
||||
})
|
||||
)
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* GET /api/v1/admin/organizations/[id]
|
||||
*
|
||||
* Get organization details including member count and subscription.
|
||||
*
|
||||
* Response: AdminSingleResponse<AdminOrganizationDetail>
|
||||
*
|
||||
* PATCH /api/v1/admin/organizations/[id]
|
||||
*
|
||||
* Update organization details.
|
||||
*
|
||||
* Body:
|
||||
* - name?: string - Organization name
|
||||
* - slug?: string - Organization slug
|
||||
*
|
||||
* Response: AdminSingleResponse<AdminOrganization>
|
||||
*/
|
||||
|
||||
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
|
||||
import { db } from '@sim/db'
|
||||
import { member, organization, subscription } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { and, count, eq, inArray } from 'drizzle-orm'
|
||||
import {
|
||||
adminV1GetOrganizationContract,
|
||||
adminV1UpdateOrganizationContract,
|
||||
} from '@/lib/api/contracts/v1/admin'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import {
|
||||
ensureOrganizationSlugAvailable,
|
||||
OrganizationSlugInvalidError,
|
||||
OrganizationSlugTakenError,
|
||||
validateOrganizationSlugOrThrow,
|
||||
} from '@/lib/billing/organizations/create-organization'
|
||||
import { ENTITLED_SUBSCRIPTION_STATUSES } from '@/lib/billing/subscriptions/utils'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { withAdminAuthParams } from '@/app/api/v1/admin/middleware'
|
||||
import {
|
||||
adminInvalidJsonResponse,
|
||||
adminValidationErrorResponse,
|
||||
badRequestResponse,
|
||||
internalErrorResponse,
|
||||
notFoundResponse,
|
||||
singleResponse,
|
||||
} from '@/app/api/v1/admin/responses'
|
||||
import {
|
||||
type AdminOrganizationDetail,
|
||||
toAdminOrganization,
|
||||
toAdminSubscription,
|
||||
} from '@/app/api/v1/admin/types'
|
||||
|
||||
const logger = createLogger('AdminOrganizationDetailAPI')
|
||||
|
||||
interface RouteParams {
|
||||
id: string
|
||||
}
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1GetOrganizationContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: organizationId } = parsed.data.params
|
||||
|
||||
try {
|
||||
const [orgData] = await db
|
||||
.select()
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1)
|
||||
|
||||
if (!orgData) {
|
||||
return notFoundResponse('Organization')
|
||||
}
|
||||
|
||||
const [memberCountResult, subscriptionData] = await Promise.all([
|
||||
db.select({ count: count() }).from(member).where(eq(member.organizationId, organizationId)),
|
||||
db
|
||||
.select()
|
||||
.from(subscription)
|
||||
.where(
|
||||
and(
|
||||
eq(subscription.referenceId, organizationId),
|
||||
inArray(subscription.status, ENTITLED_SUBSCRIPTION_STATUSES)
|
||||
)
|
||||
)
|
||||
.limit(1),
|
||||
])
|
||||
|
||||
const data: AdminOrganizationDetail = {
|
||||
...toAdminOrganization(orgData),
|
||||
memberCount: memberCountResult[0].count,
|
||||
subscription: subscriptionData[0] ? toAdminSubscription(subscriptionData[0]) : null,
|
||||
}
|
||||
|
||||
logger.info(`Admin API: Retrieved organization ${organizationId}`)
|
||||
|
||||
return singleResponse(data)
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to get organization', { error, organizationId })
|
||||
return internalErrorResponse('Failed to get organization')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
export const PATCH = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1UpdateOrganizationContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
invalidJsonResponse: adminInvalidJsonResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: organizationId } = parsed.data.params
|
||||
|
||||
try {
|
||||
const [existing] = await db
|
||||
.select()
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1)
|
||||
|
||||
if (!existing) {
|
||||
return notFoundResponse('Organization')
|
||||
}
|
||||
|
||||
const updateData: Record<string, unknown> = {
|
||||
updatedAt: new Date(),
|
||||
}
|
||||
|
||||
const validatedBody = parsed.data.body
|
||||
|
||||
if (validatedBody.name !== undefined) {
|
||||
updateData.name = validatedBody.name
|
||||
}
|
||||
|
||||
if (validatedBody.slug !== undefined) {
|
||||
const nextSlug = validatedBody.slug
|
||||
validateOrganizationSlugOrThrow(nextSlug)
|
||||
await ensureOrganizationSlugAvailable({
|
||||
slug: nextSlug,
|
||||
excludeOrganizationId: organizationId,
|
||||
})
|
||||
updateData.slug = nextSlug
|
||||
}
|
||||
|
||||
if (Object.keys(updateData).length === 1) {
|
||||
return badRequestResponse(
|
||||
'No valid fields to update. Use /billing endpoint for orgUsageLimit.'
|
||||
)
|
||||
}
|
||||
|
||||
const [updated] = await db
|
||||
.update(organization)
|
||||
.set(updateData)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.returning()
|
||||
|
||||
logger.info(`Admin API: Updated organization ${organizationId}`, {
|
||||
fields: Object.keys(updateData).filter((k) => k !== 'updatedAt'),
|
||||
})
|
||||
|
||||
recordAudit({
|
||||
workspaceId: null,
|
||||
actorId: 'admin-api',
|
||||
action: AuditAction.ORGANIZATION_UPDATED,
|
||||
resourceType: AuditResourceType.ORGANIZATION,
|
||||
resourceId: organizationId,
|
||||
resourceName: updated.name,
|
||||
description: `Admin API updated organization "${updated.name}"`,
|
||||
metadata: { fields: Object.keys(updateData).filter((k) => k !== 'updatedAt') },
|
||||
request,
|
||||
})
|
||||
|
||||
return singleResponse(toAdminOrganization(updated))
|
||||
} catch (error) {
|
||||
if (error instanceof OrganizationSlugInvalidError) {
|
||||
return badRequestResponse(
|
||||
'Organization slug can only contain lowercase letters, numbers, hyphens, and underscores.'
|
||||
)
|
||||
}
|
||||
|
||||
if (error instanceof OrganizationSlugTakenError) {
|
||||
return badRequestResponse('This slug is already taken')
|
||||
}
|
||||
|
||||
logger.error('Admin API: Failed to update organization', { error, organizationId })
|
||||
return internalErrorResponse('Failed to update organization')
|
||||
}
|
||||
})
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
/**
|
||||
* GET /api/v1/admin/organizations/[id]/seats
|
||||
*
|
||||
* Get organization seat analytics including member activity.
|
||||
*
|
||||
* Response: AdminSingleResponse<AdminSeatAnalytics>
|
||||
*/
|
||||
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { adminV1GetOrganizationSeatsContract } from '@/lib/api/contracts/v1/admin'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { getOrganizationSeatAnalytics } from '@/lib/billing/validation/seat-management'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { withAdminAuthParams } from '@/app/api/v1/admin/middleware'
|
||||
import {
|
||||
adminValidationErrorResponse,
|
||||
internalErrorResponse,
|
||||
notFoundResponse,
|
||||
singleResponse,
|
||||
} from '@/app/api/v1/admin/responses'
|
||||
import type { AdminSeatAnalytics } from '@/app/api/v1/admin/types'
|
||||
|
||||
const logger = createLogger('AdminOrganizationSeatsAPI')
|
||||
|
||||
interface RouteParams {
|
||||
id: string
|
||||
}
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1GetOrganizationSeatsContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: organizationId } = parsed.data.params
|
||||
|
||||
try {
|
||||
const analytics = await getOrganizationSeatAnalytics(organizationId)
|
||||
|
||||
if (!analytics) {
|
||||
return notFoundResponse('Organization or subscription')
|
||||
}
|
||||
|
||||
const data: AdminSeatAnalytics = {
|
||||
organizationId: analytics.organizationId,
|
||||
organizationName: analytics.organizationName,
|
||||
currentSeats: analytics.currentSeats,
|
||||
maxSeats: analytics.maxSeats,
|
||||
availableSeats: analytics.availableSeats,
|
||||
subscriptionPlan: analytics.subscriptionPlan,
|
||||
canAddSeats: analytics.canAddSeats,
|
||||
utilizationRate: analytics.utilizationRate,
|
||||
}
|
||||
|
||||
logger.info(`Admin API: Retrieved seat analytics for organization ${organizationId}`)
|
||||
|
||||
return singleResponse(data)
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to get organization seats', { error, organizationId })
|
||||
return internalErrorResponse('Failed to get organization seats')
|
||||
}
|
||||
})
|
||||
)
|
||||
@@ -0,0 +1,145 @@
|
||||
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
|
||||
import { db } from '@sim/db'
|
||||
import { member, organization, user } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { and, eq } from 'drizzle-orm'
|
||||
import { adminV1TransferOwnershipContract } from '@/lib/api/contracts/v1/admin'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { transferOrganizationOwnership } from '@/lib/billing/organizations/membership'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { withAdminAuthParams } from '@/app/api/v1/admin/middleware'
|
||||
import {
|
||||
adminValidationErrorResponse,
|
||||
badRequestResponse,
|
||||
internalErrorResponse,
|
||||
notFoundResponse,
|
||||
singleResponse,
|
||||
} from '@/app/api/v1/admin/responses'
|
||||
|
||||
const logger = createLogger('AdminTransferOwnershipAPI')
|
||||
|
||||
interface RouteParams {
|
||||
id: string
|
||||
}
|
||||
|
||||
export const POST = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const routeParams = await context.params
|
||||
const { id: organizationId } = routeParams
|
||||
|
||||
try {
|
||||
const parsed = await parseRequest(
|
||||
adminV1TransferOwnershipContract,
|
||||
request,
|
||||
{ params: routeParams },
|
||||
{
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
invalidJsonResponse: () => badRequestResponse('Invalid request body'),
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { newOwnerUserId, currentOwnerUserId: currentOwnerUserIdOverride } = parsed.data.body
|
||||
|
||||
const [orgRow] = await db
|
||||
.select({ id: organization.id })
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1)
|
||||
|
||||
if (!orgRow) {
|
||||
return notFoundResponse('Organization')
|
||||
}
|
||||
|
||||
let currentOwnerUserId: string
|
||||
if (currentOwnerUserIdOverride) {
|
||||
currentOwnerUserId = currentOwnerUserIdOverride
|
||||
} else {
|
||||
const [ownerMembership] = await db
|
||||
.select({ userId: member.userId })
|
||||
.from(member)
|
||||
.where(and(eq(member.organizationId, organizationId), eq(member.role, 'owner')))
|
||||
.limit(1)
|
||||
|
||||
if (!ownerMembership) {
|
||||
return badRequestResponse(
|
||||
'Organization has no owner; provide currentOwnerUserId explicitly to seed ownership'
|
||||
)
|
||||
}
|
||||
|
||||
currentOwnerUserId = ownerMembership.userId
|
||||
}
|
||||
|
||||
if (currentOwnerUserId === newOwnerUserId) {
|
||||
return badRequestResponse('New owner must differ from current owner')
|
||||
}
|
||||
|
||||
const [newOwnerMember] = await db
|
||||
.select({
|
||||
id: member.id,
|
||||
role: member.role,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
})
|
||||
.from(member)
|
||||
.innerJoin(user, eq(member.userId, user.id))
|
||||
.where(and(eq(member.organizationId, organizationId), eq(member.userId, newOwnerUserId)))
|
||||
.limit(1)
|
||||
|
||||
if (!newOwnerMember) {
|
||||
return badRequestResponse('Target user is not a member of this organization')
|
||||
}
|
||||
|
||||
const result = await transferOrganizationOwnership({
|
||||
organizationId,
|
||||
currentOwnerUserId,
|
||||
newOwnerUserId,
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
return internalErrorResponse(result.error ?? 'Failed to transfer ownership')
|
||||
}
|
||||
|
||||
logger.info(`Admin API: Transferred ownership of organization ${organizationId}`, {
|
||||
currentOwnerUserId,
|
||||
newOwnerUserId,
|
||||
workspacesReassigned: result.workspacesReassigned,
|
||||
billedAccountReassigned: result.billedAccountReassigned,
|
||||
overageMigrated: result.overageMigrated,
|
||||
billingBlockInherited: result.billingBlockInherited,
|
||||
})
|
||||
|
||||
recordAudit({
|
||||
workspaceId: null,
|
||||
actorId: 'admin-api',
|
||||
action: AuditAction.ORG_MEMBER_ROLE_CHANGED,
|
||||
resourceType: AuditResourceType.ORGANIZATION,
|
||||
resourceId: organizationId,
|
||||
description: 'Admin API transferred organization ownership',
|
||||
metadata: {
|
||||
currentOwnerUserId,
|
||||
newOwnerUserId,
|
||||
workspacesReassigned: result.workspacesReassigned,
|
||||
billedAccountReassigned: result.billedAccountReassigned,
|
||||
},
|
||||
request,
|
||||
})
|
||||
|
||||
return singleResponse({
|
||||
organizationId,
|
||||
currentOwnerUserId,
|
||||
newOwnerUserId,
|
||||
workspacesReassigned: result.workspacesReassigned,
|
||||
billedAccountReassigned: result.billedAccountReassigned,
|
||||
overageMigrated: result.overageMigrated,
|
||||
billingBlockInherited: result.billingBlockInherited,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to transfer organization ownership', {
|
||||
organizationId,
|
||||
error,
|
||||
})
|
||||
return internalErrorResponse('Failed to transfer ownership')
|
||||
}
|
||||
})
|
||||
)
|
||||
@@ -0,0 +1,202 @@
|
||||
/**
|
||||
* GET /api/v1/admin/organizations
|
||||
*
|
||||
* List all organizations with pagination.
|
||||
*
|
||||
* Query Parameters:
|
||||
* - limit: number (default: 50, max: 250)
|
||||
* - offset: number (default: 0)
|
||||
*
|
||||
* Response: AdminListResponse<AdminOrganization>
|
||||
*
|
||||
* POST /api/v1/admin/organizations
|
||||
*
|
||||
* Create a new organization.
|
||||
*
|
||||
* Body:
|
||||
* - name: string - Organization name (required)
|
||||
* - slug: string - Organization slug (optional, auto-generated from name if not provided)
|
||||
* - ownerId: string - User ID of the organization owner (required)
|
||||
*
|
||||
* Response: AdminSingleResponse<AdminOrganization & { memberId: string }>
|
||||
*/
|
||||
|
||||
import { AuditAction, AuditResourceType, recordAudit } from '@sim/audit'
|
||||
import { db, dbReplica } from '@sim/db'
|
||||
import { member, organization, user } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { count, eq } from 'drizzle-orm'
|
||||
import {
|
||||
adminV1CreateOrganizationContract,
|
||||
adminV1ListOrganizationsContract,
|
||||
} from '@/lib/api/contracts/v1/admin'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import {
|
||||
createOrganizationWithOwner,
|
||||
OrganizationSlugInvalidError,
|
||||
OrganizationSlugTakenError,
|
||||
} from '@/lib/billing/organizations/create-organization'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { withAdminAuth } from '@/app/api/v1/admin/middleware'
|
||||
import {
|
||||
adminInvalidJsonResponse,
|
||||
adminValidationErrorResponse,
|
||||
badRequestResponse,
|
||||
internalErrorResponse,
|
||||
listResponse,
|
||||
notFoundResponse,
|
||||
singleResponse,
|
||||
} from '@/app/api/v1/admin/responses'
|
||||
import {
|
||||
type AdminOrganization,
|
||||
createPaginationMeta,
|
||||
toAdminOrganization,
|
||||
} from '@/app/api/v1/admin/types'
|
||||
|
||||
const logger = createLogger('AdminOrganizationsAPI')
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
withAdminAuth(async (request) => {
|
||||
const parsed = await parseRequest(
|
||||
adminV1ListOrganizationsContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { limit, offset } = parsed.data.query
|
||||
|
||||
try {
|
||||
const [countResult, organizations] = await Promise.all([
|
||||
dbReplica.select({ total: count() }).from(organization),
|
||||
dbReplica
|
||||
.select({
|
||||
id: organization.id,
|
||||
name: organization.name,
|
||||
slug: organization.slug,
|
||||
logo: organization.logo,
|
||||
orgUsageLimit: organization.orgUsageLimit,
|
||||
storageUsedBytes: organization.storageUsedBytes,
|
||||
departedMemberUsage: organization.departedMemberUsage,
|
||||
createdAt: organization.createdAt,
|
||||
updatedAt: organization.updatedAt,
|
||||
})
|
||||
.from(organization)
|
||||
.orderBy(organization.name)
|
||||
.limit(limit)
|
||||
.offset(offset),
|
||||
])
|
||||
|
||||
const total = countResult[0].total
|
||||
const data: AdminOrganization[] = organizations.map(toAdminOrganization)
|
||||
const pagination = createPaginationMeta(total, limit, offset)
|
||||
|
||||
logger.info(`Admin API: Listed ${data.length} organizations (total: ${total})`)
|
||||
|
||||
return listResponse(data, pagination)
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to list organizations', { error })
|
||||
return internalErrorResponse('Failed to list organizations')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
export const POST = withRouteHandler(
|
||||
withAdminAuth(async (request) => {
|
||||
const parsed = await parseRequest(
|
||||
adminV1CreateOrganizationContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
invalidJsonResponse: adminInvalidJsonResponse,
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
try {
|
||||
const { name, ownerId, slug: requestedSlug } = parsed.data.body
|
||||
|
||||
const [ownerData] = await db
|
||||
.select({ id: user.id, name: user.name })
|
||||
.from(user)
|
||||
.where(eq(user.id, ownerId))
|
||||
.limit(1)
|
||||
|
||||
if (!ownerData) {
|
||||
return notFoundResponse('Owner user')
|
||||
}
|
||||
|
||||
const [existingMembership] = await db
|
||||
.select({ organizationId: member.organizationId })
|
||||
.from(member)
|
||||
.where(eq(member.userId, ownerId))
|
||||
.limit(1)
|
||||
|
||||
if (existingMembership) {
|
||||
return badRequestResponse(
|
||||
'User is already a member of another organization. Users can only belong to one organization at a time.'
|
||||
)
|
||||
}
|
||||
|
||||
const slug =
|
||||
requestedSlug?.trim() ||
|
||||
name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-|-$/g, '')
|
||||
|
||||
const { organizationId, memberId } = await createOrganizationWithOwner({
|
||||
ownerUserId: ownerId,
|
||||
name,
|
||||
slug,
|
||||
})
|
||||
|
||||
const [createdOrg] = await db
|
||||
.select()
|
||||
.from(organization)
|
||||
.where(eq(organization.id, organizationId))
|
||||
.limit(1)
|
||||
|
||||
logger.info(`Admin API: Created organization ${organizationId}`, {
|
||||
name,
|
||||
slug,
|
||||
ownerId,
|
||||
memberId,
|
||||
})
|
||||
|
||||
recordAudit({
|
||||
workspaceId: null,
|
||||
actorId: 'admin-api',
|
||||
action: AuditAction.ORGANIZATION_CREATED,
|
||||
resourceType: AuditResourceType.ORGANIZATION,
|
||||
resourceId: organizationId,
|
||||
resourceName: name,
|
||||
description: `Admin API created organization "${name}"`,
|
||||
metadata: { slug, ownerId, memberId },
|
||||
request,
|
||||
})
|
||||
|
||||
return singleResponse({
|
||||
...toAdminOrganization(createdOrg),
|
||||
memberId,
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof OrganizationSlugInvalidError) {
|
||||
return badRequestResponse(
|
||||
'Organization slug can only contain lowercase letters, numbers, hyphens, and underscores.'
|
||||
)
|
||||
}
|
||||
|
||||
if (error instanceof OrganizationSlugTakenError) {
|
||||
return badRequestResponse('This slug is already taken')
|
||||
}
|
||||
|
||||
logger.error('Admin API: Failed to create organization', { error })
|
||||
return internalErrorResponse('Failed to create organization')
|
||||
}
|
||||
})
|
||||
)
|
||||
Reference in New Issue
Block a user