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,277 @@
|
||||
/**
|
||||
* GET /api/v1/admin/users/[id]/billing
|
||||
*
|
||||
* Get user billing information including usage stats, subscriptions, and org memberships.
|
||||
*
|
||||
* Response: AdminSingleResponse<AdminUserBillingWithSubscription>
|
||||
*
|
||||
* PATCH /api/v1/admin/users/[id]/billing
|
||||
*
|
||||
* Update user billing settings with proper validation.
|
||||
*
|
||||
* Body:
|
||||
* - currentUsageLimit?: number | null - Usage limit (null to use default)
|
||||
* - billingBlocked?: boolean - Block/unblock billing
|
||||
* - currentPeriodCost?: number - Reset/adjust current period cost (use with caution)
|
||||
* - reason?: string - Reason for the change (for audit logging)
|
||||
*
|
||||
* Response: AdminSingleResponse<{ success: true, updated: string[], warnings: string[] }>
|
||||
*/
|
||||
|
||||
import { db } from '@sim/db'
|
||||
import { member, organization, subscription, user, userStats } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { generateShortId } from '@sim/utils/id'
|
||||
import { eq, or } from 'drizzle-orm'
|
||||
import {
|
||||
adminV1GetUserBillingContract,
|
||||
adminV1UpdateUserBillingContract,
|
||||
} from '@/lib/api/contracts/v1/admin'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { getHighestPrioritySubscription } from '@/lib/billing/core/subscription'
|
||||
import { getUserUsageData } from '@/lib/billing/core/usage'
|
||||
import { isOrgScopedSubscription } 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 AdminUserBillingWithSubscription,
|
||||
toAdminSubscription,
|
||||
} from '@/app/api/v1/admin/types'
|
||||
|
||||
const logger = createLogger('AdminUserBillingAPI')
|
||||
|
||||
interface RouteParams {
|
||||
id: string
|
||||
}
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1GetUserBillingContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: userId } = parsed.data.params
|
||||
|
||||
try {
|
||||
const [userData] = await db
|
||||
.select({
|
||||
id: user.id,
|
||||
name: user.name,
|
||||
email: user.email,
|
||||
stripeCustomerId: user.stripeCustomerId,
|
||||
})
|
||||
.from(user)
|
||||
.where(eq(user.id, userId))
|
||||
.limit(1)
|
||||
|
||||
if (!userData) {
|
||||
return notFoundResponse('User')
|
||||
}
|
||||
|
||||
const [stats] = await db.select().from(userStats).where(eq(userStats.userId, userId)).limit(1)
|
||||
|
||||
// currentPeriodCost is now only a baseline; canonical current-period usage
|
||||
// (baseline + attributed usage_log, refresh-adjusted) comes from the same
|
||||
// helper users see, so admin reflects real usage instead of a stale 0.
|
||||
const usage = await getUserUsageData(userId)
|
||||
|
||||
const memberOrgs = await db
|
||||
.select({
|
||||
organizationId: member.organizationId,
|
||||
organizationName: organization.name,
|
||||
role: member.role,
|
||||
})
|
||||
.from(member)
|
||||
.innerJoin(organization, eq(member.organizationId, organization.id))
|
||||
.where(eq(member.userId, userId))
|
||||
|
||||
const orgIds = memberOrgs.map((m) => m.organizationId)
|
||||
|
||||
const subscriptions = await db
|
||||
.select()
|
||||
.from(subscription)
|
||||
.where(
|
||||
orgIds.length > 0
|
||||
? or(
|
||||
eq(subscription.referenceId, userId),
|
||||
...orgIds.map((orgId) => eq(subscription.referenceId, orgId))
|
||||
)
|
||||
: eq(subscription.referenceId, userId)
|
||||
)
|
||||
|
||||
const data: AdminUserBillingWithSubscription = {
|
||||
userId: userData.id,
|
||||
userName: userData.name,
|
||||
userEmail: userData.email,
|
||||
stripeCustomerId: userData.stripeCustomerId,
|
||||
currentUsageLimit: stats?.currentUsageLimit ?? null,
|
||||
currentPeriodCost: usage.currentUsage.toString(),
|
||||
lastPeriodCost: stats?.lastPeriodCost ?? null,
|
||||
billedOverageThisPeriod: stats?.billedOverageThisPeriod ?? '0',
|
||||
storageUsedBytes: stats?.storageUsedBytes ?? 0,
|
||||
billingBlocked: stats?.billingBlocked ?? false,
|
||||
currentPeriodCopilotCost: stats?.currentPeriodCopilotCost ?? '0',
|
||||
lastPeriodCopilotCost: stats?.lastPeriodCopilotCost ?? null,
|
||||
subscriptions: subscriptions.map(toAdminSubscription),
|
||||
organizationMemberships: memberOrgs.map((m) => ({
|
||||
organizationId: m.organizationId,
|
||||
organizationName: m.organizationName,
|
||||
role: m.role,
|
||||
})),
|
||||
}
|
||||
|
||||
logger.info(`Admin API: Retrieved billing for user ${userId}`)
|
||||
|
||||
return singleResponse(data)
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to get user billing', { error, userId })
|
||||
return internalErrorResponse('Failed to get user billing')
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
export const PATCH = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1UpdateUserBillingContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
invalidJsonResponse: adminInvalidJsonResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: userId } = parsed.data.params
|
||||
|
||||
try {
|
||||
const {
|
||||
currentUsageLimit,
|
||||
billingBlocked,
|
||||
currentPeriodCost,
|
||||
reason: providedReason,
|
||||
} = parsed.data.body
|
||||
const reason = providedReason || 'Admin update (no reason provided)'
|
||||
|
||||
const [userData] = await db
|
||||
.select({ id: user.id })
|
||||
.from(user)
|
||||
.where(eq(user.id, userId))
|
||||
.limit(1)
|
||||
|
||||
if (!userData) {
|
||||
return notFoundResponse('User')
|
||||
}
|
||||
|
||||
const [existingStats] = await db
|
||||
.select()
|
||||
.from(userStats)
|
||||
.where(eq(userStats.userId, userId))
|
||||
.limit(1)
|
||||
|
||||
const userSubscription = await getHighestPrioritySubscription(userId)
|
||||
const isOrgScopedMember = isOrgScopedSubscription(userSubscription, userId)
|
||||
|
||||
const [orgMembership] = await db
|
||||
.select({ organizationId: member.organizationId })
|
||||
.from(member)
|
||||
.where(eq(member.userId, userId))
|
||||
.limit(1)
|
||||
|
||||
const updateData: Record<string, unknown> = {}
|
||||
const updated: string[] = []
|
||||
const warnings: string[] = []
|
||||
|
||||
if (currentUsageLimit !== undefined) {
|
||||
if (isOrgScopedMember && orgMembership) {
|
||||
warnings.push(
|
||||
'User is on an org-scoped subscription. Individual limits are ignored in favor of organization limits.'
|
||||
)
|
||||
}
|
||||
|
||||
if (currentUsageLimit === null) {
|
||||
updateData.currentUsageLimit = null
|
||||
} else {
|
||||
const currentCost = Number.parseFloat(existingStats?.currentPeriodCost || '0')
|
||||
if (currentUsageLimit < currentCost) {
|
||||
warnings.push(
|
||||
`New limit ($${currentUsageLimit.toFixed(2)}) is below current usage ($${currentCost.toFixed(2)}). User may be immediately blocked.`
|
||||
)
|
||||
}
|
||||
updateData.currentUsageLimit = currentUsageLimit.toFixed(2)
|
||||
}
|
||||
updateData.usageLimitUpdatedAt = new Date()
|
||||
updated.push('currentUsageLimit')
|
||||
}
|
||||
|
||||
if (billingBlocked !== undefined) {
|
||||
if (billingBlocked === false && existingStats?.billingBlocked === true) {
|
||||
warnings.push(
|
||||
'Unblocking user. Ensure payment issues are resolved to prevent re-blocking on next invoice.'
|
||||
)
|
||||
}
|
||||
|
||||
updateData.billingBlocked = billingBlocked
|
||||
// Clear the reason when unblocking
|
||||
if (billingBlocked === false) {
|
||||
updateData.billingBlockedReason = null
|
||||
}
|
||||
updated.push('billingBlocked')
|
||||
}
|
||||
|
||||
if (currentPeriodCost !== undefined) {
|
||||
const previousCost = existingStats?.currentPeriodCost || '0'
|
||||
warnings.push(
|
||||
`Manually adjusting currentPeriodCost from $${previousCost} to $${currentPeriodCost.toFixed(2)}. This may affect billing accuracy.`
|
||||
)
|
||||
|
||||
updateData.currentPeriodCost = currentPeriodCost.toFixed(2)
|
||||
updated.push('currentPeriodCost')
|
||||
}
|
||||
|
||||
if (updated.length === 0) {
|
||||
return badRequestResponse('No valid fields to update')
|
||||
}
|
||||
|
||||
if (existingStats) {
|
||||
await db.update(userStats).set(updateData).where(eq(userStats.userId, userId))
|
||||
} else {
|
||||
await db.insert(userStats).values({
|
||||
id: generateShortId(),
|
||||
userId,
|
||||
...updateData,
|
||||
})
|
||||
}
|
||||
|
||||
logger.info(`Admin API: Updated billing for user ${userId}`, {
|
||||
updated,
|
||||
warnings,
|
||||
reason,
|
||||
previousValues: existingStats
|
||||
? {
|
||||
currentUsageLimit: existingStats.currentUsageLimit,
|
||||
billingBlocked: existingStats.billingBlocked,
|
||||
currentPeriodCost: existingStats.currentPeriodCost,
|
||||
}
|
||||
: null,
|
||||
newValues: updateData,
|
||||
isTeamMember: !!orgMembership,
|
||||
})
|
||||
|
||||
return singleResponse({
|
||||
success: true,
|
||||
updated,
|
||||
warnings,
|
||||
reason,
|
||||
})
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to update user billing', { error, userId })
|
||||
return internalErrorResponse('Failed to update user billing')
|
||||
}
|
||||
})
|
||||
)
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* GET /api/v1/admin/users/[id]
|
||||
*
|
||||
* Get user details.
|
||||
*
|
||||
* Response: AdminSingleResponse<AdminUser>
|
||||
*/
|
||||
|
||||
import { db } from '@sim/db'
|
||||
import { user } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { adminV1GetUserContract } from '@/lib/api/contracts/v1/admin'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
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 { toAdminUser } from '@/app/api/v1/admin/types'
|
||||
|
||||
const logger = createLogger('AdminUserDetailAPI')
|
||||
|
||||
interface RouteParams {
|
||||
id: string
|
||||
}
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
withAdminAuthParams<RouteParams>(async (request, context) => {
|
||||
const parsed = await parseRequest(adminV1GetUserContract, request, context, {
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
})
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { id: userId } = parsed.data.params
|
||||
|
||||
try {
|
||||
const [userData] = await db.select().from(user).where(eq(user.id, userId)).limit(1)
|
||||
|
||||
if (!userData) {
|
||||
return notFoundResponse('User')
|
||||
}
|
||||
|
||||
const data = toAdminUser(userData)
|
||||
|
||||
logger.info(`Admin API: Retrieved user ${userId}`)
|
||||
|
||||
return singleResponse(data)
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to get user', { error, userId })
|
||||
return internalErrorResponse('Failed to get user')
|
||||
}
|
||||
})
|
||||
)
|
||||
@@ -0,0 +1,62 @@
|
||||
/**
|
||||
* GET /api/v1/admin/users
|
||||
*
|
||||
* List all users with pagination.
|
||||
*
|
||||
* Query Parameters:
|
||||
* - limit: number (default: 50, max: 250)
|
||||
* - offset: number (default: 0)
|
||||
*
|
||||
* Response: AdminListResponse<AdminUser>
|
||||
*/
|
||||
|
||||
import { db } from '@sim/db'
|
||||
import { user } from '@sim/db/schema'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { count } from 'drizzle-orm'
|
||||
import { adminV1ListUsersContract } from '@/lib/api/contracts/v1/admin'
|
||||
import { parseRequest } from '@/lib/api/server'
|
||||
import { withRouteHandler } from '@/lib/core/utils/with-route-handler'
|
||||
import { withAdminAuth } from '@/app/api/v1/admin/middleware'
|
||||
import {
|
||||
adminValidationErrorResponse,
|
||||
internalErrorResponse,
|
||||
listResponse,
|
||||
} from '@/app/api/v1/admin/responses'
|
||||
import { type AdminUser, createPaginationMeta, toAdminUser } from '@/app/api/v1/admin/types'
|
||||
|
||||
const logger = createLogger('AdminUsersAPI')
|
||||
|
||||
export const GET = withRouteHandler(
|
||||
withAdminAuth(async (request) => {
|
||||
const parsed = await parseRequest(
|
||||
adminV1ListUsersContract,
|
||||
request,
|
||||
{},
|
||||
{
|
||||
validationErrorResponse: adminValidationErrorResponse,
|
||||
}
|
||||
)
|
||||
if (!parsed.success) return parsed.response
|
||||
|
||||
const { limit, offset } = parsed.data.query
|
||||
|
||||
try {
|
||||
const [countResult, users] = await Promise.all([
|
||||
db.select({ total: count() }).from(user),
|
||||
db.select().from(user).orderBy(user.name).limit(limit).offset(offset),
|
||||
])
|
||||
|
||||
const total = countResult[0].total
|
||||
const data: AdminUser[] = users.map(toAdminUser)
|
||||
const pagination = createPaginationMeta(total, limit, offset)
|
||||
|
||||
logger.info(`Admin API: Listed ${data.length} users (total: ${total})`)
|
||||
|
||||
return listResponse(data, pagination)
|
||||
} catch (error) {
|
||||
logger.error('Admin API: Failed to list users', { error })
|
||||
return internalErrorResponse('Failed to list users')
|
||||
}
|
||||
})
|
||||
)
|
||||
Reference in New Issue
Block a user