import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api"; import { requireAdminSession } from "@/lib/server/auth/current-user"; import { AccountStoreError, createPlatformUser, deletePlatformUser, getPlatformUserById, listPlatformOrganizations, listPlatformUsers, updatePlatformUser, type PlatformUserFilters } from "@/lib/server/account-store"; import { hasSuperAdminAccess } from "@/lib/auth/permissions"; import type { AuthUser } from "@/lib/auth/session"; import type { PlatformRole } from "@/lib/types"; export const runtime = "nodejs"; export const dynamic = "force-dynamic"; export async function GET(request: Request) { try { const session = await requireAdminSession(); const url = new URL(request.url); const isSuperAdmin = hasSuperAdminAccess(session.user); const organizationId = isSuperAdmin ? optionalString(url.searchParams.get("organizationId")) : requiredOrganizationId(session.user.organizationId); const filters: PlatformUserFilters = { organizationId, includeDisabled: true, role: isSuperAdmin ? undefined : "user" }; const [members, organizations] = await Promise.all([ listPlatformUsers(filters), listPlatformOrganizations({ includeDisabled: isSuperAdmin }) ]); return jsonOk({ configured: true, currentOrganizationId: organizationId || null, organizations: isSuperAdmin ? organizations.map(publicOrganization) : organizations.filter((item) => item.id === organizationId).map(publicOrganization), members: members.map(publicUser), canManageOrganizations: isSuperAdmin, canAssignOrganizationAdmin: isSuperAdmin, canCreateSuperAdmin: isSuperAdmin }); } catch (error) { return jsonError(error, 500, { request, source: "api.admin.accounts", logClientErrors: true }); } } export async function POST(request: Request) { try { const session = await requireAdminSession(); const body = await readJsonBody>(request); const isSuperAdmin = hasSuperAdminAccess(session.user); const role = parseRole(body.role, isSuperAdmin ? "user" : "user"); if (!isSuperAdmin && role !== "user") throw new AccountStoreError("组织管理员只能创建普通用户。", 403); const organizationId = role === "super_admin" ? optionalString(body.organizationId) : isSuperAdmin ? requiredString(body.organizationId, "组织") : requiredOrganizationId(session.user.organizationId); const user = await createPlatformUser({ phone: requiredString(body.phone, "手机号"), displayName: requiredString(body.displayName, "显示名称"), password: requiredString(body.password, "初始密码"), role, organizationId, legacySubject: optionalString(body.legacySubject) }); return jsonOk({ ok: true, user: publicUser(user) }, { status: 201 }); } catch (error) { return jsonError(error, 500, { request, source: "api.admin.accounts", logClientErrors: true }); } } export async function PATCH(request: Request) { try { const session = await requireAdminSession(); const body = await readJsonBody>(request); const target = await getTarget(body); assertCanManageTarget(session.user, target, "修改"); const isSuperAdmin = hasSuperAdminAccess(session.user); const role = body.role === undefined ? undefined : parseRole(body.role, target.role); if (!isSuperAdmin && role !== undefined && role !== target.role) { throw new AccountStoreError("组织管理员不能修改账号角色。", 403); } if (!isSuperAdmin && body.organizationId !== undefined) { throw new AccountStoreError("组织管理员不能修改账号归属。", 403); } const user = await updatePlatformUser(target.id, { displayName: optionalString(body.displayName), role, organizationId: isSuperAdmin && body.organizationId !== undefined ? optionalString(body.organizationId) : undefined, status: parseStatus(body.status), clearLoginLock: body.clearLoginLock === true }); return jsonOk({ ok: true, user: publicUser(user) }); } catch (error) { return jsonError(error, 500, { request, source: "api.admin.accounts", logClientErrors: true }); } } export async function PUT(request: Request) { try { const session = await requireAdminSession(); const body = await readJsonBody>(request); const target = await getTarget(body); assertCanManageTarget(session.user, target, "变更状态"); const status = parseStatus(requiredString(body.status, "账号状态")); if (!status) throw new AccountStoreError("账号状态只能是 active 或 disabled。", 400); if (target.id === session.user.id && status === "disabled") throw new AccountStoreError("不能停用当前登录账号。", 400); const user = await updatePlatformUser(target.id, { status, clearLoginLock: status === "active" }); return jsonOk({ ok: true, user: publicUser(user) }); } catch (error) { return jsonError(error, 500, { request, source: "api.admin.accounts", logClientErrors: true }); } } export async function DELETE(request: Request) { try { const session = await requireAdminSession(); const body = await readJsonBody>(request); const target = await getTarget(body); assertCanManageTarget(session.user, target, "删除"); if (target.id === session.user.id) throw new AccountStoreError("不能删除当前登录账号。", 400); await deletePlatformUser(target.id); return jsonOk({ ok: true, archivedOwnerId: target.organizationId ? `archive:${target.organizationId}` : "archive:global" }); } catch (error) { return jsonError(error, 500, { request, source: "api.admin.accounts", logClientErrors: true }); } } async function getTarget(body: Record) { const id = requiredString(body.userId, "账号 ID"); const user = await getPlatformUserById(id, { includeDisabled: true }); if (!user) throw new AccountStoreError("账号不存在。", 404); return user; } function assertCanManageTarget(actor: AuthUser, target: { id: string; role: PlatformRole; organizationId?: string }, action: string) { if (hasSuperAdminAccess(actor)) return; if (actor.role !== "organization_admin" || target.role !== "user" || actor.organizationId !== target.organizationId) { throw new AccountStoreError(`组织管理员不能${action}该账号。`, 403); } } function publicOrganization(organization: { id: string; name: string; status: string }) { return { id: organization.id, name: organization.name, status: organization.status }; } function publicUser(user: { id: string; phone: string; displayName: string; role: PlatformRole; organizationId?: string; status: string; createdAt: string; lastLoginAt?: string; lockedUntil?: string }) { return { id: user.id, phone: user.phone, displayName: user.displayName, role: user.role, organizationId: user.organizationId || null, status: user.status, createdAt: user.createdAt, lastLoginAt: user.lastLoginAt || null, lockedUntil: user.lockedUntil || null }; } function parseRole(value: unknown, fallback: PlatformRole): PlatformRole { if (value === undefined || value === null || value === "") return fallback; if (value === "super_admin" || value === "organization_admin" || value === "user") return value; throw new AccountStoreError("账号角色不正确。", 400); } function parseStatus(value: unknown): "active" | "disabled" | undefined { if (value === undefined || value === null || value === "") return undefined; if (value === "active" || value === "disabled") return value; throw new AccountStoreError("账号状态不正确。", 400); } function requiredString(value: unknown, label: string): string { const normalized = optionalString(value); if (!normalized) throw new AccountStoreError(`${label}不能为空。`, 400); return normalized; } function requiredOrganizationId(value: string | undefined): string { if (!value) throw new AccountStoreError("当前账号没有组织归属。", 403); return value; } function optionalString(value: unknown): string | undefined { return typeof value === "string" && value.trim() ? value.trim() : undefined; }