feat: add local auth billing and usage management
This commit is contained in:
1 parent
f642b5e71f
commit
196fdde83f
119 files changed
+15695
-2650
No files matched your search
@@ -1,51 +1,7 @@
|
||||
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { requireAdminSession } from "@/lib/server/auth/current-user";
|
||||
import {
|
||||
createOrganizationGroup,
|
||||
getOrganizationApiConfig,
|
||||
listOrganizationGroups
|
||||
} from "@/lib/server/organization-client";
|
||||
import { jsonError } from "@/lib/server/api";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const config = getOrganizationApiConfig(context.accessToken);
|
||||
if (!config.configured) {
|
||||
throw Object.assign(new Error(`组织接口配置不完整:${config.missing.join(", ")}`), { status: 503 });
|
||||
}
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
const organizationId = requiredString(body, "organizationId", "组织");
|
||||
const groupName = requiredString(body, "groupName", "部门名称");
|
||||
await createOrganizationGroup({
|
||||
organizationId,
|
||||
groupName,
|
||||
groupDesc: optionalString(body.groupDesc),
|
||||
parentId: optionalString(body.parentId)
|
||||
}, context);
|
||||
const groups = await listOrganizationGroups(organizationId, context);
|
||||
const group = groups.find((item) => item.groupName === groupName) || null;
|
||||
return jsonOk({ ok: true, group, groups });
|
||||
} catch (error) {
|
||||
return jsonError(error, 500, { request, source: "api.admin.accounts.groups", logClientErrors: true });
|
||||
}
|
||||
}
|
||||
|
||||
function requiredString(body: Record<string, unknown>, key: string, label: string): string {
|
||||
const value = optionalString(body[key]);
|
||||
if (!value) throw badRequest(`${label}不能为空。`);
|
||||
return value;
|
||||
}
|
||||
|
||||
function optionalString(value: unknown): string | undefined {
|
||||
return typeof value === "string" && value.trim() ? value.trim() : undefined;
|
||||
}
|
||||
|
||||
function badRequest(message: string): Error & { status: number } {
|
||||
const error = new Error(message) as Error & { status: number };
|
||||
error.status = 400;
|
||||
return error;
|
||||
export async function POST() {
|
||||
return jsonError(Object.assign(new Error("平台账号体系不再使用外部部门接口,请直接管理组织。"), { status: 410 }), 410);
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { requireAdminSession } from "@/lib/server/auth/current-user";
|
||||
import { getOrganizationApiConfig, resetPlatformUserPassword } from "@/lib/server/organization-client";
|
||||
import { AccountStoreError, getPlatformUserById, updatePlatformUser } from "@/lib/server/account-store";
|
||||
import { hasSuperAdminAccess } from "@/lib/auth/permissions";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const dynamic = "force-dynamic";
|
||||
@@ -8,53 +9,23 @@ export const dynamic = "force-dynamic";
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const config = getOrganizationApiConfig(context.accessToken);
|
||||
if (!config.staffConfigured) {
|
||||
throw Object.assign(new Error(`企业端用户接口配置不完整:${config.staffMissing.join(", ")}`), { status: 503 });
|
||||
}
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
await resetPlatformUserPassword({
|
||||
tenantId: tenantIdNumber(config.tenantId),
|
||||
userId: requiredNumber(body.userId, "用户 ID"),
|
||||
newPassword: requiredString(body, "newPassword", "新密码"),
|
||||
mustChangePassword: booleanValue(body.mustChangePassword, true)
|
||||
}, context);
|
||||
return jsonOk({ ok: true });
|
||||
const userId = requiredString(body.userId, "账号 ID");
|
||||
const target = await getPlatformUserById(userId, { includeDisabled: true });
|
||||
if (!target) throw new AccountStoreError("账号不存在。", 404);
|
||||
if (!hasSuperAdminAccess(session.user) && (session.user.role !== "organization_admin" || target.role !== "user" || target.organizationId !== session.user.organizationId)) {
|
||||
throw new AccountStoreError("组织管理员只能重置本组织普通用户密码。", 403);
|
||||
}
|
||||
const newPassword = requiredString(body.newPassword, "新密码");
|
||||
if (newPassword.length < 8) throw new AccountStoreError("新密码至少需要 8 位。", 400);
|
||||
const user = await updatePlatformUser(userId, { password: newPassword, clearLoginLock: true });
|
||||
return jsonOk({ ok: true, userId: user.id });
|
||||
} catch (error) {
|
||||
return jsonError(error, 500, { request, source: "api.admin.accounts.password", logClientErrors: true });
|
||||
}
|
||||
}
|
||||
|
||||
function requiredString(body: Record<string, unknown>, key: string, label: string): string {
|
||||
const value = body[key];
|
||||
function requiredString(value: unknown, label: string): string {
|
||||
if (typeof value === "string" && value.trim()) return value.trim();
|
||||
throw badRequest(`${label}不能为空。`);
|
||||
}
|
||||
|
||||
function requiredNumber(value: unknown, label: string): number {
|
||||
const parsed = typeof value === "number" ? value : Number(value);
|
||||
if (Number.isFinite(parsed)) return parsed;
|
||||
throw badRequest(`${label}必须是数字。`);
|
||||
}
|
||||
|
||||
function tenantIdNumber(value: string): number {
|
||||
const tenantId = Number(value);
|
||||
if (!Number.isFinite(tenantId)) throw badRequest("租户 ID 必须是数字。");
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
function booleanValue(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === "boolean") return value;
|
||||
if (typeof value === "string") {
|
||||
if (value === "true") return true;
|
||||
if (value === "false") return false;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function badRequest(message: string): Error & { status: number } {
|
||||
const error = new Error(message) as Error & { status: number };
|
||||
error.status = 400;
|
||||
return error;
|
||||
throw new AccountStoreError(`${label}不能为空。`, 400);
|
||||
}
|
||||
+124
-203
@@ -1,19 +1,18 @@
|
||||
import { jsonError, jsonOk, readJsonBody } from "@/lib/server/api";
|
||||
import { requireAdminSession } from "@/lib/server/auth/current-user";
|
||||
import {
|
||||
addOrganizationMemberAndCreatePlatformUser,
|
||||
emptyPage,
|
||||
getOrganizationApiConfig,
|
||||
isOrganizationPermissionDenied,
|
||||
isOrganizationRouteNotFound,
|
||||
listOrganizationGroups,
|
||||
listOrganizationMembers,
|
||||
listOrganizationRoles,
|
||||
listOrganizations,
|
||||
modifyOrganizationMemberStatus,
|
||||
removeOrganizationMember,
|
||||
updateOrganizationMember
|
||||
} from "@/lib/server/organization-client";
|
||||
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";
|
||||
@@ -21,92 +20,24 @@ export const dynamic = "force-dynamic";
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const config = getOrganizationApiConfig(context.accessToken);
|
||||
const url = new URL(request.url);
|
||||
const pageNum = positiveInteger(url.searchParams.get("pageNum"), 1);
|
||||
const pageSize = positiveInteger(url.searchParams.get("pageSize"), 10, 50);
|
||||
|
||||
if (!config.configured) {
|
||||
return jsonOk({
|
||||
configured: false,
|
||||
missing: config.missing,
|
||||
staffConfigured: config.staffConfigured,
|
||||
staffMissing: config.staffMissing,
|
||||
selectedOrganizationId: config.defaultOrganizationId,
|
||||
organizations: [],
|
||||
groups: [],
|
||||
roles: [],
|
||||
members: emptyPage(pageNum, pageSize),
|
||||
warnings: [],
|
||||
memberListAvailable: false,
|
||||
passwordManagementAvailable: config.staffConfigured
|
||||
});
|
||||
}
|
||||
|
||||
const warnings: string[] = [];
|
||||
let organizations: Awaited<ReturnType<typeof listOrganizations>> = [];
|
||||
try {
|
||||
organizations = await listOrganizations(context);
|
||||
} catch (error) {
|
||||
if (!isOrganizationRouteNotFound(error) || !config.defaultOrganizationId) throw error;
|
||||
warnings.push(error.message);
|
||||
organizations = [{
|
||||
organizationId: config.defaultOrganizationId,
|
||||
organizationName: config.defaultOrganizationId
|
||||
}];
|
||||
}
|
||||
const selectedOrganizationId = url.searchParams.get("organizationId")?.trim() ||
|
||||
config.defaultOrganizationId ||
|
||||
organizations[0]?.organizationId ||
|
||||
"";
|
||||
|
||||
if (!selectedOrganizationId) {
|
||||
return jsonOk({
|
||||
configured: true,
|
||||
missing: [],
|
||||
staffConfigured: config.staffConfigured,
|
||||
staffMissing: config.staffMissing,
|
||||
selectedOrganizationId: "",
|
||||
organizations,
|
||||
groups: [],
|
||||
roles: [],
|
||||
members: emptyPage(pageNum, pageSize),
|
||||
warnings: uniqueWarnings(warnings),
|
||||
memberListAvailable: false,
|
||||
passwordManagementAvailable: config.staffConfigured
|
||||
});
|
||||
}
|
||||
|
||||
const [groupsResult, rolesResult, membersResult] = await Promise.allSettled([
|
||||
listOrganizationGroups(selectedOrganizationId, context),
|
||||
listOrganizationRoles(selectedOrganizationId, context),
|
||||
listOrganizationMembers({
|
||||
organizationId: selectedOrganizationId,
|
||||
pageNum,
|
||||
pageSize,
|
||||
memberName: url.searchParams.get("memberName") || undefined,
|
||||
memberStatus: statusFilter(url.searchParams.get("memberStatus"))
|
||||
}, context)
|
||||
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 })
|
||||
]);
|
||||
const groups = routeFallback(groupsResult, warnings, []);
|
||||
const roles = routeFallback(rolesResult, warnings, []);
|
||||
const members = memberListFallback(membersResult, warnings, emptyPage(pageNum, pageSize));
|
||||
const memberListAvailable = membersResult.status === "fulfilled";
|
||||
|
||||
return jsonOk({
|
||||
configured: true,
|
||||
missing: [],
|
||||
staffConfigured: config.staffConfigured,
|
||||
staffMissing: config.staffMissing,
|
||||
selectedOrganizationId,
|
||||
organizations,
|
||||
groups,
|
||||
roles,
|
||||
members,
|
||||
warnings: uniqueWarnings(warnings),
|
||||
memberListAvailable,
|
||||
passwordManagementAvailable: config.staffConfigured
|
||||
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 });
|
||||
@@ -116,29 +47,24 @@ export async function GET(request: Request) {
|
||||
export async function POST(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const config = getOrganizationApiConfig(context.accessToken);
|
||||
if (!config.staffConfigured) {
|
||||
throw Object.assign(new Error(`企业端用户接口配置不完整:${config.staffMissing.join(", ")}`), { status: 503 });
|
||||
}
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
const memberName = requiredString(body, "memberName", "成员名称");
|
||||
const memberPhone = requiredString(body, "memberPhone", "手机号");
|
||||
const user = await addOrganizationMemberAndCreatePlatformUser({
|
||||
tenantId: tenantIdNumber(config.tenantId),
|
||||
username: optionalString(body.username),
|
||||
phone: optionalString(body.phone) || memberPhone,
|
||||
name: optionalString(body.name) || memberName,
|
||||
nickname: optionalString(body.nickname) || optionalString(body.name) || memberName,
|
||||
initialPassword: optionalString(body.initialPassword),
|
||||
mustChangePassword: booleanValue(body.mustChangePassword, true),
|
||||
memberName,
|
||||
memberPhone,
|
||||
roleId: requiredString(body, "roleId", "角色"),
|
||||
organizationId: requiredString(body, "organizationId", "组织"),
|
||||
groupId: requiredString(body, "groupId", "部门")
|
||||
}, context);
|
||||
return jsonOk({ ok: true, user });
|
||||
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 });
|
||||
}
|
||||
@@ -147,19 +73,25 @@ export async function POST(request: Request) {
|
||||
export async function PATCH(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
const update = {
|
||||
memberId: requiredString(body, "memberId", "成员 ID"),
|
||||
memberName: optionalString(body.memberName),
|
||||
roleId: optionalString(body.roleId),
|
||||
groupId: optionalString(body.groupId)
|
||||
};
|
||||
if (!update.memberName && !update.roleId && !update.groupId) {
|
||||
throw badRequest("至少需要修改一个成员字段。");
|
||||
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);
|
||||
}
|
||||
await updateOrganizationMember(update, context);
|
||||
return jsonOk({ ok: true });
|
||||
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 });
|
||||
}
|
||||
@@ -168,13 +100,14 @@ export async function PATCH(request: Request) {
|
||||
export async function PUT(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
await modifyOrganizationMemberStatus({
|
||||
memberId: requiredString(body, "memberId", "成员 ID"),
|
||||
memberStatus: memberStatus(requiredString(body, "memberStatus", "成员状态"))
|
||||
}, context);
|
||||
return jsonOk({ ok: true });
|
||||
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 });
|
||||
}
|
||||
@@ -183,84 +116,72 @@ export async function PUT(request: Request) {
|
||||
export async function DELETE(request: Request) {
|
||||
try {
|
||||
const session = await requireAdminSession();
|
||||
const context = { accessToken: session.accessToken };
|
||||
const body = await readJsonBody<Record<string, unknown>>(request);
|
||||
await removeOrganizationMember(requiredString(body, "memberId", "成员 ID"), context);
|
||||
return jsonOk({ ok: true });
|
||||
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 });
|
||||
}
|
||||
}
|
||||
|
||||
function requiredString(body: Record<string, unknown>, key: string, label: string): string {
|
||||
const value = optionalString(body[key]);
|
||||
if (!value) throw badRequest(`${label}不能为空。`);
|
||||
async function getTarget(body: Record<string, unknown>) {
|
||||
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;
|
||||
}
|
||||
|
||||
function memberStatus(value: string): "0" | "1" | "2" {
|
||||
if (value === "0" || value === "1" || value === "2") return value;
|
||||
throw badRequest("成员状态只能是 0、1、2。");
|
||||
}
|
||||
|
||||
function statusFilter(value: string | null): string | undefined {
|
||||
return value === "0" || value === "1" || value === "2" ? value : undefined;
|
||||
}
|
||||
|
||||
function routeFallback<T>(result: PromiseSettledResult<T>, warnings: string[], fallback: T): T {
|
||||
if (result.status === "fulfilled") return result.value;
|
||||
if (!isOrganizationRouteNotFound(result.reason)) throw result.reason;
|
||||
warnings.push(result.reason.message);
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function memberListFallback<T>(result: PromiseSettledResult<T>, warnings: string[], fallback: T): T {
|
||||
if (result.status === "fulfilled") return result.value;
|
||||
if (!isOrganizationRouteNotFound(result.reason) && !isOrganizationPermissionDenied(result.reason)) {
|
||||
throw result.reason;
|
||||
}
|
||||
warnings.push(memberListWarning(result.reason));
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function memberListWarning(error: unknown): string {
|
||||
if (isOrganizationPermissionDenied(error)) {
|
||||
return "当前登录 token 缺少上游 hotelStaff 管理员角色,成员列表暂不可用。";
|
||||
}
|
||||
return error instanceof Error ? error.message : String(error);
|
||||
}
|
||||
|
||||
function uniqueWarnings(warnings: string[]): string[] {
|
||||
return [...new Set(warnings.filter(Boolean))];
|
||||
}
|
||||
|
||||
function tenantIdNumber(value: string): number {
|
||||
const tenantId = Number(value);
|
||||
if (!Number.isFinite(tenantId)) throw badRequest("租户 ID 必须是数字。");
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
function booleanValue(value: unknown, fallback: boolean): boolean {
|
||||
if (typeof value === "boolean") return value;
|
||||
if (typeof value === "string") {
|
||||
if (value === "true") return true;
|
||||
if (value === "false") return false;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
function positiveInteger(value: string | null, fallback: number, max = 200): number {
|
||||
const parsed = Number(value);
|
||||
if (!Number.isInteger(parsed) || parsed < 1) return fallback;
|
||||
return Math.min(parsed, max);
|
||||
}
|
||||
|
||||
function badRequest(message: string): Error & { status: number } {
|
||||
const error = new Error(message) as Error & { status: number };
|
||||
error.status = 400;
|
||||
return error;
|
||||
}
|
||||
Reference in new issue
Block a user