feat: add system configuration platform
This commit is contained in:
@@ -15,11 +15,27 @@ export function jsonSuccess<T extends Record<string, unknown>>(
|
||||
payload: T,
|
||||
status = 200,
|
||||
): Response {
|
||||
return Response.json({ success: true, reason, ...payload }, { status });
|
||||
return Response.json(
|
||||
{ success: true, reason, ...payload },
|
||||
{
|
||||
status,
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export function jsonFailure(reason: string, status = 400): Response {
|
||||
return Response.json({ success: false, reason }, { status });
|
||||
return Response.json(
|
||||
{ success: false, reason },
|
||||
{
|
||||
status,
|
||||
headers: {
|
||||
"Cache-Control": "no-store",
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export async function readJsonBody(request: Request): Promise<unknown> {
|
||||
@@ -29,4 +45,3 @@ export async function readJsonBody(request: Request): Promise<unknown> {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { desc, eq } from "drizzle-orm";
|
||||
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { auditLogs } from "@/modules/core/server/schema";
|
||||
import type { AuditLog, AuditResult, PublicAccount } from "@/modules/core/types";
|
||||
import { updateData } from "@/modules/core/server/store";
|
||||
|
||||
type AuditInput = {
|
||||
actor?: PublicAccount;
|
||||
organizationId?: string;
|
||||
action: string;
|
||||
targetType: string;
|
||||
targetId?: string;
|
||||
@@ -12,13 +14,27 @@ type AuditInput = {
|
||||
reason: string;
|
||||
};
|
||||
|
||||
export async function recordAuditLog(input: AuditInput): Promise<AuditLog> {
|
||||
const timestamp = new Date().toISOString();
|
||||
function toAuditLog(row: typeof auditLogs.$inferSelect): AuditLog {
|
||||
return {
|
||||
id: row.id,
|
||||
organizationId: row.organizationId ?? undefined,
|
||||
timestamp: row.timestamp.toISOString(),
|
||||
actorAccountId: row.actorAccountId ?? undefined,
|
||||
actorEmail: row.actorEmail ?? undefined,
|
||||
action: row.action,
|
||||
targetType: row.targetType,
|
||||
targetId: row.targetId ?? undefined,
|
||||
result: row.result,
|
||||
reason: row.reason,
|
||||
};
|
||||
}
|
||||
|
||||
return await updateData((data) => {
|
||||
const nextLog: AuditLog = {
|
||||
id: randomUUID(),
|
||||
timestamp,
|
||||
export async function recordAuditLog(input: AuditInput): Promise<AuditLog> {
|
||||
const database = getDatabase();
|
||||
const rows = await database
|
||||
.insert(auditLogs)
|
||||
.values({
|
||||
organizationId: input.organizationId,
|
||||
actorAccountId: input.actor?.id,
|
||||
actorEmail: input.actor?.email,
|
||||
action: input.action,
|
||||
@@ -26,10 +42,27 @@ export async function recordAuditLog(input: AuditInput): Promise<AuditLog> {
|
||||
targetId: input.targetId,
|
||||
result: input.result,
|
||||
reason: input.reason,
|
||||
};
|
||||
})
|
||||
.returning();
|
||||
const row = rows[0];
|
||||
if (!row) {
|
||||
throw new Error("审计日志写入失败");
|
||||
}
|
||||
|
||||
data.auditLogs = [nextLog, ...data.auditLogs].slice(0, 500);
|
||||
return nextLog;
|
||||
});
|
||||
return toAuditLog(row);
|
||||
}
|
||||
|
||||
export async function listAuditLogs(params: { organizationId?: string; limit?: number }): Promise<AuditLog[]> {
|
||||
const database = getDatabase();
|
||||
const limit = params.limit ?? 100;
|
||||
const rows = params.organizationId
|
||||
? await database
|
||||
.select()
|
||||
.from(auditLogs)
|
||||
.where(eq(auditLogs.organizationId, params.organizationId))
|
||||
.orderBy(desc(auditLogs.timestamp))
|
||||
.limit(limit)
|
||||
: await database.select().from(auditLogs).orderBy(desc(auditLogs.timestamp)).limit(limit);
|
||||
|
||||
return rows.map(toAuditLog);
|
||||
}
|
||||
|
||||
@@ -1,30 +1,83 @@
|
||||
import { randomBytes, randomUUID, scryptSync, timingSafeEqual } from "node:crypto";
|
||||
import { randomBytes, scryptSync, timingSafeEqual } from "node:crypto";
|
||||
|
||||
import { and, eq, gt, isNull } from "drizzle-orm";
|
||||
import { cookies } from "next/headers";
|
||||
|
||||
import type { Account, AuthContext, Permission, PublicAccount, RoleId, Session } from "@/modules/core/types";
|
||||
import { jsonFailure } from "@/modules/core/server/api";
|
||||
import { recordAuditLog } from "@/modules/core/server/audit";
|
||||
import { getPermissionsForRole, hasPermission } from "@/modules/core/server/permissions";
|
||||
import { readData, updateData } from "@/modules/core/server/store";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { getPermissionsForRole, hasPermission, seedOrganizationRoles } from "@/modules/core/server/permissions";
|
||||
import { accounts, joinRequests, memberships, organizations, roles, sessions } from "@/modules/core/server/schema";
|
||||
import type { Account, AuthContext, Membership, Organization, Permission, PublicAccount, Session } from "@/modules/core/types";
|
||||
|
||||
const SESSION_COOKIE = "teatea_session";
|
||||
const SESSION_MAX_AGE_SECONDS = 60 * 60 * 24 * 7;
|
||||
|
||||
type AccountRow = typeof accounts.$inferSelect;
|
||||
type OrganizationRow = typeof organizations.$inferSelect;
|
||||
type MembershipRow = typeof memberships.$inferSelect;
|
||||
type RoleRow = typeof roles.$inferSelect;
|
||||
type SessionRow = typeof sessions.$inferSelect;
|
||||
|
||||
export function normalizeEmail(email: string): string {
|
||||
return email.trim().toLowerCase();
|
||||
}
|
||||
|
||||
export function toPublicAccount(account: Account): PublicAccount {
|
||||
function toIsoString(value: Date): string {
|
||||
return value.toISOString();
|
||||
}
|
||||
|
||||
function toOrganization(row: OrganizationRow): Organization {
|
||||
return {
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
slug: row.slug,
|
||||
status: row.status,
|
||||
createdAt: toIsoString(row.createdAt),
|
||||
updatedAt: toIsoString(row.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
function toSession(row: SessionRow): Session {
|
||||
return {
|
||||
id: row.id,
|
||||
accountId: row.accountId,
|
||||
activeOrganizationId: row.activeOrganizationId ?? undefined,
|
||||
createdAt: toIsoString(row.createdAt),
|
||||
expiresAt: toIsoString(row.expiresAt),
|
||||
};
|
||||
}
|
||||
|
||||
function toMembership(row: MembershipRow, role: RoleRow): Membership {
|
||||
return {
|
||||
id: row.id,
|
||||
accountId: row.accountId,
|
||||
organizationId: row.organizationId,
|
||||
roleId: row.roleId,
|
||||
roleKey: role.key,
|
||||
roleLabel: role.label,
|
||||
status: row.status,
|
||||
createdAt: toIsoString(row.createdAt),
|
||||
updatedAt: toIsoString(row.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
export function toPublicAccount(account: AccountRow | Account, roleKey?: string, organization?: Organization): PublicAccount {
|
||||
const fallbackRole = "role" in account ? account.role : "viewer";
|
||||
const fallbackOrganization = "organization" in account ? account.organization : undefined;
|
||||
const fallbackOrganizationId = "organizationId" in account ? account.organizationId : undefined;
|
||||
|
||||
return {
|
||||
id: account.id,
|
||||
platformRoleId: "platformRoleId" in account ? account.platformRoleId ?? undefined : undefined,
|
||||
name: account.name,
|
||||
email: account.email,
|
||||
role: account.role,
|
||||
organization: account.organization,
|
||||
role: roleKey ?? fallbackRole,
|
||||
organization: organization?.name ?? fallbackOrganization,
|
||||
organizationId: organization?.id ?? fallbackOrganizationId,
|
||||
status: account.status,
|
||||
createdAt: account.createdAt,
|
||||
updatedAt: account.updatedAt,
|
||||
createdAt: typeof account.createdAt === "string" ? account.createdAt : toIsoString(account.createdAt),
|
||||
updatedAt: typeof account.updatedAt === "string" ? account.updatedAt : toIsoString(account.updatedAt),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -38,7 +91,7 @@ export function hashPassword(password: string, salt = randomBytes(16).toString("
|
||||
};
|
||||
}
|
||||
|
||||
export function verifyPassword(password: string, account: Account): boolean {
|
||||
export function verifyPassword(password: string, account: Pick<AccountRow, "passwordHash" | "passwordSalt">): boolean {
|
||||
const candidate = Buffer.from(hashPassword(password, account.passwordSalt).hash, "hex");
|
||||
const stored = Buffer.from(account.passwordHash, "hex");
|
||||
|
||||
@@ -49,40 +102,14 @@ export function verifyPassword(password: string, account: Account): boolean {
|
||||
return timingSafeEqual(candidate, stored);
|
||||
}
|
||||
|
||||
export function createAccountRecord(input: {
|
||||
name: string;
|
||||
email: string;
|
||||
password: string;
|
||||
role: RoleId;
|
||||
organization?: string;
|
||||
}): Account {
|
||||
const now = new Date().toISOString();
|
||||
const password = hashPassword(input.password);
|
||||
function createSlug(name: string): string {
|
||||
const base = name
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-|-$/g, "");
|
||||
|
||||
return {
|
||||
id: randomUUID(),
|
||||
name: input.name.trim(),
|
||||
email: normalizeEmail(input.email),
|
||||
role: input.role,
|
||||
organization: input.organization?.trim(),
|
||||
passwordHash: password.hash,
|
||||
passwordSalt: password.salt,
|
||||
status: "active",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
};
|
||||
}
|
||||
|
||||
export function createSessionRecord(accountId: string): Session {
|
||||
const now = new Date();
|
||||
const expiresAt = new Date(now.getTime() + SESSION_MAX_AGE_SECONDS * 1000);
|
||||
|
||||
return {
|
||||
id: randomUUID(),
|
||||
accountId,
|
||||
createdAt: now.toISOString(),
|
||||
expiresAt: expiresAt.toISOString(),
|
||||
};
|
||||
return base.length > 0 ? base : `org-${Date.now()}`;
|
||||
}
|
||||
|
||||
export async function setSessionCookie(sessionId: string): Promise<void> {
|
||||
@@ -103,8 +130,255 @@ export async function clearSessionCookie(): Promise<void> {
|
||||
}
|
||||
|
||||
export async function getBootstrapState(): Promise<{ setupRequired: boolean }> {
|
||||
const data = await readData();
|
||||
return { setupRequired: data.accounts.length === 0 };
|
||||
const database = getDatabase();
|
||||
const existingAccounts = await database.select({ id: accounts.id }).from(accounts).limit(1);
|
||||
return { setupRequired: existingAccounts.length === 0 };
|
||||
}
|
||||
|
||||
export async function setupFirstPlatformAdmin(input: {
|
||||
organization: string;
|
||||
name: string;
|
||||
email: string;
|
||||
password: string;
|
||||
}): Promise<{ account: PublicAccount; session: Session }> {
|
||||
const database = getDatabase();
|
||||
const password = hashPassword(input.password);
|
||||
const expiresAt = new Date(Date.now() + SESSION_MAX_AGE_SECONDS * 1000);
|
||||
|
||||
const created = await database.transaction(async (transaction) => {
|
||||
const existingAccounts = await transaction.select({ id: accounts.id }).from(accounts).limit(1);
|
||||
if (existingAccounts.length > 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const platformRoleRows = await transaction
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.key, "platform_admin"), isNull(roles.organizationId)))
|
||||
.limit(1);
|
||||
const platformRole = platformRoleRows[0];
|
||||
if (!platformRole) {
|
||||
throw new Error("平台超管角色未初始化,请先运行数据库初始化");
|
||||
}
|
||||
|
||||
const organizationRows = await transaction
|
||||
.insert(organizations)
|
||||
.values({
|
||||
name: input.organization.trim(),
|
||||
slug: createSlug(input.organization),
|
||||
})
|
||||
.returning();
|
||||
const organization = organizationRows[0];
|
||||
if (!organization) {
|
||||
throw new Error("机构初始化失败");
|
||||
}
|
||||
|
||||
const accountRows = await transaction
|
||||
.insert(accounts)
|
||||
.values({
|
||||
platformRoleId: platformRole.id,
|
||||
name: input.name.trim(),
|
||||
email: normalizeEmail(input.email),
|
||||
passwordHash: password.hash,
|
||||
passwordSalt: password.salt,
|
||||
status: "active",
|
||||
})
|
||||
.returning();
|
||||
const account = accountRows[0];
|
||||
if (!account) {
|
||||
throw new Error("账号初始化失败");
|
||||
}
|
||||
|
||||
const sessionRows = await transaction
|
||||
.insert(sessions)
|
||||
.values({
|
||||
accountId: account.id,
|
||||
activeOrganizationId: organization.id,
|
||||
expiresAt,
|
||||
})
|
||||
.returning();
|
||||
const session = sessionRows[0];
|
||||
if (!session) {
|
||||
throw new Error("会话初始化失败");
|
||||
}
|
||||
|
||||
return { account, organization, platformRole, session };
|
||||
});
|
||||
|
||||
if (!created) {
|
||||
throw new Error("系统已完成初始化");
|
||||
}
|
||||
|
||||
await seedOrganizationRoles(created.organization.id);
|
||||
const databaseAfterSeed = getDatabase();
|
||||
const orgAdminRows = await databaseAfterSeed
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.organizationId, created.organization.id), eq(roles.key, "org_admin")))
|
||||
.limit(1);
|
||||
const orgAdminRole = orgAdminRows[0];
|
||||
if (orgAdminRole) {
|
||||
await databaseAfterSeed
|
||||
.insert(memberships)
|
||||
.values({
|
||||
accountId: created.account.id,
|
||||
organizationId: created.organization.id,
|
||||
roleId: orgAdminRole.id,
|
||||
status: "active",
|
||||
})
|
||||
.onConflictDoNothing();
|
||||
}
|
||||
|
||||
const organization = toOrganization(created.organization);
|
||||
const publicAccount = toPublicAccount(created.account, created.platformRole.key, organization);
|
||||
const session = toSession(created.session);
|
||||
|
||||
await recordAuditLog({
|
||||
actor: publicAccount,
|
||||
organizationId: organization.id,
|
||||
action: "account.setup",
|
||||
targetType: "account",
|
||||
targetId: publicAccount.id,
|
||||
result: "success",
|
||||
reason: "初始化平台超管与首个机构",
|
||||
});
|
||||
|
||||
return { account: publicAccount, session };
|
||||
}
|
||||
|
||||
export async function createRegistration(input: {
|
||||
name: string;
|
||||
email: string;
|
||||
password: string;
|
||||
organizationId?: string;
|
||||
}): Promise<{ account: PublicAccount; session: Session }> {
|
||||
const database = getDatabase();
|
||||
const password = hashPassword(input.password);
|
||||
const expiresAt = new Date(Date.now() + SESSION_MAX_AGE_SECONDS * 1000);
|
||||
|
||||
const created = await database.transaction(async (transaction) => {
|
||||
const normalizedEmail = normalizeEmail(input.email);
|
||||
const existing = await transaction.select({ id: accounts.id }).from(accounts).where(eq(accounts.email, normalizedEmail));
|
||||
if (existing.length > 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const accountRows = await transaction
|
||||
.insert(accounts)
|
||||
.values({
|
||||
name: input.name.trim(),
|
||||
email: normalizedEmail,
|
||||
passwordHash: password.hash,
|
||||
passwordSalt: password.salt,
|
||||
status: input.organizationId ? "pending" : "active",
|
||||
})
|
||||
.returning();
|
||||
const account = accountRows[0];
|
||||
if (!account) {
|
||||
throw new Error("账号创建失败");
|
||||
}
|
||||
|
||||
const sessionRows = await transaction
|
||||
.insert(sessions)
|
||||
.values({
|
||||
accountId: account.id,
|
||||
activeOrganizationId: input.organizationId,
|
||||
expiresAt,
|
||||
})
|
||||
.returning();
|
||||
const session = sessionRows[0];
|
||||
if (!session) {
|
||||
throw new Error("会话创建失败");
|
||||
}
|
||||
|
||||
if (input.organizationId) {
|
||||
await transaction.insert(joinRequests).values({
|
||||
accountId: account.id,
|
||||
organizationId: input.organizationId,
|
||||
status: "pending",
|
||||
reason: "公开注册申请加入机构",
|
||||
});
|
||||
}
|
||||
|
||||
return { account, session };
|
||||
});
|
||||
|
||||
if (!created) {
|
||||
throw new Error("账号已存在");
|
||||
}
|
||||
|
||||
const publicAccount = toPublicAccount(created.account);
|
||||
const session = toSession(created.session);
|
||||
await recordAuditLog({
|
||||
actor: publicAccount,
|
||||
organizationId: input.organizationId,
|
||||
action: "account.register",
|
||||
targetType: "account",
|
||||
targetId: publicAccount.id,
|
||||
result: "success",
|
||||
reason: input.organizationId ? "注册账号并申请加入机构" : "注册独立账号",
|
||||
});
|
||||
|
||||
return { account: publicAccount, session };
|
||||
}
|
||||
|
||||
export async function loginWithPassword(input: {
|
||||
email: string;
|
||||
password: string;
|
||||
}): Promise<{ account: PublicAccount; session: Session }> {
|
||||
const database = getDatabase();
|
||||
const accountRows = await database
|
||||
.select()
|
||||
.from(accounts)
|
||||
.where(eq(accounts.email, normalizeEmail(input.email)))
|
||||
.limit(1);
|
||||
const account = accountRows[0];
|
||||
|
||||
if (!account || account.status === "disabled" || !verifyPassword(input.password, account)) {
|
||||
throw new Error("邮箱或密码错误");
|
||||
}
|
||||
|
||||
const membershipRows = await database
|
||||
.select({ membership: memberships, organization: organizations, role: roles })
|
||||
.from(memberships)
|
||||
.innerJoin(organizations, eq(organizations.id, memberships.organizationId))
|
||||
.innerJoin(roles, eq(roles.id, memberships.roleId))
|
||||
.where(and(eq(memberships.accountId, account.id), eq(memberships.status, "active")))
|
||||
.limit(1);
|
||||
const membership = membershipRows[0];
|
||||
const expiresAt = new Date(Date.now() + SESSION_MAX_AGE_SECONDS * 1000);
|
||||
const sessionRows = await database
|
||||
.insert(sessions)
|
||||
.values({
|
||||
accountId: account.id,
|
||||
activeOrganizationId: membership?.organization.id,
|
||||
expiresAt,
|
||||
})
|
||||
.returning();
|
||||
const sessionRow = sessionRows[0];
|
||||
if (!sessionRow) {
|
||||
throw new Error("会话创建失败");
|
||||
}
|
||||
|
||||
const platformRoleRows = account.platformRoleId
|
||||
? await database.select().from(roles).where(eq(roles.id, account.platformRoleId)).limit(1)
|
||||
: [];
|
||||
const platformRole = platformRoleRows[0];
|
||||
const organization = membership ? toOrganization(membership.organization) : undefined;
|
||||
const publicAccount = toPublicAccount(account, platformRole?.key ?? membership?.role.key, organization);
|
||||
const session = toSession(sessionRow);
|
||||
|
||||
await recordAuditLog({
|
||||
actor: publicAccount,
|
||||
organizationId: organization?.id,
|
||||
action: "account.login",
|
||||
targetType: "account",
|
||||
targetId: account.id,
|
||||
result: "success",
|
||||
reason: "账号登录",
|
||||
});
|
||||
|
||||
return { account: publicAccount, session };
|
||||
}
|
||||
|
||||
export async function getCurrentAuthContext(): Promise<AuthContext | null> {
|
||||
@@ -115,20 +389,54 @@ export async function getCurrentAuthContext(): Promise<AuthContext | null> {
|
||||
return null;
|
||||
}
|
||||
|
||||
const data = await readData();
|
||||
const session = data.sessions.find((item) => item.id === sessionId);
|
||||
if (!session || Date.parse(session.expiresAt) <= Date.now()) {
|
||||
const database = getDatabase();
|
||||
const rows = await database
|
||||
.select({ session: sessions, account: accounts })
|
||||
.from(sessions)
|
||||
.innerJoin(accounts, eq(accounts.id, sessions.accountId))
|
||||
.where(and(eq(sessions.id, sessionId), gt(sessions.expiresAt, new Date())))
|
||||
.limit(1);
|
||||
const row = rows[0];
|
||||
if (!row || row.account.status === "disabled") {
|
||||
return null;
|
||||
}
|
||||
|
||||
const account = data.accounts.find((item) => item.id === session.accountId);
|
||||
if (!account || account.status !== "active") {
|
||||
return null;
|
||||
}
|
||||
const session = toSession(row.session);
|
||||
const platformRoleRows = row.account.platformRoleId
|
||||
? await database.select().from(roles).where(eq(roles.id, row.account.platformRoleId)).limit(1)
|
||||
: [];
|
||||
const platformRole = platformRoleRows[0];
|
||||
const organizationRows = row.session.activeOrganizationId
|
||||
? await database.select().from(organizations).where(eq(organizations.id, row.session.activeOrganizationId)).limit(1)
|
||||
: [];
|
||||
const organizationRow = organizationRows[0];
|
||||
const membershipRows = organizationRow
|
||||
? await database
|
||||
.select({ membership: memberships, role: roles })
|
||||
.from(memberships)
|
||||
.innerJoin(roles, eq(roles.id, memberships.roleId))
|
||||
.where(
|
||||
and(
|
||||
eq(memberships.accountId, row.account.id),
|
||||
eq(memberships.organizationId, organizationRow.id),
|
||||
eq(memberships.status, "active"),
|
||||
),
|
||||
)
|
||||
.limit(1)
|
||||
: [];
|
||||
const membershipRow = membershipRows[0];
|
||||
|
||||
const platformPermissions = platformRole ? await getPermissionsForRole(platformRole.id) : [];
|
||||
const organizationPermissions = membershipRow ? await getPermissionsForRole(membershipRow.role.id) : [];
|
||||
const permissions = [...new Set([...platformPermissions, ...organizationPermissions])];
|
||||
const organization = organizationRow ? toOrganization(organizationRow) : undefined;
|
||||
const membership = membershipRow ? toMembership(membershipRow.membership, membershipRow.role) : undefined;
|
||||
|
||||
return {
|
||||
account: toPublicAccount(account),
|
||||
permissions: getPermissionsForRole(account.role),
|
||||
account: toPublicAccount(row.account, platformRole?.key ?? membership?.roleKey, organization),
|
||||
organization,
|
||||
membership,
|
||||
permissions,
|
||||
session,
|
||||
};
|
||||
}
|
||||
@@ -139,9 +447,8 @@ export async function removeCurrentSession(): Promise<PublicAccount | null> {
|
||||
const sessionId = cookieStore.get(SESSION_COOKIE)?.value;
|
||||
|
||||
if (sessionId) {
|
||||
await updateData((data) => {
|
||||
data.sessions = data.sessions.filter((item) => item.id !== sessionId);
|
||||
});
|
||||
const database = getDatabase();
|
||||
await database.delete(sessions).where(eq(sessions.id, sessionId));
|
||||
}
|
||||
|
||||
await clearSessionCookie();
|
||||
@@ -162,6 +469,7 @@ type DeniedAuditContext = {
|
||||
action: string;
|
||||
targetType: string;
|
||||
targetId?: string;
|
||||
organizationId?: string;
|
||||
};
|
||||
|
||||
export async function requirePermission(
|
||||
@@ -172,6 +480,7 @@ export async function requirePermission(
|
||||
|
||||
if (!context) {
|
||||
await recordAuditLog({
|
||||
organizationId: auditContext.organizationId,
|
||||
action: auditContext.action,
|
||||
targetType: auditContext.targetType,
|
||||
targetId: auditContext.targetId,
|
||||
@@ -185,9 +494,10 @@ export async function requirePermission(
|
||||
};
|
||||
}
|
||||
|
||||
if (!hasPermission(context.account.role, permission)) {
|
||||
if (!hasPermission(context.permissions, permission)) {
|
||||
await recordAuditLog({
|
||||
actor: context.account,
|
||||
organizationId: auditContext.organizationId ?? context.organization?.id,
|
||||
action: auditContext.action,
|
||||
targetType: auditContext.targetType,
|
||||
targetId: auditContext.targetId,
|
||||
|
||||
37
modules/core/server/db.ts
Normal file
37
modules/core/server/db.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import "server-only";
|
||||
|
||||
import { sql } from "drizzle-orm";
|
||||
import { drizzle, type PostgresJsDatabase } from "drizzle-orm/postgres-js";
|
||||
import postgres from "postgres";
|
||||
|
||||
import * as schema from "@/modules/core/server/schema";
|
||||
|
||||
export type AppDatabase = PostgresJsDatabase<typeof schema>;
|
||||
|
||||
let cachedDatabase: AppDatabase | null = null;
|
||||
let cachedClient: postgres.Sql | null = null;
|
||||
|
||||
export function getDatabase(): AppDatabase {
|
||||
const databaseUrl = process.env.DATABASE_URL;
|
||||
if (!databaseUrl) {
|
||||
throw new Error("DATABASE_URL is required for database-backed system configuration");
|
||||
}
|
||||
|
||||
if (!cachedDatabase) {
|
||||
cachedClient = postgres(databaseUrl, { max: 1 });
|
||||
cachedDatabase = drizzle(cachedClient, { schema });
|
||||
}
|
||||
|
||||
return cachedDatabase;
|
||||
}
|
||||
|
||||
export async function checkDatabaseConnection(): Promise<{ ok: boolean; reason: string }> {
|
||||
try {
|
||||
const database = getDatabase();
|
||||
await database.execute(sql`select 1`);
|
||||
return { ok: true, reason: "数据库连接正常" };
|
||||
} catch (error) {
|
||||
const reason = error instanceof Error ? error.message : "数据库连接失败";
|
||||
return { ok: false, reason };
|
||||
}
|
||||
}
|
||||
@@ -1,15 +1,97 @@
|
||||
import type { Permission, RoleDefinition, RoleId } from "@/modules/core/types";
|
||||
import { ROLE_LABELS } from "@/modules/core/types";
|
||||
import { and, eq, inArray, isNull, or } from "drizzle-orm";
|
||||
|
||||
export const ROLE_DEFINITIONS: RoleDefinition[] = [
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import { permissions, rolePermissions, roles } from "@/modules/core/server/schema";
|
||||
import type { Permission, RoleDefinition, RoleId } from "@/modules/core/types";
|
||||
import { PERMISSIONS, ROLE_LABELS } from "@/modules/core/types";
|
||||
|
||||
type PermissionDefinition = {
|
||||
id: Permission;
|
||||
label: string;
|
||||
category: string;
|
||||
description: string;
|
||||
};
|
||||
|
||||
export const PERMISSION_DEFINITIONS: PermissionDefinition[] = [
|
||||
{ id: "platform:manage", label: "平台管理", category: "平台", description: "管理平台级配置和跨机构操作。" },
|
||||
{ id: "organization:read", label: "查看机构", category: "机构", description: "查看机构、院区和租户信息。" },
|
||||
{ id: "organization:manage", label: "管理机构", category: "机构", description: "创建、编辑和停用机构。" },
|
||||
{ id: "account:read", label: "查看用户", category: "用户", description: "查看账号、成员和申请。" },
|
||||
{ id: "account:manage", label: "管理用户", category: "用户", description: "创建、审批、启停和分配用户。" },
|
||||
{ id: "role:read", label: "查看角色", category: "权限", description: "查看角色和权限矩阵。" },
|
||||
{ id: "role:manage", label: "管理角色", category: "权限", description: "创建自定义角色并配置权限组合。" },
|
||||
{ id: "permission:read", label: "查看权限", category: "权限", description: "查看系统注册权限点。" },
|
||||
{ id: "audit:read", label: "查看审计", category: "审计", description: "查看关键操作审计日志。" },
|
||||
{ id: "incident:read", label: "查看故障", category: "运维", description: "查看系统健康和故障中心。" },
|
||||
{ id: "incident:manage", label: "处理故障", category: "运维", description: "确认、处理和关闭故障事件。" },
|
||||
{ id: "facility:read", label: "查看房间床位", category: "床位", description: "查看房间、床位和占用状态。" },
|
||||
{ id: "facility:manage", label: "管理房间床位", category: "床位", description: "维护院区、房间、床位和床位状态。" },
|
||||
{ id: "admission:read", label: "查看入住", category: "入住", description: "查看入住、换床、退住历史。" },
|
||||
{ id: "admission:manage", label: "管理入住", category: "入住", description: "办理入住、换床和退住。" },
|
||||
{ id: "elder:read", label: "查看老人档案", category: "老人", description: "查看老人基础档案。" },
|
||||
{ id: "elder:create", label: "新增老人档案", category: "老人", description: "创建老人档案。" },
|
||||
{ id: "elder:update", label: "更新老人档案", category: "老人", description: "更新老人档案和照护信息。" },
|
||||
{ id: "elder:delete", label: "删除老人档案", category: "老人", description: "删除老人档案。" },
|
||||
];
|
||||
|
||||
type SeedRole = {
|
||||
key: RoleId;
|
||||
scope: "platform" | "organization";
|
||||
description: string;
|
||||
permissions: Permission[];
|
||||
};
|
||||
|
||||
export const SYSTEM_ROLE_DEFINITIONS: SeedRole[] = [
|
||||
{
|
||||
id: "admin",
|
||||
label: ROLE_LABELS.admin,
|
||||
description: "管理账号、权限、审计日志与全部业务数据。",
|
||||
key: "platform_admin",
|
||||
scope: "platform",
|
||||
description: "平台最高权限,管理所有机构、角色、审计和故障中心。",
|
||||
permissions: [...PERMISSIONS],
|
||||
},
|
||||
{
|
||||
key: "platform_operator",
|
||||
scope: "platform",
|
||||
description: "平台运营角色,管理机构和跨机构用户配置。",
|
||||
permissions: [
|
||||
"organization:read",
|
||||
"organization:manage",
|
||||
"account:read",
|
||||
"account:manage",
|
||||
"role:read",
|
||||
"permission:read",
|
||||
"audit:read",
|
||||
"incident:read",
|
||||
],
|
||||
},
|
||||
{
|
||||
key: "platform_auditor",
|
||||
scope: "platform",
|
||||
description: "平台审计角色,只读查看机构、审计和故障。",
|
||||
permissions: ["organization:read", "account:read", "role:read", "permission:read", "audit:read", "incident:read"],
|
||||
},
|
||||
{
|
||||
key: "platform_ops",
|
||||
scope: "platform",
|
||||
description: "平台运维角色,处理系统故障和运行状态。",
|
||||
permissions: ["organization:read", "audit:read", "incident:read", "incident:manage"],
|
||||
},
|
||||
{
|
||||
key: "org_admin",
|
||||
scope: "organization",
|
||||
description: "机构管理员,管理本机构用户、角色、房间床位、入住和审计。",
|
||||
permissions: [
|
||||
"organization:read",
|
||||
"account:read",
|
||||
"account:manage",
|
||||
"role:read",
|
||||
"role:manage",
|
||||
"permission:read",
|
||||
"audit:read",
|
||||
"incident:read",
|
||||
"facility:read",
|
||||
"facility:manage",
|
||||
"admission:read",
|
||||
"admission:manage",
|
||||
"elder:read",
|
||||
"elder:create",
|
||||
"elder:update",
|
||||
@@ -17,43 +99,160 @@ export const ROLE_DEFINITIONS: RoleDefinition[] = [
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "manager",
|
||||
label: ROLE_LABELS.manager,
|
||||
description: "处理运营业务,可查看账号与审计日志,不管理账号角色。",
|
||||
permissions: ["account:read", "audit:read", "elder:read", "elder:create", "elder:update", "elder:delete"],
|
||||
key: "manager",
|
||||
scope: "organization",
|
||||
description: "运营主管,处理老人档案、床位入住和审计查看。",
|
||||
permissions: [
|
||||
"account:read",
|
||||
"role:read",
|
||||
"audit:read",
|
||||
"facility:read",
|
||||
"facility:manage",
|
||||
"admission:read",
|
||||
"admission:manage",
|
||||
"elder:read",
|
||||
"elder:create",
|
||||
"elder:update",
|
||||
"elder:delete",
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "caregiver",
|
||||
label: ROLE_LABELS.caregiver,
|
||||
description: "查看老人档案并维护照护相关信息。",
|
||||
permissions: ["elder:read", "elder:update"],
|
||||
key: "caregiver",
|
||||
scope: "organization",
|
||||
description: "照护人员,查看床位和维护老人照护信息。",
|
||||
permissions: ["facility:read", "admission:read", "elder:read", "elder:update"],
|
||||
},
|
||||
{
|
||||
id: "viewer",
|
||||
label: ROLE_LABELS.viewer,
|
||||
description: "只读查看老人档案。",
|
||||
permissions: ["elder:read"],
|
||||
key: "viewer",
|
||||
scope: "organization",
|
||||
description: "只读访客,查看老人、床位和入住信息。",
|
||||
permissions: ["facility:read", "admission:read", "elder:read"],
|
||||
},
|
||||
];
|
||||
|
||||
export function getRoleDefinition(role: RoleId): RoleDefinition {
|
||||
const roleDefinition = ROLE_DEFINITIONS.find((item) => item.id === role);
|
||||
if (roleDefinition) {
|
||||
return roleDefinition;
|
||||
export async function ensureSystemDefaults(): Promise<void> {
|
||||
const database = getDatabase();
|
||||
|
||||
await database
|
||||
.insert(permissions)
|
||||
.values(PERMISSION_DEFINITIONS)
|
||||
.onConflictDoUpdate({
|
||||
target: permissions.id,
|
||||
set: {
|
||||
label: permissions.label,
|
||||
category: permissions.category,
|
||||
description: permissions.description,
|
||||
isEnabled: true,
|
||||
},
|
||||
});
|
||||
|
||||
const existingRoles = await database.select().from(roles).where(isNull(roles.organizationId));
|
||||
const existingRoleKeys = new Set(existingRoles.map((role) => role.key));
|
||||
const seedRoles = SYSTEM_ROLE_DEFINITIONS.filter((role) => role.scope === "platform" && !existingRoleKeys.has(role.key));
|
||||
|
||||
if (seedRoles.length > 0) {
|
||||
await database.insert(roles).values(
|
||||
seedRoles.map((role) => ({
|
||||
key: role.key,
|
||||
scope: role.scope,
|
||||
label: ROLE_LABELS[role.key],
|
||||
description: role.description,
|
||||
isSystem: true,
|
||||
isEnabled: true,
|
||||
})),
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
id: "viewer",
|
||||
label: ROLE_LABELS.viewer,
|
||||
description: "只读查看老人档案。",
|
||||
permissions: ["elder:read"],
|
||||
};
|
||||
const platformRoles = await database.select().from(roles).where(isNull(roles.organizationId));
|
||||
const inserts = platformRoles.flatMap((role) => {
|
||||
const definition = SYSTEM_ROLE_DEFINITIONS.find((item) => item.key === role.key);
|
||||
if (!definition) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return definition.permissions.map((permissionId) => ({
|
||||
roleId: role.id,
|
||||
permissionId,
|
||||
}));
|
||||
});
|
||||
|
||||
if (inserts.length > 0) {
|
||||
await database.insert(rolePermissions).values(inserts).onConflictDoNothing();
|
||||
}
|
||||
}
|
||||
|
||||
export function getPermissionsForRole(role: RoleId): Permission[] {
|
||||
return [...getRoleDefinition(role).permissions];
|
||||
export async function seedOrganizationRoles(organizationId: string): Promise<void> {
|
||||
const database = getDatabase();
|
||||
const organizationRoles = SYSTEM_ROLE_DEFINITIONS.filter((role) => role.scope === "organization");
|
||||
|
||||
await database
|
||||
.insert(roles)
|
||||
.values(
|
||||
organizationRoles.map((role) => ({
|
||||
key: role.key,
|
||||
organizationId,
|
||||
scope: role.scope,
|
||||
label: ROLE_LABELS[role.key],
|
||||
description: role.description,
|
||||
isSystem: true,
|
||||
isEnabled: true,
|
||||
})),
|
||||
)
|
||||
.onConflictDoNothing();
|
||||
|
||||
const seededRoles = await database
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(and(eq(roles.organizationId, organizationId), inArray(roles.key, organizationRoles.map((role) => role.key))));
|
||||
|
||||
const inserts = seededRoles.flatMap((role) => {
|
||||
const definition = SYSTEM_ROLE_DEFINITIONS.find((item) => item.key === role.key);
|
||||
if (!definition) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return definition.permissions.map((permissionId) => ({ roleId: role.id, permissionId }));
|
||||
});
|
||||
|
||||
if (inserts.length > 0) {
|
||||
await database.insert(rolePermissions).values(inserts).onConflictDoNothing();
|
||||
}
|
||||
}
|
||||
|
||||
export function hasPermission(role: RoleId, permission: Permission): boolean {
|
||||
return getRoleDefinition(role).permissions.includes(permission);
|
||||
export async function getRoleDefinitions(organizationId?: string): Promise<RoleDefinition[]> {
|
||||
const database = getDatabase();
|
||||
const rows = await database
|
||||
.select()
|
||||
.from(roles)
|
||||
.where(organizationId ? or(isNull(roles.organizationId), eq(roles.organizationId, organizationId)) : isNull(roles.organizationId));
|
||||
|
||||
const roleIds = rows.map((role) => role.id);
|
||||
const permissionRows =
|
||||
roleIds.length > 0
|
||||
? await database.select().from(rolePermissions).where(inArray(rolePermissions.roleId, roleIds))
|
||||
: [];
|
||||
|
||||
return rows.map((role) => ({
|
||||
id: role.id,
|
||||
key: role.key,
|
||||
label: role.label,
|
||||
description: role.description,
|
||||
scope: role.scope,
|
||||
organizationId: role.organizationId ?? undefined,
|
||||
isSystem: role.isSystem,
|
||||
isEnabled: role.isEnabled,
|
||||
permissions: permissionRows
|
||||
.filter((permission) => permission.roleId === role.id)
|
||||
.map((permission) => permission.permissionId as Permission),
|
||||
}));
|
||||
}
|
||||
|
||||
export async function getPermissionsForRole(roleId: string): Promise<Permission[]> {
|
||||
const database = getDatabase();
|
||||
const rows = await database.select().from(rolePermissions).where(eq(rolePermissions.roleId, roleId));
|
||||
return rows.map((row) => row.permissionId as Permission);
|
||||
}
|
||||
|
||||
export function hasPermission(permissionsList: readonly Permission[], permission: Permission): boolean {
|
||||
return permissionsList.includes(permission);
|
||||
}
|
||||
|
||||
227
modules/core/server/schema.ts
Normal file
227
modules/core/server/schema.ts
Normal file
@@ -0,0 +1,227 @@
|
||||
import {
|
||||
boolean,
|
||||
integer,
|
||||
pgEnum,
|
||||
pgTable,
|
||||
primaryKey,
|
||||
text,
|
||||
timestamp,
|
||||
uniqueIndex,
|
||||
uuid,
|
||||
} from "drizzle-orm/pg-core";
|
||||
|
||||
export const accountStatusEnum = pgEnum("account_status", ["active", "disabled", "pending"]);
|
||||
export const organizationStatusEnum = pgEnum("organization_status", ["active", "disabled"]);
|
||||
export const roleScopeEnum = pgEnum("role_scope", ["platform", "organization"]);
|
||||
export const membershipStatusEnum = pgEnum("membership_status", ["active", "disabled", "pending"]);
|
||||
export const bedStatusEnum = pgEnum("bed_status", ["available", "occupied", "maintenance", "disabled"]);
|
||||
export const elderStatusEnum = pgEnum("elder_status", ["active", "pending", "discharged"]);
|
||||
export const careLevelEnum = pgEnum("care_level", ["self-care", "semi-assisted", "assisted", "intensive"]);
|
||||
export const genderEnum = pgEnum("gender", ["male", "female", "other"]);
|
||||
export const admissionStatusEnum = pgEnum("admission_status", ["active", "transferred", "discharged"]);
|
||||
export const auditResultEnum = pgEnum("audit_result", ["success", "denied", "failure"]);
|
||||
export const incidentStatusEnum = pgEnum("incident_status", ["open", "acknowledged", "resolved", "closed"]);
|
||||
export const incidentSeverityEnum = pgEnum("incident_severity", ["info", "warning", "critical"]);
|
||||
export const joinRequestStatusEnum = pgEnum("join_request_status", ["pending", "approved", "rejected"]);
|
||||
|
||||
export const organizations = pgTable("organizations", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
name: text("name").notNull(),
|
||||
slug: text("slug").notNull(),
|
||||
status: organizationStatusEnum("status").notNull().default("active"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (table) => ({
|
||||
slugUnique: uniqueIndex("organizations_slug_unique").on(table.slug),
|
||||
}));
|
||||
|
||||
export const permissions = pgTable("permissions", {
|
||||
id: text("id").primaryKey(),
|
||||
label: text("label").notNull(),
|
||||
category: text("category").notNull(),
|
||||
description: text("description").notNull(),
|
||||
isEnabled: boolean("is_enabled").notNull().default(true),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const roles = pgTable("roles", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
key: text("key").notNull(),
|
||||
organizationId: uuid("organization_id").references(() => organizations.id, { onDelete: "cascade" }),
|
||||
scope: roleScopeEnum("scope").notNull(),
|
||||
label: text("label").notNull(),
|
||||
description: text("description").notNull(),
|
||||
isSystem: boolean("is_system").notNull().default(false),
|
||||
isEnabled: boolean("is_enabled").notNull().default(true),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (table) => ({
|
||||
roleKeyUnique: uniqueIndex("roles_key_organization_unique").on(table.key, table.organizationId),
|
||||
}));
|
||||
|
||||
export const rolePermissions = pgTable("role_permissions", {
|
||||
roleId: uuid("role_id").notNull().references(() => roles.id, { onDelete: "cascade" }),
|
||||
permissionId: text("permission_id").notNull().references(() => permissions.id, { onDelete: "cascade" }),
|
||||
}, (table) => ({
|
||||
pk: primaryKey({ columns: [table.roleId, table.permissionId] }),
|
||||
}));
|
||||
|
||||
export const accounts = pgTable("accounts", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
platformRoleId: uuid("platform_role_id").references(() => roles.id),
|
||||
name: text("name").notNull(),
|
||||
email: text("email").notNull(),
|
||||
passwordHash: text("password_hash").notNull(),
|
||||
passwordSalt: text("password_salt").notNull(),
|
||||
status: accountStatusEnum("status").notNull().default("active"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (table) => ({
|
||||
emailUnique: uniqueIndex("accounts_email_unique").on(table.email),
|
||||
}));
|
||||
|
||||
export const memberships = pgTable("memberships", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
accountId: uuid("account_id").notNull().references(() => accounts.id, { onDelete: "cascade" }),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
roleId: uuid("role_id").notNull().references(() => roles.id),
|
||||
status: membershipStatusEnum("status").notNull().default("active"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (table) => ({
|
||||
accountOrganizationUnique: uniqueIndex("memberships_account_organization_unique").on(
|
||||
table.accountId,
|
||||
table.organizationId,
|
||||
),
|
||||
}));
|
||||
|
||||
export const sessions = pgTable("sessions", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
accountId: uuid("account_id").notNull().references(() => accounts.id, { onDelete: "cascade" }),
|
||||
activeOrganizationId: uuid("active_organization_id").references(() => organizations.id),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
||||
});
|
||||
|
||||
export const joinRequests = pgTable("join_requests", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
accountId: uuid("account_id").notNull().references(() => accounts.id, { onDelete: "cascade" }),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
status: joinRequestStatusEnum("status").notNull().default("pending"),
|
||||
reason: text("reason").notNull().default(""),
|
||||
reviewedByAccountId: uuid("reviewed_by_account_id").references(() => accounts.id),
|
||||
reviewedAt: timestamp("reviewed_at", { withTimezone: true }),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const campuses = pgTable("campuses", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
address: text("address").notNull().default(""),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const buildings = pgTable("buildings", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
campusId: uuid("campus_id").notNull().references(() => campuses.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const floors = pgTable("floors", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
buildingId: uuid("building_id").notNull().references(() => buildings.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
level: integer("level").notNull(),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const rooms = pgTable("rooms", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
floorId: uuid("floor_id").notNull().references(() => floors.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
code: text("code").notNull(),
|
||||
capacity: integer("capacity").notNull().default(1),
|
||||
status: organizationStatusEnum("status").notNull().default("active"),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (table) => ({
|
||||
roomCodeUnique: uniqueIndex("rooms_code_organization_unique").on(table.organizationId, table.code),
|
||||
}));
|
||||
|
||||
export const beds = pgTable("beds", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
roomId: uuid("room_id").notNull().references(() => rooms.id, { onDelete: "cascade" }),
|
||||
code: text("code").notNull(),
|
||||
status: bedStatusEnum("status").notNull().default("available"),
|
||||
notes: text("notes").notNull().default(""),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
}, (table) => ({
|
||||
bedCodeUnique: uniqueIndex("beds_code_room_unique").on(table.roomId, table.code),
|
||||
}));
|
||||
|
||||
export const elders = pgTable("elders", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
name: text("name").notNull(),
|
||||
gender: genderEnum("gender").notNull(),
|
||||
age: integer("age").notNull(),
|
||||
careLevel: careLevelEnum("care_level").notNull(),
|
||||
status: elderStatusEnum("status").notNull().default("pending"),
|
||||
primaryContact: text("primary_contact").notNull(),
|
||||
phone: text("phone").notNull(),
|
||||
medicalNotes: text("medical_notes").notNull().default(""),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const admissions = pgTable("admissions", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").notNull().references(() => organizations.id, { onDelete: "cascade" }),
|
||||
elderId: uuid("elder_id").notNull().references(() => elders.id, { onDelete: "cascade" }),
|
||||
bedId: uuid("bed_id").notNull().references(() => beds.id),
|
||||
status: admissionStatusEnum("status").notNull().default("active"),
|
||||
admittedAt: timestamp("admitted_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
dischargedAt: timestamp("discharged_at", { withTimezone: true }),
|
||||
notes: text("notes").notNull().default(""),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
|
||||
export const auditLogs = pgTable("audit_logs", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").references(() => organizations.id, { onDelete: "cascade" }),
|
||||
timestamp: timestamp("timestamp", { withTimezone: true }).notNull().defaultNow(),
|
||||
actorAccountId: uuid("actor_account_id").references(() => accounts.id),
|
||||
actorEmail: text("actor_email"),
|
||||
action: text("action").notNull(),
|
||||
targetType: text("target_type").notNull(),
|
||||
targetId: text("target_id"),
|
||||
result: auditResultEnum("result").notNull(),
|
||||
reason: text("reason").notNull(),
|
||||
});
|
||||
|
||||
export const systemIncidents = pgTable("system_incidents", {
|
||||
id: uuid("id").primaryKey().defaultRandom(),
|
||||
organizationId: uuid("organization_id").references(() => organizations.id, { onDelete: "cascade" }),
|
||||
severity: incidentSeverityEnum("severity").notNull(),
|
||||
status: incidentStatusEnum("status").notNull().default("open"),
|
||||
title: text("title").notNull(),
|
||||
description: text("description").notNull(),
|
||||
source: text("source").notNull(),
|
||||
acknowledgedByAccountId: uuid("acknowledged_by_account_id").references(() => accounts.id),
|
||||
acknowledgedAt: timestamp("acknowledged_at", { withTimezone: true }),
|
||||
resolvedByAccountId: uuid("resolved_by_account_id").references(() => accounts.id),
|
||||
resolvedAt: timestamp("resolved_at", { withTimezone: true }),
|
||||
createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp("updated_at", { withTimezone: true }).notNull().defaultNow(),
|
||||
});
|
||||
@@ -1,63 +1,223 @@
|
||||
import { promises as fs } from "node:fs";
|
||||
import path from "node:path";
|
||||
import { desc, eq, sql } from "drizzle-orm";
|
||||
|
||||
import type { AppData } from "@/modules/core/types";
|
||||
import { listAuditLogs } from "@/modules/core/server/audit";
|
||||
import { getDatabase } from "@/modules/core/server/db";
|
||||
import {
|
||||
accounts,
|
||||
admissions,
|
||||
beds,
|
||||
elders,
|
||||
memberships,
|
||||
organizations,
|
||||
roles,
|
||||
rooms,
|
||||
sessions,
|
||||
systemIncidents,
|
||||
} from "@/modules/core/server/schema";
|
||||
import type { Account, Admission, AppData, FacilityBed, Membership, Organization, Room, Session, SystemIncident } from "@/modules/core/types";
|
||||
import type { Elder } from "@/modules/elders/types";
|
||||
|
||||
const DATA_DIR = process.env.TEATEA_DATA_DIR ?? path.join(process.cwd(), ".data");
|
||||
const DATA_FILE = path.join(DATA_DIR, "teatea.json");
|
||||
|
||||
function createEmptyData(): AppData {
|
||||
return {
|
||||
accounts: [],
|
||||
sessions: [],
|
||||
elders: [],
|
||||
auditLogs: [],
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeData(data: Partial<AppData>): AppData {
|
||||
return {
|
||||
accounts: Array.isArray(data.accounts) ? data.accounts : [],
|
||||
sessions: Array.isArray(data.sessions) ? data.sessions : [],
|
||||
elders: Array.isArray(data.elders) ? data.elders : [],
|
||||
auditLogs: Array.isArray(data.auditLogs) ? data.auditLogs : [],
|
||||
};
|
||||
}
|
||||
|
||||
function isMissingFileError(error: unknown): boolean {
|
||||
return (
|
||||
typeof error === "object" &&
|
||||
error !== null &&
|
||||
"code" in error &&
|
||||
(error as { code?: unknown }).code === "ENOENT"
|
||||
);
|
||||
function iso(value: Date): string {
|
||||
return value.toISOString();
|
||||
}
|
||||
|
||||
export async function readData(): Promise<AppData> {
|
||||
try {
|
||||
const raw = await fs.readFile(DATA_FILE, "utf8");
|
||||
const parsed = JSON.parse(raw) as Partial<AppData>;
|
||||
return normalizeData(parsed);
|
||||
} catch (error) {
|
||||
if (isMissingFileError(error)) {
|
||||
return createEmptyData();
|
||||
const database = getDatabase();
|
||||
const [
|
||||
organizationRows,
|
||||
accountRows,
|
||||
membershipRows,
|
||||
sessionRows,
|
||||
elderRows,
|
||||
roomRows,
|
||||
bedRows,
|
||||
admissionRows,
|
||||
auditLogRows,
|
||||
incidentRows,
|
||||
] = await Promise.all([
|
||||
database.select().from(organizations).orderBy(desc(organizations.createdAt)),
|
||||
database.select().from(accounts).orderBy(desc(accounts.createdAt)),
|
||||
database.select({ membership: memberships, role: roles }).from(memberships).innerJoin(roles, eq(roles.id, memberships.roleId)),
|
||||
database.select().from(sessions).orderBy(desc(sessions.createdAt)),
|
||||
database.select().from(elders).orderBy(desc(elders.createdAt)),
|
||||
database.select().from(rooms).orderBy(desc(rooms.createdAt)),
|
||||
database
|
||||
.select({
|
||||
bed: beds,
|
||||
roomName: rooms.name,
|
||||
currentElderName: sql<string | null>`(
|
||||
select ${elders.name}
|
||||
from ${admissions}
|
||||
inner join ${elders} on ${elders.id} = ${admissions.elderId}
|
||||
where ${admissions.bedId} = ${beds.id} and ${admissions.status} = 'active'
|
||||
limit 1
|
||||
)`,
|
||||
})
|
||||
.from(beds)
|
||||
.innerJoin(rooms, eq(rooms.id, beds.roomId))
|
||||
.orderBy(desc(beds.createdAt)),
|
||||
database
|
||||
.select({
|
||||
admission: admissions,
|
||||
elderName: elders.name,
|
||||
bedCode: beds.code,
|
||||
roomName: rooms.name,
|
||||
})
|
||||
.from(admissions)
|
||||
.innerJoin(elders, eq(elders.id, admissions.elderId))
|
||||
.innerJoin(beds, eq(beds.id, admissions.bedId))
|
||||
.innerJoin(rooms, eq(rooms.id, beds.roomId))
|
||||
.orderBy(desc(admissions.admittedAt)),
|
||||
listAuditLogs({ limit: 100 }),
|
||||
database.select().from(systemIncidents).orderBy(desc(systemIncidents.createdAt)),
|
||||
]);
|
||||
|
||||
const roleById = new Map(membershipRows.map((row) => [row.membership.id, row.role]));
|
||||
const bedCounts = new Map<string, { total: number; occupied: number }>();
|
||||
for (const row of bedRows) {
|
||||
const current = bedCounts.get(row.bed.roomId) ?? { total: 0, occupied: 0 };
|
||||
current.total += 1;
|
||||
if (row.bed.status === "occupied") {
|
||||
current.occupied += 1;
|
||||
}
|
||||
|
||||
throw error;
|
||||
bedCounts.set(row.bed.roomId, current);
|
||||
}
|
||||
|
||||
const organizationsData: Organization[] = organizationRows.map((row) => ({
|
||||
id: row.id,
|
||||
name: row.name,
|
||||
slug: row.slug,
|
||||
status: row.status,
|
||||
createdAt: iso(row.createdAt),
|
||||
updatedAt: iso(row.updatedAt),
|
||||
}));
|
||||
|
||||
const accountsData: Account[] = accountRows.map((row) => ({
|
||||
id: row.id,
|
||||
platformRoleId: row.platformRoleId ?? undefined,
|
||||
name: row.name,
|
||||
email: row.email,
|
||||
role: row.platformRoleId ?? "viewer",
|
||||
passwordHash: row.passwordHash,
|
||||
passwordSalt: row.passwordSalt,
|
||||
status: row.status,
|
||||
createdAt: iso(row.createdAt),
|
||||
updatedAt: iso(row.updatedAt),
|
||||
}));
|
||||
|
||||
const membershipsData: Membership[] = membershipRows.map((row) => {
|
||||
const role = roleById.get(row.membership.id) ?? row.role;
|
||||
return {
|
||||
id: row.membership.id,
|
||||
accountId: row.membership.accountId,
|
||||
organizationId: row.membership.organizationId,
|
||||
roleId: row.membership.roleId,
|
||||
roleKey: role.key,
|
||||
roleLabel: role.label,
|
||||
status: row.membership.status,
|
||||
createdAt: iso(row.membership.createdAt),
|
||||
updatedAt: iso(row.membership.updatedAt),
|
||||
};
|
||||
});
|
||||
|
||||
const sessionsData: Session[] = sessionRows.map((row) => ({
|
||||
id: row.id,
|
||||
accountId: row.accountId,
|
||||
activeOrganizationId: row.activeOrganizationId ?? undefined,
|
||||
createdAt: iso(row.createdAt),
|
||||
expiresAt: iso(row.expiresAt),
|
||||
}));
|
||||
|
||||
const eldersData: Elder[] = elderRows.map((row) => ({
|
||||
id: row.id,
|
||||
organizationId: row.organizationId,
|
||||
name: row.name,
|
||||
gender: row.gender,
|
||||
age: row.age,
|
||||
careLevel: row.careLevel,
|
||||
room: "",
|
||||
bed: "",
|
||||
status: row.status,
|
||||
primaryContact: row.primaryContact,
|
||||
phone: row.phone,
|
||||
medicalNotes: row.medicalNotes,
|
||||
createdAt: iso(row.createdAt),
|
||||
updatedAt: iso(row.updatedAt),
|
||||
}));
|
||||
|
||||
const roomsData: Room[] = roomRows.map((row) => {
|
||||
const counts = bedCounts.get(row.id) ?? { total: 0, occupied: 0 };
|
||||
return {
|
||||
id: row.id,
|
||||
organizationId: row.organizationId,
|
||||
name: row.name,
|
||||
code: row.code,
|
||||
capacity: row.capacity,
|
||||
status: row.status,
|
||||
bedCount: counts.total,
|
||||
occupiedBedCount: counts.occupied,
|
||||
createdAt: iso(row.createdAt),
|
||||
updatedAt: iso(row.updatedAt),
|
||||
};
|
||||
});
|
||||
|
||||
const bedsData: FacilityBed[] = bedRows.map((row) => ({
|
||||
id: row.bed.id,
|
||||
organizationId: row.bed.organizationId,
|
||||
roomId: row.bed.roomId,
|
||||
roomName: row.roomName,
|
||||
code: row.bed.code,
|
||||
status: row.bed.status,
|
||||
notes: row.bed.notes,
|
||||
currentElderName: row.currentElderName ?? undefined,
|
||||
createdAt: iso(row.bed.createdAt),
|
||||
updatedAt: iso(row.bed.updatedAt),
|
||||
}));
|
||||
|
||||
const admissionsData: Admission[] = admissionRows.map((row) => ({
|
||||
id: row.admission.id,
|
||||
organizationId: row.admission.organizationId,
|
||||
elderId: row.admission.elderId,
|
||||
elderName: row.elderName,
|
||||
bedId: row.admission.bedId,
|
||||
bedCode: row.bedCode,
|
||||
roomName: row.roomName,
|
||||
status: row.admission.status,
|
||||
admittedAt: iso(row.admission.admittedAt),
|
||||
dischargedAt: row.admission.dischargedAt ? iso(row.admission.dischargedAt) : undefined,
|
||||
notes: row.admission.notes,
|
||||
}));
|
||||
|
||||
const incidentsData: SystemIncident[] = incidentRows.map((row) => ({
|
||||
id: row.id,
|
||||
organizationId: row.organizationId ?? undefined,
|
||||
severity: row.severity,
|
||||
status: row.status,
|
||||
title: row.title,
|
||||
description: row.description,
|
||||
source: row.source,
|
||||
createdAt: iso(row.createdAt),
|
||||
updatedAt: iso(row.updatedAt),
|
||||
}));
|
||||
|
||||
return {
|
||||
organizations: organizationsData,
|
||||
accounts: accountsData,
|
||||
memberships: membershipsData,
|
||||
sessions: sessionsData,
|
||||
elders: eldersData,
|
||||
rooms: roomsData,
|
||||
beds: bedsData,
|
||||
admissions: admissionsData,
|
||||
auditLogs: auditLogRows,
|
||||
incidents: incidentsData,
|
||||
};
|
||||
}
|
||||
|
||||
export async function writeData(data: AppData): Promise<void> {
|
||||
await fs.mkdir(DATA_DIR, { recursive: true });
|
||||
const temporaryFile = `${DATA_FILE}.tmp`;
|
||||
await fs.writeFile(temporaryFile, JSON.stringify(data, null, 2), "utf8");
|
||||
await fs.rename(temporaryFile, DATA_FILE);
|
||||
export async function writeData(): Promise<void> {
|
||||
throw new Error("writeData is not available after PostgreSQL migration");
|
||||
}
|
||||
|
||||
export async function updateData<T>(mutator: (data: AppData) => T): Promise<T> {
|
||||
const data = await readData();
|
||||
const result = mutator(data);
|
||||
await writeData(data);
|
||||
return result;
|
||||
export async function updateData<T>(): Promise<T> {
|
||||
throw new Error("updateData is not available after PostgreSQL migration");
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,44 @@
|
||||
import type { Elder } from "@/modules/elders/types";
|
||||
|
||||
export const ROLE_IDS = ["admin", "manager", "caregiver", "viewer"] as const;
|
||||
export const ROLE_IDS = [
|
||||
"platform_admin",
|
||||
"platform_operator",
|
||||
"platform_auditor",
|
||||
"platform_ops",
|
||||
"org_admin",
|
||||
"manager",
|
||||
"caregiver",
|
||||
"viewer",
|
||||
] as const;
|
||||
export type RoleId = (typeof ROLE_IDS)[number];
|
||||
|
||||
export const ROLE_LABELS: Record<RoleId, string> = {
|
||||
admin: "系统管理员",
|
||||
platform_admin: "平台超管",
|
||||
platform_operator: "平台运营",
|
||||
platform_auditor: "平台审计",
|
||||
platform_ops: "平台运维",
|
||||
org_admin: "机构管理员",
|
||||
manager: "运营主管",
|
||||
caregiver: "照护人员",
|
||||
viewer: "只读访客",
|
||||
};
|
||||
|
||||
export const PERMISSIONS = [
|
||||
"platform:manage",
|
||||
"organization:read",
|
||||
"organization:manage",
|
||||
"account:read",
|
||||
"account:manage",
|
||||
"role:read",
|
||||
"role:manage",
|
||||
"permission:read",
|
||||
"audit:read",
|
||||
"incident:read",
|
||||
"incident:manage",
|
||||
"facility:read",
|
||||
"facility:manage",
|
||||
"admission:read",
|
||||
"admission:manage",
|
||||
"elder:read",
|
||||
"elder:create",
|
||||
"elder:update",
|
||||
@@ -23,20 +48,52 @@ export const PERMISSIONS = [
|
||||
export type Permission = (typeof PERMISSIONS)[number];
|
||||
|
||||
export type RoleDefinition = {
|
||||
id: RoleId;
|
||||
id: string;
|
||||
key: RoleId | string;
|
||||
label: string;
|
||||
description: string;
|
||||
scope: "platform" | "organization";
|
||||
organizationId?: string;
|
||||
isSystem: boolean;
|
||||
isEnabled: boolean;
|
||||
permissions: Permission[];
|
||||
};
|
||||
|
||||
export type AccountStatus = "active" | "disabled";
|
||||
export type AccountStatus = "active" | "disabled" | "pending";
|
||||
|
||||
export type OrganizationStatus = "active" | "disabled";
|
||||
|
||||
export type Organization = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
status: OrganizationStatus;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type MembershipStatus = "active" | "disabled" | "pending";
|
||||
|
||||
export type Membership = {
|
||||
id: string;
|
||||
accountId: string;
|
||||
organizationId: string;
|
||||
roleId: string;
|
||||
roleKey: string;
|
||||
roleLabel: string;
|
||||
status: MembershipStatus;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type Account = {
|
||||
id: string;
|
||||
platformRoleId?: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: RoleId;
|
||||
role: RoleId | string;
|
||||
organization?: string;
|
||||
organizationId?: string;
|
||||
passwordHash: string;
|
||||
passwordSalt: string;
|
||||
status: AccountStatus;
|
||||
@@ -49,6 +106,7 @@ export type PublicAccount = Omit<Account, "passwordHash" | "passwordSalt">;
|
||||
export type Session = {
|
||||
id: string;
|
||||
accountId: string;
|
||||
activeOrganizationId?: string;
|
||||
createdAt: string;
|
||||
expiresAt: string;
|
||||
};
|
||||
@@ -57,6 +115,7 @@ export type AuditResult = "success" | "denied" | "failure";
|
||||
|
||||
export type AuditLog = {
|
||||
id: string;
|
||||
organizationId?: string;
|
||||
timestamp: string;
|
||||
actorAccountId?: string;
|
||||
actorEmail?: string;
|
||||
@@ -67,16 +126,82 @@ export type AuditLog = {
|
||||
reason: string;
|
||||
};
|
||||
|
||||
export type BedStatus = "available" | "occupied" | "maintenance" | "disabled";
|
||||
|
||||
export type FacilityBed = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
roomId: string;
|
||||
roomName: string;
|
||||
code: string;
|
||||
status: BedStatus;
|
||||
notes: string;
|
||||
currentElderName?: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type Room = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
name: string;
|
||||
code: string;
|
||||
capacity: number;
|
||||
status: OrganizationStatus;
|
||||
bedCount: number;
|
||||
occupiedBedCount: number;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type AdmissionStatus = "active" | "transferred" | "discharged";
|
||||
|
||||
export type Admission = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
elderId: string;
|
||||
elderName: string;
|
||||
bedId: string;
|
||||
bedCode: string;
|
||||
roomName: string;
|
||||
status: AdmissionStatus;
|
||||
admittedAt: string;
|
||||
dischargedAt?: string;
|
||||
notes: string;
|
||||
};
|
||||
|
||||
export type IncidentSeverity = "info" | "warning" | "critical";
|
||||
export type IncidentStatus = "open" | "acknowledged" | "resolved" | "closed";
|
||||
|
||||
export type SystemIncident = {
|
||||
id: string;
|
||||
organizationId?: string;
|
||||
severity: IncidentSeverity;
|
||||
status: IncidentStatus;
|
||||
title: string;
|
||||
description: string;
|
||||
source: string;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
};
|
||||
|
||||
export type AppData = {
|
||||
organizations: Organization[];
|
||||
accounts: Account[];
|
||||
memberships: Membership[];
|
||||
sessions: Session[];
|
||||
elders: Elder[];
|
||||
rooms: Room[];
|
||||
beds: FacilityBed[];
|
||||
admissions: Admission[];
|
||||
auditLogs: AuditLog[];
|
||||
incidents: SystemIncident[];
|
||||
};
|
||||
|
||||
export type AuthContext = {
|
||||
account: PublicAccount;
|
||||
organization?: Organization;
|
||||
membership?: Membership;
|
||||
permissions: Permission[];
|
||||
session: Session;
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user